3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * moodlelib.php - Moodle main library
21 * Main library file of miscellaneous general-purpose Moodle functions.
22 * Other main libraries:
23 * - weblib.php - functions that produce web output
24 * - datalib.php - functions that access the database
28 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32 defined('MOODLE_INTERNAL') || die();
34 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
36 /// Date and time constants ///
38 * Time constant - the number of seconds in a year
40 define('YEARSECS', 31536000);
43 * Time constant - the number of seconds in a week
45 define('WEEKSECS', 604800);
48 * Time constant - the number of seconds in a day
50 define('DAYSECS', 86400);
53 * Time constant - the number of seconds in an hour
55 define('HOURSECS', 3600);
58 * Time constant - the number of seconds in a minute
60 define('MINSECS', 60);
63 * Time constant - the number of minutes in a day
65 define('DAYMINS', 1440);
68 * Time constant - the number of minutes in an hour
70 define('HOURMINS', 60);
72 /// Parameter constants - every call to optional_param(), required_param() ///
73 /// or clean_param() should have a specified type of parameter. //////////////
78 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
80 define('PARAM_ALPHA', 'alpha');
83 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
84 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
86 define('PARAM_ALPHAEXT', 'alphaext');
89 * PARAM_ALPHANUM - expected numbers and letters only.
91 define('PARAM_ALPHANUM', 'alphanum');
94 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
96 define('PARAM_ALPHANUMEXT', 'alphanumext');
99 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
101 define('PARAM_AUTH', 'auth');
104 * PARAM_BASE64 - Base 64 encoded format
106 define('PARAM_BASE64', 'base64');
109 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
111 define('PARAM_BOOL', 'bool');
114 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
115 * checked against the list of capabilities in the database.
117 define('PARAM_CAPABILITY', 'capability');
120 * PARAM_CLEANHTML - cleans submitted HTML code. use only for text in HTML format. This cleaning may fix xhtml strictness too.
122 define('PARAM_CLEANHTML', 'cleanhtml');
125 * PARAM_EMAIL - an email address following the RFC
127 define('PARAM_EMAIL', 'email');
130 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
132 define('PARAM_FILE', 'file');
135 * PARAM_FLOAT - a real/floating point number.
137 define('PARAM_FLOAT', 'float');
140 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
142 define('PARAM_HOST', 'host');
145 * PARAM_INT - integers only, use when expecting only numbers.
147 define('PARAM_INT', 'int');
150 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
152 define('PARAM_LANG', 'lang');
155 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
157 define('PARAM_LOCALURL', 'localurl');
160 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
162 define('PARAM_NOTAGS', 'notags');
165 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
166 * note: the leading slash is not removed, window drive letter is not allowed
168 define('PARAM_PATH', 'path');
171 * PARAM_PEM - Privacy Enhanced Mail format
173 define('PARAM_PEM', 'pem');
176 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
178 define('PARAM_PERMISSION', 'permission');
181 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
183 define('PARAM_RAW', 'raw');
186 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
188 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
191 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
193 define('PARAM_SAFEDIR', 'safedir');
196 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
198 define('PARAM_SAFEPATH', 'safepath');
201 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
203 define('PARAM_SEQUENCE', 'sequence');
206 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
208 define('PARAM_TAG', 'tag');
211 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
213 define('PARAM_TAGLIST', 'taglist');
216 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
218 define('PARAM_TEXT', 'text');
221 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
223 define('PARAM_THEME', 'theme');
226 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
228 define('PARAM_URL', 'url');
231 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user accounts, do NOT use when syncing with external systems!!
233 define('PARAM_USERNAME', 'username');
236 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
238 define('PARAM_STRINGID', 'stringid');
240 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
242 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
243 * It was one of the first types, that is why it is abused so much ;-)
244 * @deprecated since 2.0
246 define('PARAM_CLEAN', 'clean');
249 * PARAM_INTEGER - deprecated alias for PARAM_INT
251 define('PARAM_INTEGER', 'int');
254 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
256 define('PARAM_NUMBER', 'float');
259 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
260 * NOTE: originally alias for PARAM_APLHA
262 define('PARAM_ACTION', 'alphanumext');
265 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
266 * NOTE: originally alias for PARAM_APLHA
268 define('PARAM_FORMAT', 'alphanumext');
271 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
273 define('PARAM_MULTILANG', 'text');
276 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
277 * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
278 * America/Port-au-Prince)
280 define('PARAM_TIMEZONE', 'timezone');
283 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
285 define('PARAM_CLEANFILE', 'file');
290 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
292 define('VALUE_REQUIRED', 1);
295 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
297 define('VALUE_OPTIONAL', 2);
300 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
302 define('VALUE_DEFAULT', 0);
305 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
307 define('NULL_NOT_ALLOWED', false);
310 * NULL_ALLOWED - the parameter can be set to null in the database
312 define('NULL_ALLOWED', true);
316 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
318 define('PAGE_COURSE_VIEW', 'course-view');
320 /** Get remote addr constant */
321 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
322 /** Get remote addr constant */
323 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
325 /// Blog access level constant declaration ///
326 define ('BLOG_USER_LEVEL', 1);
327 define ('BLOG_GROUP_LEVEL', 2);
328 define ('BLOG_COURSE_LEVEL', 3);
329 define ('BLOG_SITE_LEVEL', 4);
330 define ('BLOG_GLOBAL_LEVEL', 5);
335 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
336 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
337 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
339 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
341 define('TAG_MAX_LENGTH', 50);
343 /// Password policy constants ///
344 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
345 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
346 define ('PASSWORD_DIGITS', '0123456789');
347 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
349 /// Feature constants ///
350 // Used for plugin_supports() to report features that are, or are not, supported by a module.
352 /** True if module can provide a grade */
353 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
354 /** True if module supports outcomes */
355 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
357 /** True if module has code to track whether somebody viewed it */
358 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
359 /** True if module has custom completion rules */
360 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
362 /** True if module has no 'view' page (like label) */
363 define('FEATURE_NO_VIEW_LINK', 'viewlink');
364 /** True if module supports outcomes */
365 define('FEATURE_IDNUMBER', 'idnumber');
366 /** True if module supports groups */
367 define('FEATURE_GROUPS', 'groups');
368 /** True if module supports groupings */
369 define('FEATURE_GROUPINGS', 'groupings');
370 /** True if module supports groupmembersonly */
371 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
373 /** Type of module */
374 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
375 /** True if module supports intro editor */
376 define('FEATURE_MOD_INTRO', 'mod_intro');
377 /** True if module has default completion */
378 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
380 define('FEATURE_COMMENT', 'comment');
382 define('FEATURE_RATE', 'rate');
383 /** True if module supports backup/restore of moodle2 format */
384 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
386 /** True if module can show description on course main page */
387 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
389 /** Unspecified module archetype */
390 define('MOD_ARCHETYPE_OTHER', 0);
391 /** Resource-like type module */
392 define('MOD_ARCHETYPE_RESOURCE', 1);
393 /** Assignment module archetype */
394 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
397 * Security token used for allowing access
398 * from external application such as web services.
399 * Scripts do not use any session, performance is relatively
400 * low because we need to load access info in each request.
401 * Scripts are executed in parallel.
403 define('EXTERNAL_TOKEN_PERMANENT', 0);
406 * Security token used for allowing access
407 * of embedded applications, the code is executed in the
408 * active user session. Token is invalidated after user logs out.
409 * Scripts are executed serially - normal session locking is used.
411 define('EXTERNAL_TOKEN_EMBEDDED', 1);
414 * The home page should be the site home
416 define('HOMEPAGE_SITE', 0);
418 * The home page should be the users my page
420 define('HOMEPAGE_MY', 1);
422 * The home page can be chosen by the user
424 define('HOMEPAGE_USER', 2);
427 * Hub directory url (should be moodle.org)
429 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
433 * Moodle.org url (should be moodle.org)
435 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
438 * Moodle mobile app service name
440 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
442 /// PARAMETER HANDLING ////////////////////////////////////////////////////
445 * Returns a particular value for the named variable, taken from
446 * POST or GET. If the parameter doesn't exist then an error is
447 * thrown because we require this variable.
449 * This function should be used to initialise all required values
450 * in a script that are based on parameters. Usually it will be
452 * $id = required_param('id', PARAM_INT);
454 * Please note the $type parameter is now required and the value can not be array.
456 * @param string $parname the name of the page parameter we want
457 * @param string $type expected type of parameter
460 function required_param($parname, $type) {
461 if (func_num_args() != 2 or empty($parname) or empty($type)) {
462 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
464 if (isset($_POST[$parname])) { // POST has precedence
465 $param = $_POST[$parname];
466 } else if (isset($_GET[$parname])) {
467 $param = $_GET[$parname];
469 print_error('missingparam', '', '', $parname);
472 if (is_array($param)) {
473 debugging('Invalid array parameter detected in required_param(): '.$parname);
474 // TODO: switch to fatal error in Moodle 2.3
475 //print_error('missingparam', '', '', $parname);
476 return required_param_array($parname, $type);
479 return clean_param($param, $type);
483 * Returns a particular array value for the named variable, taken from
484 * POST or GET. If the parameter doesn't exist then an error is
485 * thrown because we require this variable.
487 * This function should be used to initialise all required values
488 * in a script that are based on parameters. Usually it will be
490 * $ids = required_param_array('ids', PARAM_INT);
492 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
494 * @param string $parname the name of the page parameter we want
495 * @param string $type expected type of parameter
498 function required_param_array($parname, $type) {
499 if (func_num_args() != 2 or empty($parname) or empty($type)) {
500 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
502 if (isset($_POST[$parname])) { // POST has precedence
503 $param = $_POST[$parname];
504 } else if (isset($_GET[$parname])) {
505 $param = $_GET[$parname];
507 print_error('missingparam', '', '', $parname);
509 if (!is_array($param)) {
510 print_error('missingparam', '', '', $parname);
514 foreach($param as $key=>$value) {
515 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
516 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
519 $result[$key] = clean_param($value, $type);
526 * Returns a particular value for the named variable, taken from
527 * POST or GET, otherwise returning a given default.
529 * This function should be used to initialise all optional values
530 * in a script that are based on parameters. Usually it will be
532 * $name = optional_param('name', 'Fred', PARAM_TEXT);
534 * Please note the $type parameter is now required and the value can not be array.
536 * @param string $parname the name of the page parameter we want
537 * @param mixed $default the default value to return if nothing is found
538 * @param string $type expected type of parameter
541 function optional_param($parname, $default, $type) {
542 if (func_num_args() != 3 or empty($parname) or empty($type)) {
543 throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
545 if (!isset($default)) {
549 if (isset($_POST[$parname])) { // POST has precedence
550 $param = $_POST[$parname];
551 } else if (isset($_GET[$parname])) {
552 $param = $_GET[$parname];
557 if (is_array($param)) {
558 debugging('Invalid array parameter detected in required_param(): '.$parname);
559 // TODO: switch to $default in Moodle 2.3
561 return optional_param_array($parname, $default, $type);
564 return clean_param($param, $type);
568 * Returns a particular array value for the named variable, taken from
569 * POST or GET, otherwise returning a given default.
571 * This function should be used to initialise all optional values
572 * in a script that are based on parameters. Usually it will be
574 * $ids = optional_param('id', array(), PARAM_INT);
576 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
578 * @param string $parname the name of the page parameter we want
579 * @param mixed $default the default value to return if nothing is found
580 * @param string $type expected type of parameter
583 function optional_param_array($parname, $default, $type) {
584 if (func_num_args() != 3 or empty($parname) or empty($type)) {
585 throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
588 if (isset($_POST[$parname])) { // POST has precedence
589 $param = $_POST[$parname];
590 } else if (isset($_GET[$parname])) {
591 $param = $_GET[$parname];
595 if (!is_array($param)) {
596 debugging('optional_param_array() expects array parameters only: '.$parname);
601 foreach($param as $key=>$value) {
602 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
603 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
606 $result[$key] = clean_param($value, $type);
613 * Strict validation of parameter values, the values are only converted
614 * to requested PHP type. Internally it is using clean_param, the values
615 * before and after cleaning must be equal - otherwise
616 * an invalid_parameter_exception is thrown.
617 * Objects and classes are not accepted.
619 * @param mixed $param
620 * @param string $type PARAM_ constant
621 * @param bool $allownull are nulls valid value?
622 * @param string $debuginfo optional debug information
623 * @return mixed the $param value converted to PHP type or invalid_parameter_exception
625 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
626 if (is_null($param)) {
627 if ($allownull == NULL_ALLOWED) {
630 throw new invalid_parameter_exception($debuginfo);
633 if (is_array($param) or is_object($param)) {
634 throw new invalid_parameter_exception($debuginfo);
637 $cleaned = clean_param($param, $type);
638 if ((string)$param !== (string)$cleaned) {
639 // conversion to string is usually lossless
640 throw new invalid_parameter_exception($debuginfo);
647 * Makes sure array contains only the allowed types,
648 * this function does not validate array key names!
650 * $options = clean_param($options, PARAM_INT);
653 * @param array $param the variable array we are cleaning
654 * @param string $type expected format of param after cleaning.
655 * @param bool $recursive clean recursive arrays
658 function clean_param_array(array $param = null, $type, $recursive = false) {
659 $param = (array)$param; // convert null to empty array
660 foreach ($param as $key => $value) {
661 if (is_array($value)) {
663 $param[$key] = clean_param_array($value, $type, true);
665 throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
668 $param[$key] = clean_param($value, $type);
675 * Used by {@link optional_param()} and {@link required_param()} to
676 * clean the variables and/or cast to specific types, based on
679 * $course->format = clean_param($course->format, PARAM_ALPHA);
680 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
683 * @param mixed $param the variable we are cleaning
684 * @param string $type expected format of param after cleaning.
687 function clean_param($param, $type) {
691 if (is_array($param)) {
692 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
693 } else if (is_object($param)) {
694 if (method_exists($param, '__toString')) {
695 $param = $param->__toString();
697 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
702 case PARAM_RAW: // no cleaning at all
703 $param = fix_utf8($param);
706 case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
707 $param = fix_utf8($param);
710 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
711 // this is deprecated!, please use more specific type instead
712 if (is_numeric($param)) {
715 $param = fix_utf8($param);
716 return clean_text($param); // Sweep for scripts, etc
718 case PARAM_CLEANHTML: // clean html fragment
719 $param = fix_utf8($param);
720 $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
724 return (int)$param; // Convert to integer
728 return (float)$param; // Convert to float
730 case PARAM_ALPHA: // Remove everything not a-z
731 return preg_replace('/[^a-zA-Z]/i', '', $param);
733 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
734 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
736 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
737 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
739 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
740 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
742 case PARAM_SEQUENCE: // Remove everything not 0-9,
743 return preg_replace('/[^0-9,]/i', '', $param);
745 case PARAM_BOOL: // Convert to 1 or 0
746 $tempstr = strtolower($param);
747 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
749 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
752 $param = empty($param) ? 0 : 1;
756 case PARAM_NOTAGS: // Strip all tags
757 $param = fix_utf8($param);
758 return strip_tags($param);
760 case PARAM_TEXT: // leave only tags needed for multilang
761 $param = fix_utf8($param);
762 // if the multilang syntax is not correct we strip all tags
763 // because it would break xhtml strict which is required for accessibility standards
764 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
766 if (strpos($param, '</lang>') !== false) {
767 // old and future mutilang syntax
768 $param = strip_tags($param, '<lang>');
769 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
773 foreach ($matches[0] as $match) {
774 if ($match === '</lang>') {
782 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
793 } else if (strpos($param, '</span>') !== false) {
794 // current problematic multilang syntax
795 $param = strip_tags($param, '<span>');
796 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
800 foreach ($matches[0] as $match) {
801 if ($match === '</span>') {
809 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
821 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
822 return strip_tags($param);
824 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
825 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
827 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
828 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
830 case PARAM_FILE: // Strip all suspicious characters from filename
831 $param = fix_utf8($param);
832 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
833 $param = preg_replace('~\.\.+~', '', $param);
834 if ($param === '.') {
839 case PARAM_PATH: // Strip all suspicious characters from file path
840 $param = fix_utf8($param);
841 $param = str_replace('\\', '/', $param);
842 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
843 $param = preg_replace('~\.\.+~', '', $param);
844 $param = preg_replace('~//+~', '/', $param);
845 return preg_replace('~/(\./)+~', '/', $param);
847 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
848 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
849 // match ipv4 dotted quad
850 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
851 // confirm values are ok
855 || $match[4] > 255 ) {
856 // hmmm, what kind of dotted quad is this?
859 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
860 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
861 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
863 // all is ok - $param is respected
870 case PARAM_URL: // allow safe ftp, http, mailto urls
871 $param = fix_utf8($param);
872 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
873 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
874 // all is ok, param is respected
876 $param =''; // not really ok
880 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
881 $param = clean_param($param, PARAM_URL);
882 if (!empty($param)) {
883 if (preg_match(':^/:', $param)) {
884 // root-relative, ok!
885 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
886 // absolute, and matches our wwwroot
888 // relative - let's make sure there are no tricks
889 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
899 $param = trim($param);
900 // PEM formatted strings may contain letters/numbers and the symbols
904 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
905 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
906 list($wholething, $body) = $matches;
907 unset($wholething, $matches);
908 $b64 = clean_param($body, PARAM_BASE64);
910 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
918 if (!empty($param)) {
919 // PEM formatted strings may contain letters/numbers and the symbols
923 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
926 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
927 // Each line of base64 encoded data must be 64 characters in
928 // length, except for the last line which may be less than (or
929 // equal to) 64 characters long.
930 for ($i=0, $j=count($lines); $i < $j; $i++) {
932 if (64 < strlen($lines[$i])) {
938 if (64 != strlen($lines[$i])) {
942 return implode("\n",$lines);
948 $param = fix_utf8($param);
949 // Please note it is not safe to use the tag name directly anywhere,
950 // it must be processed with s(), urlencode() before embedding anywhere.
951 // remove some nasties
952 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
953 //convert many whitespace chars into one
954 $param = preg_replace('/\s+/', ' ', $param);
955 $textlib = textlib_get_instance();
956 $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
960 $param = fix_utf8($param);
961 $tags = explode(',', $param);
963 foreach ($tags as $tag) {
964 $res = clean_param($tag, PARAM_TAG);
970 return implode(',', $result);
975 case PARAM_CAPABILITY:
976 if (get_capability_info($param)) {
982 case PARAM_PERMISSION:
983 $param = (int)$param;
984 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
991 $param = clean_param($param, PARAM_SAFEDIR);
992 if (exists_auth_plugin($param)) {
999 $param = clean_param($param, PARAM_SAFEDIR);
1000 if (get_string_manager()->translation_exists($param)) {
1003 return ''; // Specified language is not installed or param malformed
1007 $param = clean_param($param, PARAM_SAFEDIR);
1008 if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1010 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1013 return ''; // Specified theme is not installed
1016 case PARAM_USERNAME:
1017 $param = fix_utf8($param);
1018 $param = str_replace(" " , "", $param);
1019 $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
1020 if (empty($CFG->extendedusernamechars)) {
1021 // regular expression, eliminate all chars EXCEPT:
1022 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1023 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1028 $param = fix_utf8($param);
1029 if (validate_email($param)) {
1035 case PARAM_STRINGID:
1036 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1042 case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1043 $param = fix_utf8($param);
1044 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1045 if (preg_match($timezonepattern, $param)) {
1051 default: // throw error, switched parameters in optional_param or another serious problem
1052 print_error("unknownparamtype", '', '', $type);
1057 * Makes sure the data is using valid utf8, invalid characters are discarded.
1059 * Note: this function is not intended for full objects with methods and private properties.
1061 * @param mixed $value
1062 * @return mixed with proper utf-8 encoding
1064 function fix_utf8($value) {
1065 if (is_null($value) or $value === '') {
1068 } else if (is_string($value)) {
1069 if ((string)(int)$value === $value) {
1073 return iconv('UTF-8', 'UTF-8//IGNORE', $value);
1075 } else if (is_array($value)) {
1076 foreach ($value as $k=>$v) {
1077 $value[$k] = fix_utf8($v);
1081 } else if (is_object($value)) {
1082 $value = clone($value); // do not modify original
1083 foreach ($value as $k=>$v) {
1084 $value->$k = fix_utf8($v);
1089 // this is some other type, no utf-8 here
1095 * Return true if given value is integer or string with integer value
1097 * @param mixed $value String or Int
1098 * @return bool true if number, false if not
1100 function is_number($value) {
1101 if (is_int($value)) {
1103 } else if (is_string($value)) {
1104 return ((string)(int)$value) === $value;
1111 * Returns host part from url
1112 * @param string $url full url
1113 * @return string host, null if not found
1115 function get_host_from_url($url) {
1116 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1124 * Tests whether anything was returned by text editor
1126 * This function is useful for testing whether something you got back from
1127 * the HTML editor actually contains anything. Sometimes the HTML editor
1128 * appear to be empty, but actually you get back a <br> tag or something.
1130 * @param string $string a string containing HTML.
1131 * @return boolean does the string contain any actual content - that is text,
1132 * images, objects, etc.
1134 function html_is_blank($string) {
1135 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1139 * Set a key in global configuration
1141 * Set a key/value pair in both this session's {@link $CFG} global variable
1142 * and in the 'config' database table for future sessions.
1144 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1145 * In that case it doesn't affect $CFG.
1147 * A NULL value will delete the entry.
1151 * @param string $name the key to set
1152 * @param string $value the value to set (without magic quotes)
1153 * @param string $plugin (optional) the plugin scope, default NULL
1154 * @return bool true or exception
1156 function set_config($name, $value, $plugin=NULL) {
1159 if (empty($plugin)) {
1160 if (!array_key_exists($name, $CFG->config_php_settings)) {
1161 // So it's defined for this invocation at least
1162 if (is_null($value)) {
1165 $CFG->$name = (string)$value; // settings from db are always strings
1169 if ($DB->get_field('config', 'name', array('name'=>$name))) {
1170 if ($value === null) {
1171 $DB->delete_records('config', array('name'=>$name));
1173 $DB->set_field('config', 'value', $value, array('name'=>$name));
1176 if ($value !== null) {
1177 $config = new stdClass();
1178 $config->name = $name;
1179 $config->value = $value;
1180 $DB->insert_record('config', $config, false);
1184 } else { // plugin scope
1185 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1186 if ($value===null) {
1187 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1189 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1192 if ($value !== null) {
1193 $config = new stdClass();
1194 $config->plugin = $plugin;
1195 $config->name = $name;
1196 $config->value = $value;
1197 $DB->insert_record('config_plugins', $config, false);
1206 * Get configuration values from the global config table
1207 * or the config_plugins table.
1209 * If called with one parameter, it will load all the config
1210 * variables for one plugin, and return them as an object.
1212 * If called with 2 parameters it will return a string single
1213 * value or false if the value is not found.
1215 * @param string $plugin full component name
1216 * @param string $name default NULL
1217 * @return mixed hash-like object or single value, return false no config found
1219 function get_config($plugin, $name = NULL) {
1222 // normalise component name
1223 if ($plugin === 'moodle' or $plugin === 'core') {
1227 if (!empty($name)) { // the user is asking for a specific value
1228 if (!empty($plugin)) {
1229 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1230 // setting forced in config file
1231 return $CFG->forced_plugin_settings[$plugin][$name];
1233 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1236 if (array_key_exists($name, $CFG->config_php_settings)) {
1237 // setting force in config file
1238 return $CFG->config_php_settings[$name];
1240 return $DB->get_field('config', 'value', array('name'=>$name));
1245 // the user is after a recordset
1247 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1248 if (isset($CFG->forced_plugin_settings[$plugin])) {
1249 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1250 if (is_null($v) or is_array($v) or is_object($v)) {
1251 // we do not want any extra mess here, just real settings that could be saved in db
1252 unset($localcfg[$n]);
1254 //convert to string as if it went through the DB
1255 $localcfg[$n] = (string)$v;
1260 return (object)$localcfg;
1266 // this part is not really used any more, but anyway...
1267 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1268 foreach($CFG->config_php_settings as $n=>$v) {
1269 if (is_null($v) or is_array($v) or is_object($v)) {
1270 // we do not want any extra mess here, just real settings that could be saved in db
1271 unset($localcfg[$n]);
1273 //convert to string as if it went through the DB
1274 $localcfg[$n] = (string)$v;
1277 return (object)$localcfg;
1282 * Removes a key from global configuration
1284 * @param string $name the key to set
1285 * @param string $plugin (optional) the plugin scope
1287 * @return boolean whether the operation succeeded.
1289 function unset_config($name, $plugin=NULL) {
1292 if (empty($plugin)) {
1294 $DB->delete_records('config', array('name'=>$name));
1296 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1303 * Remove all the config variables for a given plugin.
1305 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1306 * @return boolean whether the operation succeeded.
1308 function unset_all_config_for_plugin($plugin) {
1310 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1311 $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
1316 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1318 * All users are verified if they still have the necessary capability.
1320 * @param string $value the value of the config setting.
1321 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1322 * @param bool $include admins, include administrators
1323 * @return array of user objects.
1325 function get_users_from_config($value, $capability, $includeadmins = true) {
1328 if (empty($value) or $value === '$@NONE@$') {
1332 // we have to make sure that users still have the necessary capability,
1333 // it should be faster to fetch them all first and then test if they are present
1334 // instead of validating them one-by-one
1335 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1336 if ($includeadmins) {
1337 $admins = get_admins();
1338 foreach ($admins as $admin) {
1339 $users[$admin->id] = $admin;
1343 if ($value === '$@ALL@$') {
1347 $result = array(); // result in correct order
1348 $allowed = explode(',', $value);
1349 foreach ($allowed as $uid) {
1350 if (isset($users[$uid])) {
1351 $user = $users[$uid];
1352 $result[$user->id] = $user;
1361 * Invalidates browser caches and cached data in temp
1364 function purge_all_caches() {
1367 reset_text_filters_cache();
1368 js_reset_all_caches();
1369 theme_reset_all_caches();
1370 get_string_manager()->reset_caches();
1372 // purge all other caches: rss, simplepie, etc.
1373 remove_dir($CFG->cachedir.'', true);
1375 // make sure cache dir is writable, throws exception if not
1376 make_cache_directory('');
1378 // hack: this script may get called after the purifier was initialised,
1379 // but we do not want to verify repeatedly this exists in each call
1380 make_cache_directory('htmlpurifier');
1386 * Get volatile flags
1388 * @param string $type
1389 * @param int $changedsince default null
1390 * @return records array
1392 function get_cache_flags($type, $changedsince=NULL) {
1395 $params = array('type'=>$type, 'expiry'=>time());
1396 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1397 if ($changedsince !== NULL) {
1398 $params['changedsince'] = $changedsince;
1399 $sqlwhere .= " AND timemodified > :changedsince";
1403 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1404 foreach ($flags as $flag) {
1405 $cf[$flag->name] = $flag->value;
1412 * Get volatile flags
1414 * @param string $type
1415 * @param string $name
1416 * @param int $changedsince default null
1417 * @return records array
1419 function get_cache_flag($type, $name, $changedsince=NULL) {
1422 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1424 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1425 if ($changedsince !== NULL) {
1426 $params['changedsince'] = $changedsince;
1427 $sqlwhere .= " AND timemodified > :changedsince";
1430 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1434 * Set a volatile flag
1436 * @param string $type the "type" namespace for the key
1437 * @param string $name the key to set
1438 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1439 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1440 * @return bool Always returns true
1442 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1445 $timemodified = time();
1446 if ($expiry===NULL || $expiry < $timemodified) {
1447 $expiry = $timemodified + 24 * 60 * 60;
1449 $expiry = (int)$expiry;
1452 if ($value === NULL) {
1453 unset_cache_flag($type,$name);
1457 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1458 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1459 return true; //no need to update; helps rcache too
1462 $f->expiry = $expiry;
1463 $f->timemodified = $timemodified;
1464 $DB->update_record('cache_flags', $f);
1466 $f = new stdClass();
1467 $f->flagtype = $type;
1470 $f->expiry = $expiry;
1471 $f->timemodified = $timemodified;
1472 $DB->insert_record('cache_flags', $f);
1478 * Removes a single volatile flag
1481 * @param string $type the "type" namespace for the key
1482 * @param string $name the key to set
1485 function unset_cache_flag($type, $name) {
1487 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1492 * Garbage-collect volatile flags
1494 * @return bool Always returns true
1496 function gc_cache_flags() {
1498 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1502 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1505 * Refresh user preference cache. This is used most often for $USER
1506 * object that is stored in session, but it also helps with performance in cron script.
1508 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1510 * @param stdClass $user user object, preferences are preloaded into ->preference property
1511 * @param int $cachelifetime cache life time on the current page (ins seconds)
1514 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1516 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1518 if (!isset($user->id)) {
1519 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1522 if (empty($user->id) or isguestuser($user->id)) {
1523 // No permanent storage for not-logged-in users and guest
1524 if (!isset($user->preference)) {
1525 $user->preference = array();
1532 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1533 // Already loaded at least once on this page. Are we up to date?
1534 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1535 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1538 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1539 // no change since the lastcheck on this page
1540 $user->preference['_lastloaded'] = $timenow;
1545 // OK, so we have to reload all preferences
1546 $loadedusers[$user->id] = true;
1547 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1548 $user->preference['_lastloaded'] = $timenow;
1552 * Called from set/delete_user_preferences, so that the prefs can
1553 * be correctly reloaded in different sessions.
1555 * NOTE: internal function, do not call from other code.
1557 * @param integer $userid the user whose prefs were changed.
1560 function mark_user_preferences_changed($userid) {
1563 if (empty($userid) or isguestuser($userid)) {
1564 // no cache flags for guest and not-logged-in users
1568 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1572 * Sets a preference for the specified user.
1574 * If user object submitted, 'preference' property contains the preferences cache.
1576 * @param string $name The key to set as preference for the specified user
1577 * @param string $value The value to set for the $name key in the specified user's record,
1578 * null means delete current value
1579 * @param stdClass|int $user A moodle user object or id, null means current user
1580 * @return bool always true or exception
1582 function set_user_preference($name, $value, $user = null) {
1585 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1586 throw new coding_exception('Invalid preference name in set_user_preference() call');
1589 if (is_null($value)) {
1590 // null means delete current
1591 return unset_user_preference($name, $user);
1592 } else if (is_object($value)) {
1593 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1594 } else if (is_array($value)) {
1595 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1597 $value = (string)$value;
1599 if (is_null($user)) {
1601 } else if (isset($user->id)) {
1602 // $user is valid object
1603 } else if (is_numeric($user)) {
1604 $user = (object)array('id'=>(int)$user);
1606 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1609 check_user_preferences_loaded($user);
1611 if (empty($user->id) or isguestuser($user->id)) {
1612 // no permanent storage for not-logged-in users and guest
1613 $user->preference[$name] = $value;
1617 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1618 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1619 // preference already set to this value
1622 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1625 $preference = new stdClass();
1626 $preference->userid = $user->id;
1627 $preference->name = $name;
1628 $preference->value = $value;
1629 $DB->insert_record('user_preferences', $preference);
1632 // update value in cache
1633 $user->preference[$name] = $value;
1635 // set reload flag for other sessions
1636 mark_user_preferences_changed($user->id);
1642 * Sets a whole array of preferences for the current user
1644 * If user object submitted, 'preference' property contains the preferences cache.
1646 * @param array $prefarray An array of key/value pairs to be set
1647 * @param stdClass|int $user A moodle user object or id, null means current user
1648 * @return bool always true or exception
1650 function set_user_preferences(array $prefarray, $user = null) {
1651 foreach ($prefarray as $name => $value) {
1652 set_user_preference($name, $value, $user);
1658 * Unsets a preference completely by deleting it from the database
1660 * If user object submitted, 'preference' property contains the preferences cache.
1662 * @param string $name The key to unset as preference for the specified user
1663 * @param stdClass|int $user A moodle user object or id, null means current user
1664 * @return bool always true or exception
1666 function unset_user_preference($name, $user = null) {
1669 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1670 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1673 if (is_null($user)) {
1675 } else if (isset($user->id)) {
1676 // $user is valid object
1677 } else if (is_numeric($user)) {
1678 $user = (object)array('id'=>(int)$user);
1680 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1683 check_user_preferences_loaded($user);
1685 if (empty($user->id) or isguestuser($user->id)) {
1686 // no permanent storage for not-logged-in user and guest
1687 unset($user->preference[$name]);
1692 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1694 // delete the preference from cache
1695 unset($user->preference[$name]);
1697 // set reload flag for other sessions
1698 mark_user_preferences_changed($user->id);
1704 * Used to fetch user preference(s)
1706 * If no arguments are supplied this function will return
1707 * all of the current user preferences as an array.
1709 * If a name is specified then this function
1710 * attempts to return that particular preference value. If
1711 * none is found, then the optional value $default is returned,
1714 * If user object submitted, 'preference' property contains the preferences cache.
1716 * @param string $name Name of the key to use in finding a preference value
1717 * @param mixed $default Value to be returned if the $name key is not set in the user preferences
1718 * @param stdClass|int $user A moodle user object or id, null means current user
1719 * @return mixed string value or default
1721 function get_user_preferences($name = null, $default = null, $user = null) {
1724 if (is_null($name)) {
1726 } else if (is_numeric($name) or $name === '_lastloaded') {
1727 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1730 if (is_null($user)) {
1732 } else if (isset($user->id)) {
1733 // $user is valid object
1734 } else if (is_numeric($user)) {
1735 $user = (object)array('id'=>(int)$user);
1737 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1740 check_user_preferences_loaded($user);
1743 return $user->preference; // All values
1744 } else if (isset($user->preference[$name])) {
1745 return $user->preference[$name]; // The single string value
1747 return $default; // Default value (null if not specified)
1751 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1754 * Given date parts in user time produce a GMT timestamp.
1756 * @todo Finish documenting this function
1757 * @param int $year The year part to create timestamp of
1758 * @param int $month The month part to create timestamp of
1759 * @param int $day The day part to create timestamp of
1760 * @param int $hour The hour part to create timestamp of
1761 * @param int $minute The minute part to create timestamp of
1762 * @param int $second The second part to create timestamp of
1763 * @param mixed $timezone Timezone modifier, if 99 then use default user's timezone
1764 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1765 * applied only if timezone is 99 or string.
1766 * @return int timestamp
1768 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1770 //save input timezone, required for dst offset check.
1771 $passedtimezone = $timezone;
1773 $timezone = get_user_timezone_offset($timezone);
1775 if (abs($timezone) > 13) { //server time
1776 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1778 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1779 $time = usertime($time, $timezone);
1781 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1782 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1783 $time -= dst_offset_on($time, $passedtimezone);
1792 * Format a date/time (seconds) as weeks, days, hours etc as needed
1794 * Given an amount of time in seconds, returns string
1795 * formatted nicely as weeks, days, hours etc as needed
1801 * @param int $totalsecs Time in seconds
1802 * @param object $str Should be a time object
1803 * @return string A nicely formatted date/time string
1805 function format_time($totalsecs, $str=NULL) {
1807 $totalsecs = abs($totalsecs);
1809 if (!$str) { // Create the str structure the slow way
1810 $str->day = get_string('day');
1811 $str->days = get_string('days');
1812 $str->hour = get_string('hour');
1813 $str->hours = get_string('hours');
1814 $str->min = get_string('min');
1815 $str->mins = get_string('mins');
1816 $str->sec = get_string('sec');
1817 $str->secs = get_string('secs');
1818 $str->year = get_string('year');
1819 $str->years = get_string('years');
1823 $years = floor($totalsecs/YEARSECS);
1824 $remainder = $totalsecs - ($years*YEARSECS);
1825 $days = floor($remainder/DAYSECS);
1826 $remainder = $totalsecs - ($days*DAYSECS);
1827 $hours = floor($remainder/HOURSECS);
1828 $remainder = $remainder - ($hours*HOURSECS);
1829 $mins = floor($remainder/MINSECS);
1830 $secs = $remainder - ($mins*MINSECS);
1832 $ss = ($secs == 1) ? $str->sec : $str->secs;
1833 $sm = ($mins == 1) ? $str->min : $str->mins;
1834 $sh = ($hours == 1) ? $str->hour : $str->hours;
1835 $sd = ($days == 1) ? $str->day : $str->days;
1836 $sy = ($years == 1) ? $str->year : $str->years;
1844 if ($years) $oyears = $years .' '. $sy;
1845 if ($days) $odays = $days .' '. $sd;
1846 if ($hours) $ohours = $hours .' '. $sh;
1847 if ($mins) $omins = $mins .' '. $sm;
1848 if ($secs) $osecs = $secs .' '. $ss;
1850 if ($years) return trim($oyears .' '. $odays);
1851 if ($days) return trim($odays .' '. $ohours);
1852 if ($hours) return trim($ohours .' '. $omins);
1853 if ($mins) return trim($omins .' '. $osecs);
1854 if ($secs) return $osecs;
1855 return get_string('now');
1859 * Returns a formatted string that represents a date in user time
1861 * Returns a formatted string that represents a date in user time
1862 * <b>WARNING: note that the format is for strftime(), not date().</b>
1863 * Because of a bug in most Windows time libraries, we can't use
1864 * the nicer %e, so we have to use %d which has leading zeroes.
1865 * A lot of the fuss in the function is just getting rid of these leading
1866 * zeroes as efficiently as possible.
1868 * If parameter fixday = true (default), then take off leading
1869 * zero from %d, else maintain it.
1871 * @param int $date the timestamp in UTC, as obtained from the database.
1872 * @param string $format strftime format. You should probably get this using
1873 * get_string('strftime...', 'langconfig');
1874 * @param mixed $timezone by default, uses the user's time zone. if numeric and
1875 * not 99 then daylight saving will not be added.
1876 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1877 * If false then the leading zero is maintained.
1878 * @return string the formatted date/time.
1880 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1884 if (empty($format)) {
1885 $format = get_string('strftimedaydatetime', 'langconfig');
1888 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1890 } else if ($fixday) {
1891 $formatnoday = str_replace('%d', 'DD', $format);
1892 $fixday = ($formatnoday != $format);
1895 //add daylight saving offset for string timezones only, as we can't get dst for
1896 //float values. if timezone is 99 (user default timezone), then try update dst.
1897 if ((99 == $timezone) || !is_numeric($timezone)) {
1898 $date += dst_offset_on($date, $timezone);
1901 $timezone = get_user_timezone_offset($timezone);
1903 if (abs($timezone) > 13) { /// Server time
1905 $datestring = strftime($formatnoday, $date);
1906 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
1907 $datestring = str_replace('DD', $daystring, $datestring);
1909 $datestring = strftime($format, $date);
1912 $date += (int)($timezone * 3600);
1914 $datestring = gmstrftime($formatnoday, $date);
1915 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
1916 $datestring = str_replace('DD', $daystring, $datestring);
1918 $datestring = gmstrftime($format, $date);
1922 /// If we are running under Windows convert from windows encoding to UTF-8
1923 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1925 if ($CFG->ostype == 'WINDOWS') {
1926 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1927 $textlib = textlib_get_instance();
1928 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1936 * Given a $time timestamp in GMT (seconds since epoch),
1937 * returns an array that represents the date in user time
1939 * @todo Finish documenting this function
1941 * @param int $time Timestamp in GMT
1942 * @param mixed $timezone offset time with timezone, if float and not 99, then no
1943 * dst offset is applyed
1944 * @return array An array that represents the date in user time
1946 function usergetdate($time, $timezone=99) {
1948 //save input timezone, required for dst offset check.
1949 $passedtimezone = $timezone;
1951 $timezone = get_user_timezone_offset($timezone);
1953 if (abs($timezone) > 13) { // Server time
1954 return getdate($time);
1957 //add daylight saving offset for string timezones only, as we can't get dst for
1958 //float values. if timezone is 99 (user default timezone), then try update dst.
1959 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
1960 $time += dst_offset_on($time, $passedtimezone);
1963 $time += intval((float)$timezone * HOURSECS);
1965 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
1967 //be careful to ensure the returned array matches that produced by getdate() above
1970 $getdate['weekday'],
1977 $getdate['minutes'],
1979 ) = explode('_', $datestring);
1985 * Given a GMT timestamp (seconds since epoch), offsets it by
1986 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1989 * @param int $date Timestamp in GMT
1990 * @param float $timezone
1993 function usertime($date, $timezone=99) {
1995 $timezone = get_user_timezone_offset($timezone);
1997 if (abs($timezone) > 13) {
2000 return $date - (int)($timezone * HOURSECS);
2004 * Given a time, return the GMT timestamp of the most recent midnight
2005 * for the current user.
2007 * @param int $date Timestamp in GMT
2008 * @param float $timezone Defaults to user's timezone
2009 * @return int Returns a GMT timestamp
2011 function usergetmidnight($date, $timezone=99) {
2013 $userdate = usergetdate($date, $timezone);
2015 // Time of midnight of this user's day, in GMT
2016 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2021 * Returns a string that prints the user's timezone
2023 * @param float $timezone The user's timezone
2026 function usertimezone($timezone=99) {
2028 $tz = get_user_timezone($timezone);
2030 if (!is_float($tz)) {
2034 if(abs($tz) > 13) { // Server time
2035 return get_string('serverlocaltime');
2038 if($tz == intval($tz)) {
2039 // Don't show .0 for whole hours
2056 * Returns a float which represents the user's timezone difference from GMT in hours
2057 * Checks various settings and picks the most dominant of those which have a value
2061 * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
2064 function get_user_timezone_offset($tz = 99) {
2068 $tz = get_user_timezone($tz);
2070 if (is_float($tz)) {
2073 $tzrecord = get_timezone_record($tz);
2074 if (empty($tzrecord)) {
2077 return (float)$tzrecord->gmtoff / HOURMINS;
2082 * Returns an int which represents the systems's timezone difference from GMT in seconds
2085 * @param mixed $tz timezone
2086 * @return int if found, false is timezone 99 or error
2088 function get_timezone_offset($tz) {
2095 if (is_numeric($tz)) {
2096 return intval($tz * 60*60);
2099 if (!$tzrecord = get_timezone_record($tz)) {
2102 return intval($tzrecord->gmtoff * 60);
2106 * Returns a float or a string which denotes the user's timezone
2107 * A float value means that a simple offset from GMT is used, while a string (it will be the name of a timezone in the database)
2108 * means that for this timezone there are also DST rules to be taken into account
2109 * Checks various settings and picks the most dominant of those which have a value
2113 * @param mixed $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
2116 function get_user_timezone($tz = 99) {
2121 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2122 isset($USER->timezone) ? $USER->timezone : 99,
2123 isset($CFG->timezone) ? $CFG->timezone : 99,
2128 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
2129 $tz = $next['value'];
2132 return is_numeric($tz) ? (float) $tz : $tz;
2136 * Returns cached timezone record for given $timezonename
2140 * @param string $timezonename
2141 * @return mixed timezonerecord object or false
2143 function get_timezone_record($timezonename) {
2145 static $cache = NULL;
2147 if ($cache === NULL) {
2151 if (isset($cache[$timezonename])) {
2152 return $cache[$timezonename];
2155 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2156 WHERE name = ? ORDER BY year DESC', array($timezonename), true);
2160 * Build and store the users Daylight Saving Time (DST) table
2165 * @param mixed $from_year Start year for the table, defaults to 1971
2166 * @param mixed $to_year End year for the table, defaults to 2035
2167 * @param mixed $strtimezone, if null or 99 then user's default timezone is used
2170 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2171 global $CFG, $SESSION, $DB;
2173 $usertz = get_user_timezone($strtimezone);
2175 if (is_float($usertz)) {
2176 // Trivial timezone, no DST
2180 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2181 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2182 unset($SESSION->dst_offsets);
2183 unset($SESSION->dst_range);
2186 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2187 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2188 // This will be the return path most of the time, pretty light computationally
2192 // Reaching here means we either need to extend our table or create it from scratch
2194 // Remember which TZ we calculated these changes for
2195 $SESSION->dst_offsettz = $usertz;
2197 if(empty($SESSION->dst_offsets)) {
2198 // If we 're creating from scratch, put the two guard elements in there
2199 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2201 if(empty($SESSION->dst_range)) {
2202 // If creating from scratch
2203 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2204 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2206 // Fill in the array with the extra years we need to process
2207 $yearstoprocess = array();
2208 for($i = $from; $i <= $to; ++$i) {
2209 $yearstoprocess[] = $i;
2212 // Take note of which years we have processed for future calls
2213 $SESSION->dst_range = array($from, $to);
2216 // If needing to extend the table, do the same
2217 $yearstoprocess = array();
2219 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2220 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2222 if($from < $SESSION->dst_range[0]) {
2223 // Take note of which years we need to process and then note that we have processed them for future calls
2224 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2225 $yearstoprocess[] = $i;
2227 $SESSION->dst_range[0] = $from;
2229 if($to > $SESSION->dst_range[1]) {
2230 // Take note of which years we need to process and then note that we have processed them for future calls
2231 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2232 $yearstoprocess[] = $i;
2234 $SESSION->dst_range[1] = $to;
2238 if(empty($yearstoprocess)) {
2239 // This means that there was a call requesting a SMALLER range than we have already calculated
2243 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2244 // Also, the array is sorted in descending timestamp order!
2248 static $presets_cache = array();
2249 if (!isset($presets_cache[$usertz])) {
2250 $presets_cache[$usertz] = $DB->get_records('timezone', array('name'=>$usertz), 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, std_startday, std_weekday, std_skipweeks, std_time');
2252 if(empty($presets_cache[$usertz])) {
2256 // Remove ending guard (first element of the array)
2257 reset($SESSION->dst_offsets);
2258 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2260 // Add all required change timestamps
2261 foreach($yearstoprocess as $y) {
2262 // Find the record which is in effect for the year $y
2263 foreach($presets_cache[$usertz] as $year => $preset) {
2269 $changes = dst_changes_for_year($y, $preset);
2271 if($changes === NULL) {
2274 if($changes['dst'] != 0) {
2275 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2277 if($changes['std'] != 0) {
2278 $SESSION->dst_offsets[$changes['std']] = 0;
2282 // Put in a guard element at the top
2283 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2284 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2287 krsort($SESSION->dst_offsets);
2293 * Calculates the required DST change and returns a Timestamp Array
2297 * @param mixed $year Int or String Year to focus on
2298 * @param object $timezone Instatiated Timezone object
2299 * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
2301 function dst_changes_for_year($year, $timezone) {
2303 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2307 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2308 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2310 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2311 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2313 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2314 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2316 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2317 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2318 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2320 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2321 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2323 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2327 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2328 * - Note: Daylight saving only works for string timezones and not for float.
2331 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2332 * @param mixed $strtimezone timezone for which offset is expected, if 99 or null
2333 * then user's default timezone is used.
2336 function dst_offset_on($time, $strtimezone = NULL) {
2339 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2343 reset($SESSION->dst_offsets);
2344 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2345 if($from <= $time) {
2350 // This is the normal return path
2351 if($offset !== NULL) {
2355 // Reaching this point means we haven't calculated far enough, do it now:
2356 // Calculate extra DST changes if needed and recurse. The recursion always
2357 // moves toward the stopping condition, so will always end.
2360 // We need a year smaller than $SESSION->dst_range[0]
2361 if($SESSION->dst_range[0] == 1971) {
2364 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2365 return dst_offset_on($time, $strtimezone);
2368 // We need a year larger than $SESSION->dst_range[1]
2369 if($SESSION->dst_range[1] == 2035) {
2372 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2373 return dst_offset_on($time, $strtimezone);
2380 * @todo Document what this function does
2381 * @param int $startday
2382 * @param int $weekday
2387 function find_day_in_month($startday, $weekday, $month, $year) {
2389 $daysinmonth = days_in_month($month, $year);
2391 if($weekday == -1) {
2392 // Don't care about weekday, so return:
2393 // abs($startday) if $startday != -1
2394 // $daysinmonth otherwise
2395 return ($startday == -1) ? $daysinmonth : abs($startday);
2398 // From now on we 're looking for a specific weekday
2400 // Give "end of month" its actual value, since we know it
2401 if($startday == -1) {
2402 $startday = -1 * $daysinmonth;
2405 // Starting from day $startday, the sign is the direction
2409 $startday = abs($startday);
2410 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2412 // This is the last such weekday of the month
2413 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2414 if($lastinmonth > $daysinmonth) {
2418 // Find the first such weekday <= $startday
2419 while($lastinmonth > $startday) {
2423 return $lastinmonth;
2428 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2430 $diff = $weekday - $indexweekday;
2435 // This is the first such weekday of the month equal to or after $startday
2436 $firstfromindex = $startday + $diff;
2438 return $firstfromindex;
2444 * Calculate the number of days in a given month
2446 * @param int $month The month whose day count is sought
2447 * @param int $year The year of the month whose day count is sought
2450 function days_in_month($month, $year) {
2451 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2455 * Calculate the position in the week of a specific calendar day
2457 * @param int $day The day of the date whose position in the week is sought
2458 * @param int $month The month of the date whose position in the week is sought
2459 * @param int $year The year of the date whose position in the week is sought
2462 function dayofweek($day, $month, $year) {
2463 // I wonder if this is any different from
2464 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2465 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2468 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2471 * Returns full login url.
2473 * @return string login url
2475 function get_login_url() {
2478 $url = "$CFG->wwwroot/login/index.php";
2480 if (!empty($CFG->loginhttps)) {
2481 $url = str_replace('http:', 'https:', $url);
2488 * This function checks that the current user is logged in and has the
2489 * required privileges
2491 * This function checks that the current user is logged in, and optionally
2492 * whether they are allowed to be in a particular course and view a particular
2494 * If they are not logged in, then it redirects them to the site login unless
2495 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2496 * case they are automatically logged in as guests.
2497 * If $courseid is given and the user is not enrolled in that course then the
2498 * user is redirected to the course enrolment page.
2499 * If $cm is given and the course module is hidden and the user is not a teacher
2500 * in the course then the user is redirected to the course home page.
2502 * When $cm parameter specified, this function sets page layout to 'module'.
2503 * You need to change it manually later if some other layout needed.
2505 * @param mixed $courseorid id of the course or course object
2506 * @param bool $autologinguest default true
2507 * @param object $cm course module object
2508 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2509 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2510 * in order to keep redirects working properly. MDL-14495
2511 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2512 * @return mixed Void, exit, and die depending on path
2514 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2515 global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2517 // setup global $COURSE, themes, language and locale
2518 if (!empty($courseorid)) {
2519 if (is_object($courseorid)) {
2520 $course = $courseorid;
2521 } else if ($courseorid == SITEID) {
2522 $course = clone($SITE);
2524 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2527 if ($cm->course != $course->id) {
2528 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2530 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2531 if (!($cm instanceof cm_info)) {
2532 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2533 // db queries so this is not really a performance concern, however it is obviously
2534 // better if you use get_fast_modinfo to get the cm before calling this.
2535 $modinfo = get_fast_modinfo($course);
2536 $cm = $modinfo->get_cm($cm->id);
2538 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2539 $PAGE->set_pagelayout('incourse');
2541 $PAGE->set_course($course); // set's up global $COURSE
2544 // do not touch global $COURSE via $PAGE->set_course(),
2545 // the reasons is we need to be able to call require_login() at any time!!
2548 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2552 // If the user is not even logged in yet then make sure they are
2553 if (!isloggedin()) {
2554 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2555 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2556 // misconfigured site guest, just redirect to login page
2557 redirect(get_login_url());
2558 exit; // never reached
2560 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2561 complete_user_login($guest);
2562 $USER->autologinguest = true;
2563 $SESSION->lang = $lang;
2565 //NOTE: $USER->site check was obsoleted by session test cookie,
2566 // $USER->confirmed test is in login/index.php
2567 if ($preventredirect) {
2568 throw new require_login_exception('You are not logged in');
2571 if ($setwantsurltome) {
2572 // TODO: switch to PAGE->url
2573 $SESSION->wantsurl = $FULLME;
2575 if (!empty($_SERVER['HTTP_REFERER'])) {
2576 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2578 redirect(get_login_url());
2579 exit; // never reached
2583 // loginas as redirection if needed
2584 if ($course->id != SITEID and session_is_loggedinas()) {
2585 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2586 if ($USER->loginascontext->instanceid != $course->id) {
2587 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2592 // check whether the user should be changing password (but only if it is REALLY them)
2593 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2594 $userauth = get_auth_plugin($USER->auth);
2595 if ($userauth->can_change_password() and !$preventredirect) {
2596 $SESSION->wantsurl = $FULLME;
2597 if ($changeurl = $userauth->change_password_url()) {
2598 //use plugin custom url
2599 redirect($changeurl);
2601 //use moodle internal method
2602 if (empty($CFG->loginhttps)) {
2603 redirect($CFG->wwwroot .'/login/change_password.php');
2605 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2606 redirect($wwwroot .'/login/change_password.php');
2610 print_error('nopasswordchangeforced', 'auth');
2614 // Check that the user account is properly set up
2615 if (user_not_fully_set_up($USER)) {
2616 if ($preventredirect) {
2617 throw new require_login_exception('User not fully set-up');
2619 $SESSION->wantsurl = $FULLME;
2620 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2623 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2626 // Do not bother admins with any formalities
2627 if (is_siteadmin()) {
2628 //set accesstime or the user will appear offline which messes up messaging
2629 user_accesstime_log($course->id);
2633 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2634 if (!$USER->policyagreed and !is_siteadmin()) {
2635 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2636 if ($preventredirect) {
2637 throw new require_login_exception('Policy not agreed');
2639 $SESSION->wantsurl = $FULLME;
2640 redirect($CFG->wwwroot .'/user/policy.php');
2641 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2642 if ($preventredirect) {
2643 throw new require_login_exception('Policy not agreed');
2645 $SESSION->wantsurl = $FULLME;
2646 redirect($CFG->wwwroot .'/user/policy.php');
2650 // Fetch the system context, the course context, and prefetch its child contexts
2651 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2652 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2654 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2659 // If the site is currently under maintenance, then print a message
2660 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2661 if ($preventredirect) {
2662 throw new require_login_exception('Maintenance in progress');
2665 print_maintenance_message();
2668 // make sure the course itself is not hidden
2669 if ($course->id == SITEID) {
2670 // frontpage can not be hidden
2672 if (is_role_switched($course->id)) {
2673 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2675 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2676 // originally there was also test of parent category visibility,
2677 // BUT is was very slow in complex queries involving "my courses"
2678 // now it is also possible to simply hide all courses user is not enrolled in :-)
2679 if ($preventredirect) {
2680 throw new require_login_exception('Course is hidden');
2682 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2687 // is the user enrolled?
2688 if ($course->id == SITEID) {
2689 // everybody is enrolled on the frontpage
2692 if (session_is_loggedinas()) {
2693 // Make sure the REAL person can access this course first
2694 $realuser = session_get_realuser();
2695 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2696 if ($preventredirect) {
2697 throw new require_login_exception('Invalid course login-as access');
2699 echo $OUTPUT->header();
2700 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2704 // very simple enrolment caching - changes in course setting are not reflected immediately
2705 if (!isset($USER->enrol)) {
2706 $USER->enrol = array();
2707 $USER->enrol['enrolled'] = array();
2708 $USER->enrol['tempguest'] = array();
2713 if (is_viewing($coursecontext, $USER)) {
2714 // ok, no need to mess with enrol
2718 if (isset($USER->enrol['enrolled'][$course->id])) {
2719 if ($USER->enrol['enrolled'][$course->id] == 0) {
2721 } else if ($USER->enrol['enrolled'][$course->id] > time()) {
2725 unset($USER->enrol['enrolled'][$course->id]);
2728 if (isset($USER->enrol['tempguest'][$course->id])) {
2729 if ($USER->enrol['tempguest'][$course->id] == 0) {
2731 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2735 unset($USER->enrol['tempguest'][$course->id]);
2736 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2742 } else if (is_enrolled($coursecontext, $USER, '', true)) {
2743 // active participants may always access
2744 // TODO: refactor this into some new function
2746 $sql = "SELECT MAX(ue.timeend)
2747 FROM {user_enrolments} ue
2748 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2749 JOIN {user} u ON u.id = ue.userid
2750 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0
2751 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
2752 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE,
2753 'userid'=>$USER->id, 'courseid'=>$coursecontext->instanceid, 'now1'=>$now, 'now2'=>$now);
2754 $until = $DB->get_field_sql($sql, $params);
2755 if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) {
2756 $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD;
2759 $USER->enrol['enrolled'][$course->id] = $until;
2762 // remove traces of previous temp guest access
2763 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2766 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2767 $enrols = enrol_get_plugins(true);
2768 // first ask all enabled enrol instances in course if they want to auto enrol user
2769 foreach($instances as $instance) {
2770 if (!isset($enrols[$instance->enrol])) {
2773 // Get a duration for the guestaccess, a timestamp in the future or false.
2774 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2775 if ($until !== false) {
2776 $USER->enrol['enrolled'][$course->id] = $until;
2777 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2782 // if not enrolled yet try to gain temporary guest access
2784 foreach($instances as $instance) {
2785 if (!isset($enrols[$instance->enrol])) {
2788 // Get a duration for the guestaccess, a timestamp in the future or false.
2789 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2790 if ($until !== false) {
2791 $USER->enrol['tempguest'][$course->id] = $until;
2801 if ($preventredirect) {
2802 throw new require_login_exception('Not enrolled');
2804 $SESSION->wantsurl = $FULLME;
2805 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2809 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
2810 // conditional availability, etc
2811 if ($cm && !$cm->uservisible) {
2812 if ($preventredirect) {
2813 throw new require_login_exception('Activity is hidden');
2815 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2818 // Finally access granted, update lastaccess times
2819 user_accesstime_log($course->id);
2824 * This function just makes sure a user is logged out.
2828 function require_logout() {
2834 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2836 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2837 foreach($authsequence as $authname) {
2838 $authplugin = get_auth_plugin($authname);
2839 $authplugin->prelogout_hook();
2843 events_trigger('user_logout', $params);
2844 session_get_instance()->terminate_current();
2849 * Weaker version of require_login()
2851 * This is a weaker version of {@link require_login()} which only requires login
2852 * when called from within a course rather than the site page, unless
2853 * the forcelogin option is turned on.
2854 * @see require_login()
2857 * @param mixed $courseorid The course object or id in question
2858 * @param bool $autologinguest Allow autologin guests if that is wanted
2859 * @param object $cm Course activity module if known
2860 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2861 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2862 * in order to keep redirects working properly. MDL-14495
2863 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2866 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2867 global $CFG, $PAGE, $SITE;
2868 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
2869 or (!is_object($courseorid) and $courseorid == SITEID);
2870 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2871 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2872 // db queries so this is not really a performance concern, however it is obviously
2873 // better if you use get_fast_modinfo to get the cm before calling this.
2874 if (is_object($courseorid)) {
2875 $course = $courseorid;
2877 $course = clone($SITE);
2879 $modinfo = get_fast_modinfo($course);
2880 $cm = $modinfo->get_cm($cm->id);
2882 if (!empty($CFG->forcelogin)) {
2883 // login required for both SITE and courses
2884 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2886 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2887 // always login for hidden activities
2888 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2890 } else if ($issite) {
2891 //login for SITE not required
2892 if ($cm and empty($cm->visible)) {
2893 // hidden activities are not accessible without login
2894 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2895 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2896 // not-logged-in users do not have any group membership
2897 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2899 // We still need to instatiate PAGE vars properly so that things
2900 // that rely on it like navigation function correctly.
2901 if (!empty($courseorid)) {
2902 if (is_object($courseorid)) {
2903 $course = $courseorid;
2905 $course = clone($SITE);
2908 if ($cm->course != $course->id) {
2909 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2911 $PAGE->set_cm($cm, $course);
2912 $PAGE->set_pagelayout('incourse');
2914 $PAGE->set_course($course);
2917 // If $PAGE->course, and hence $PAGE->context, have not already been set
2918 // up properly, set them up now.
2919 $PAGE->set_course($PAGE->course);
2921 //TODO: verify conditional activities here
2922 user_accesstime_log(SITEID);
2927 // course login always required
2928 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2933 * Require key login. Function terminates with error if key not found or incorrect.
2939 * @uses NO_MOODLE_COOKIES
2940 * @uses PARAM_ALPHANUM
2941 * @param string $script unique script identifier
2942 * @param int $instance optional instance id
2943 * @return int Instance ID
2945 function require_user_key_login($script, $instance=null) {
2946 global $USER, $SESSION, $CFG, $DB;
2948 if (!NO_MOODLE_COOKIES) {
2949 print_error('sessioncookiesdisable');
2953 @session_write_close();
2955 $keyvalue = required_param('key', PARAM_ALPHANUM);
2957 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2958 print_error('invalidkey');
2961 if (!empty($key->validuntil) and $key->validuntil < time()) {
2962 print_error('expiredkey');
2965 if ($key->iprestriction) {
2966 $remoteaddr = getremoteaddr(null);
2967 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2968 print_error('ipmismatch');
2972 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2973 print_error('invaliduserid');
2976 /// emulate normal session
2977 session_set_user($user);
2979 /// note we are not using normal login
2980 if (!defined('USER_KEY_LOGIN')) {
2981 define('USER_KEY_LOGIN', true);
2984 /// return instance id - it might be empty
2985 return $key->instance;
2989 * Creates a new private user access key.
2992 * @param string $script unique target identifier
2993 * @param int $userid
2994 * @param int $instance optional instance id
2995 * @param string $iprestriction optional ip restricted access
2996 * @param timestamp $validuntil key valid only until given data
2997 * @return string access key value
2999 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3002 $key = new stdClass();
3003 $key->script = $script;
3004 $key->userid = $userid;
3005 $key->instance = $instance;
3006 $key->iprestriction = $iprestriction;
3007 $key->validuntil = $validuntil;
3008 $key->timecreated = time();
3010 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
3011 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3013 $key->value = md5($userid.'_'.time().random_string(40));
3015 $DB->insert_record('user_private_key', $key);
3020 * Delete the user's new private user access keys for a particular script.
3023 * @param string $script unique target identifier
3024 * @param int $userid
3027 function delete_user_key($script,$userid) {
3029 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3033 * Gets a private user access key (and creates one if one doesn't exist).
3036 * @param string $script unique target identifier
3037 * @param int $userid
3038 * @param int $instance optional instance id
3039 * @param string $iprestriction optional ip restricted access
3040 * @param timestamp $validuntil key valid only until given data
3041 * @return string access key value
3043 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3046 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3047 'instance'=>$instance, 'iprestriction'=>$iprestriction,
3048 'validuntil'=>$validuntil))) {
3051 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3057 * Modify the user table by setting the currently logged in user's
3058 * last login to now.
3062 * @return bool Always returns true
3064 function update_user_login_times() {
3067 $user = new stdClass();
3068 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3069 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
3071 $user->id = $USER->id;
3073 $DB->update_record('user', $user);
3078 * Determines if a user has completed setting up their account.
3080 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3083 function user_not_fully_set_up($user) {
3084 if (isguestuser($user)) {
3087 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3091 * Check whether the user has exceeded the bounce threshold
3095 * @param user $user A {@link $USER} object
3096 * @return bool true=>User has exceeded bounce threshold
3098 function over_bounce_threshold($user) {
3101 if (empty($CFG->handlebounces)) {
3105 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3109 // set sensible defaults
3110 if (empty($CFG->minbounces)) {
3111 $CFG->minbounces = 10;
3113 if (empty($CFG->bounceratio)) {
3114 $CFG->bounceratio = .20;
3118 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3119 $bouncecount = $bounce->value;
3121 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3122 $sendcount = $send->value;
3124 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3128 * Used to increment or reset email sent count
3131 * @param user $user object containing an id
3132 * @param bool $reset will reset the count to 0
3135 function set_send_count($user,$reset=false) {
3138 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3142 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3143 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3144 $DB->update_record('user_preferences', $pref);
3146 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3148 $pref = new stdClass();
3149 $pref->name = 'email_send_count';
3151 $pref->userid = $user->id;
3152 $DB->insert_record('user_preferences', $pref, false);
3157 * Increment or reset user's email bounce count
3160 * @param user $user object containing an id
3161 * @param bool $reset will reset the count to 0
3163 function set_bounce_count($user,$reset=false) {
3166 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3167 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3168 $DB->update_record('user_preferences', $pref);
3170 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3172 $pref = new stdClass();
3173 $pref->name = 'email_bounce_count';
3175 $pref->userid = $user->id;
3176 $DB->insert_record('user_preferences', $pref, false);
3181 * Keeps track of login attempts
3185 function update_login_count() {
3190 if (empty($SESSION->logincount)) {
3191 $SESSION->logincount = 1;
3193 $SESSION->logincount++;
3196 if ($SESSION->logincount > $max_logins) {
3197 unset($SESSION->wantsurl);
3198 print_error('errortoomanylogins');
3203 * Resets login attempts
3207 function reset_login_count() {
3210 $SESSION->logincount = 0;
3214 * Determines if the currently logged in user is in editing mode.
3215 * Note: originally this function had $userid parameter - it was not usable anyway
3217 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3218 * @todo Deprecated function remove when ready
3221 * @uses DEBUG_DEVELOPER
3224 function isediting() {
3226 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3227 return $PAGE->user_is_editing();
3231 * Determines if the logged in user is currently moving an activity
3234 * @param int $courseid The id of the course being tested
3237 function ismoving($courseid) {
3240 if (!empty($USER->activitycopy)) {
3241 return ($USER->activitycopycourse == $courseid);
3247 * Returns a persons full name
3249 * Given an object containing firstname and lastname
3250 * values, this function returns a string with the
3251 * full name of the person.
3252 * The result may depend on system settings
3253 * or language. 'override' will force both names
3254 * to be used even if system settings specify one.
3258 * @param object $user A {@link $USER} object to get full name of
3259 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3262 function fullname($user, $override=false) {
3263 global $CFG, $SESSION;
3265 if (!isset($user->firstname) and !isset($user->lastname)) {
3270 if (!empty($CFG->forcefirstname)) {
3271 $user->firstname = $CFG->forcefirstname;
3273 if (!empty($CFG->forcelastname)) {
3274 $user->lastname = $CFG->forcelastname;
3278 if (!empty($SESSION->fullnamedisplay)) {
3279 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3282 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3283 return $user->firstname .' '. $user->lastname;
3285 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3286 return $user->lastname .' '. $user->firstname;
3288 } else if ($CFG->fullnamedisplay == 'firstname') {
3290 return get_string('fullnamedisplay', '', $user);
3292 return $user->firstname;
3296 return get_string('fullnamedisplay', '', $user);
3300 * Returns whether a given authentication plugin exists.
3303 * @param string $auth Form of authentication to check for. Defaults to the
3304 * global setting in {@link $CFG}.
3305 * @return boolean Whether the plugin is available.
3307 function exists_auth_plugin($auth) {
3310 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3311 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3317 * Checks if a given plugin is in the list of enabled authentication plugins.
3319 * @param string $auth Authentication plugin.
3320 * @return boolean Whether the plugin is enabled.
3322 function is_enabled_auth($auth) {
3327 $enabled = get_enabled_auth_plugins();
3329 return in_array($auth, $enabled);
3333 * Returns an authentication plugin instance.
3336 * @param string $auth name of authentication plugin
3337 * @return auth_plugin_base An instance of the required authentication plugin.
3339 function get_auth_plugin($auth) {
3342 // check the plugin exists first
3343 if (! exists_auth_plugin($auth)) {
3344 print_error('authpluginnotfound', 'debug', '', $auth);
3347 // return auth plugin instance
3348 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3349 $class = "auth_plugin_$auth";
3354 * Returns array of active auth plugins.
3356 * @param bool $fix fix $CFG->auth if needed
3359 function get_enabled_auth_plugins($fix=false) {
3362 $default = array('manual', 'nologin');
3364 if (empty($CFG->auth)) {
3367 $auths = explode(',', $CFG->auth);
3371 $auths = array_unique($auths);
3372 foreach($auths as $k=>$authname) {
3373 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3377 $newconfig = implode(',', $auths);
3378 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3379 set_config('auth', $newconfig);
3383 return (array_merge($default, $auths));
3387 * Returns true if an internal authentication method is being used.
3388 * if method not specified then, global default is assumed
3390 * @param string $auth Form of authentication required
3393 function is_internal_auth($auth) {
3394 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3395 return $authplugin->is_internal();
3399 * Returns true if the user is a 'restored' one
3401 * Used in the login process to inform the user
3402 * and allow him/her to reset the password
3406 * @param string $username username to be checked
3409 function is_restored_user($username) {
3412 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3416 * Returns an array of user fields
3418 * @return array User field/column names
3420 function get_user_fieldnames() {
3423 $fieldarray = $DB->get_columns('user');
3424 unset($fieldarray['id']);
3425 $fieldarray = array_keys($fieldarray);
3431 * Creates a bare-bones user record
3433 * @todo Outline auth types and provide code example
3435 * @param string $username New user's username to add to record
3436 * @param string $password New user's password to add to record
3437 * @param string $auth Form of authentication required
3438 * @return stdClass A complete user object
3440 function create_user_record($username, $password, $auth = 'manual') {
3443 //just in case check text case
3444 $username = trim(moodle_strtolower($username));
3446 $authplugin = get_auth_plugin($auth);
3448 $newuser = new stdClass();
3450 if ($newinfo = $authplugin->get_userinfo($username)) {
3451 $newinfo = truncate_userinfo($newinfo);
3452 foreach ($newinfo as $key => $value){
3453 $newuser->$key = $value;
3457 if (!empty($newuser->email)) {
3458 if (email_is_not_allowed($newuser->email)) {
3459 unset($newuser->email);
3463 if (!isset($newuser->city)) {
3464 $newuser->city = '';
3467 $newuser->auth = $auth;
3468 $newuser->username = $username;
3471 // user CFG lang for user if $newuser->lang is empty
3472 // or $user->lang is not an installed language
3473 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3474 $newuser->lang = $CFG->lang;
3476 $newuser->confirmed = 1;
3477 $newuser->lastip = getremoteaddr();
3478 $newuser->timemodified = time();
3479 $newuser->mnethostid = $CFG->mnet_localhost_id;
3481 $newuser->id = $DB->insert_record('user', $newuser);
3482 $user = get_complete_user_data('id', $newuser->id);
3483 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3484 set_user_preference('auth_forcepasswordchange', 1, $user);
3486 update_internal_user_password($user, $password);
3488 // fetch full user record for the event, the complete user data contains too much info
3489 // and we want to be consistent with other places that trigger this event
3490 events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
3496 * Will update a local user record from an external source.
3497 * (MNET users can not be updated using this method!)
3499 * @param string $username user's username to update the record
3500 * @return stdClass A complete user object
3502 function update_user_record($username) {
3505 $username = trim(moodle_strtolower($username)); /// just in case check text case
3507 $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
3509 $userauth = get_auth_plugin($oldinfo->auth);
3511 if ($newinfo = $userauth->get_userinfo($username)) {
3512 $newinfo = truncate_userinfo($newinfo);
3513 foreach ($newinfo as $key => $value){
3514 $key = strtolower($key);
3515 if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id'
3516 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3517 // unknown or must not be changed
3520 $confval = $userauth->config->{'field_updatelocal_' . $key};
3521 $lockval = $userauth->config->{'field_lock_' . $key};
3522 if (empty($confval) || empty($lockval)) {
3525 if ($confval === 'onlogin') {
3526 // MDL-4207 Don't overwrite modified user profile values with
3527 // empty LDAP values when 'unlocked if empty' is set. The purpose
3528 // of the setting 'unlocked if empty' is to allow the user to fill
3529 // in a value for the selected field _if LDAP is giving
3530 // nothing_ for this field. Thus it makes sense to let this value
3531 // stand in until LDAP is giving a value for this field.
3532 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3533 if ((string)$oldinfo->$key !== (string)$value) {
3534 $newuser[$key] = (string)$value;
3540 $newuser['id'] = $oldinfo->id;
3541 $DB->update_record('user', $newuser);
3542 // fetch full user record for the event, the complete user data contains too much info
3543 // and we want to be consistent with other places that trigger this event
3544 events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id)));
3548 return get_complete_user_data('id', $oldinfo->id);
3552 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3553 * which may have large fields
3555 * @todo Add vartype handling to ensure $info is an array
3557 * @param array $info Array of user properties to truncate if needed
3558 * @return array The now truncated information that was passed in
3560 function truncate_userinfo($info) {
3561 // define the limits
3571 'institution' => 40,
3579 $textlib = textlib_get_instance();
3580 // apply where needed
3581 foreach (array_keys($info) as $key) {
3582 if (!empty($limit[$key])) {
3583 $info[$key] = trim($textlib->substr($info[$key],0, $limit[$key]));
3591 * Marks user deleted in internal user database and notifies the auth plugin.
3592 * Also unenrols user from all roles and does other cleanup.
3594 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3596 * @param stdClass $user full user object before delete
3597 * @return boolean always true
3599 function delete_user($user) {
3601 require_once($CFG->libdir.'/grouplib.php');
3602 require_once($CFG->libdir.'/gradelib.php');
3603 require_once($CFG->dirroot.'/message/lib.php');
3604 require_once($CFG->dirroot.'/tag/lib.php');
3606 // delete all grades - backup is kept in grade_grades_history table
3607 grade_user_delete($user->id);
3609 //move unread messages from this user to read
3610 message_move_userfrom_unread2read($user->id);
3612 // TODO: remove from cohorts using standard API here
3615 tag_set('user', $user->id, array());
3617 // unconditionally unenrol from all courses
3618 enrol_user_delete($user);
3620 // unenrol from all roles in all contexts
3621 role_unassign_all(array('userid'=>$user->id)); // this might be slow but it is really needed - modules might do some extra cleanup!
3623 //now do a brute force cleanup
3625 // remove from all cohorts
3626 $DB->delete_records('cohort_members', array('userid'=>$user->id));
3628 // remove from all groups
3629 $DB->delete_records('groups_members', array('userid'=>$user->id));
3631 // brute force unenrol from all courses
3632 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
3634 // purge user preferences
3635 $DB->delete_records('user_preferences', array('userid'=>$user->id));
3637 // purge user extra profile info
3638 $DB->delete_records('user_info_data', array('userid'=>$user->id));
3640 // last course access not necessary either
3641 $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
3643 // force logout - may fail if file based sessions used, sorry
3644 session_kill_user($user->id);
3646 // now do a final accesslib cleanup - removes all role assignments in user context and context itself
3647 delete_context(CONTEXT_USER, $user->id);
3649 // workaround for bulk deletes of users with the same email address
3650 $delname = "$user->email.".time();
3651 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3655 // mark internal user record as "deleted"
3656 $updateuser = new stdClass();
3657 $updateuser->id = $user->id;
3658 $updateuser->deleted = 1;
3659 $updateuser->username = $delname; // Remember it just in case
3660 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
3661 $updateuser->idnumber = ''; // Clear this field to free it up
3662 $updateuser->timemodified = time();
3664 $DB->update_record('user', $updateuser);
3666 // notify auth plugin - do not block the delete even when plugin fails
3667 $authplugin = get_auth_plugin($user->auth);
3668 $authplugin->user_delete($user);
3670 // any plugin that needs to cleanup should register this event
3671 events_trigger('user_deleted', $user);
3677 * Retrieve the guest user object
3681 * @return user A {@link $USER} object
3683 function guest_user() {
3686 if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
3687 $newuser->confirmed = 1;
3688 $newuser->lang = $CFG->lang;
3689 $newuser->lastip = getremoteaddr();
3696 * Authenticates a user against the chosen authentication mechanism
3698 * Given a username and password, this function looks them
3699 * up using the currently selected authentication mechanism,
3700 * and if the authentication is successful, it returns a
3701 * valid $user object from the 'user' table.
3703 * Uses auth_ functions from the currently active auth module
3705 * After authenticate_user_login() returns success, you will need to
3706 * log that the user has logged in, and call complete_user_login() to set
3709 * Note: this function works only with non-mnet accounts!
3711 * @param string $username User's username
3712 * @param string $password User's password
3713 * @return user|flase A {@link $USER} object or false if error
3715 function authenticate_user_login($username, $password) {
3718 $authsenabled = get_enabled_auth_plugins();
3720 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
3721 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
3722 if (!empty($user->suspended)) {
3723 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3724 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3727 if ($auth=='nologin' or !is_enabled_auth($auth)) {
3728 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3729 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3732 $auths = array($auth);
3735 // check if there's a deleted record (cheaply)
3736 if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
3737 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3741 // User does not exist
3742 $auths = $authsenabled;
3743 $user = new stdClass();
3747 foreach ($auths as $auth) {
3748 $authplugin = get_auth_plugin($auth);
3750 // on auth fail fall through to the next plugin
3751 if (!$authplugin->user_login($username, $password)) {
3755 // successful authentication
3756 if ($user->id) { // User already exists in database
3757 if (empty($user->auth)) { // For some reason auth isn't set yet
3758 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
3759 $user->auth = $auth;
3761 if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3762 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
3763 $user->firstaccess = $user->timemodified;
3766 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3768 if ($authplugin->is_synchronised_with_external()) { // update user record from external DB
3769 $user = update_user_record($username);
3772 // if user not found and user creation is not disabled, create it
3773 if (empty($CFG->authpreventaccountcreation)) {
3774 $user = create_user_record($username, $password, $auth);
3780 $authplugin->sync_roles($user);
3782 foreach ($authsenabled as $hau) {
3783 $hauth = get_auth_plugin($hau);
3784 $hauth->user_authenticated_hook($user, $username, $password);
3787 if (empty($user->id)) {
3791 if (!empty($user->suspended)) {
3792 // just in case some auth plugin suspended account
3793 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3794 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3801 // failed if all the plugins have failed
3802 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3803 if (debugging('', DEBUG_ALL)) {
3804 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3810 * Call to complete the user login process after authenticate_user_login()
3811 * has succeeded. It will setup the $USER variable and other required bits
3815 * - It will NOT log anything -- up to the caller to decide what to log.
3816 * - this function does not set any cookies any more!
3818 * @param object $user
3819 * @return object A {@link $USER} object - BC only, do not use
3821 function complete_user_login($user) {
3824 // regenerate session id and delete old session,
3825 // this helps prevent session fixation attacks from the same domain
3826 session_regenerate_id(true);
3828 // check enrolments, load caps and setup $USER object
3829 session_set_user($user);
3831 // reload preferences from DB
3832 unset($user->preference);
3833 check_user_preferences_loaded($user);
3835 // update login times
3836 update_user_login_times();
3838 // extra session prefs init
3839 set_login_session_preferences();
3841 if (isguestuser()) {
3842 // no need to continue when user is THE guest
3846 /// Select password change url
3847 $userauth = get_auth_plugin($USER->auth);
3849 /// check whether the user should be changing password
3850 if (get_user_preferences('auth_forcepasswordchange', false)){
3851 if ($userauth->can_change_password()) {
3852 if ($changeurl = $userauth->change_password_url()) {
3853 redirect($changeurl);
3855 redirect($CFG->httpswwwroot.'/login/change_password.php');
3858 print_error('nopasswordchangeforced', 'auth');
3865 * Compare password against hash stored in internal user table.
3866 * If necessary it also updates the stored hash to new format.
3868 * @param stdClass $user (password property may be updated)
3869 * @param string $password plain text password
3870 * @return bool is password valid?
3872 function validate_internal_user_password($user, $password) {
3875 if (!isset($CFG->passwordsaltmain)) {
3876 $CFG->passwordsaltmain = '';
3881 if ($user->password === 'not cached') {
3882 // internal password is not used at all, it can not validate
3884 } else if ($user->password === md5($password.$CFG->passwordsaltmain)
3885 or $user->password === md5($password)
3886 or $user->password === md5(addslashes($password).$CFG->passwordsaltmain)
3887 or $user->password === md5(addslashes($password))) {
3888 // note: we are intentionally using the addslashes() here because we
3889 // need to accept old password hashes of passwords with magic quotes
3893 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
3894 $alt = 'passwordsaltalt'.$i;
3895 if (!empty($CFG->$alt)) {
3896 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
3905 // force update of password hash using latest main password salt and encoding if needed
3906 update_internal_user_password($user, $password);
3913 * Calculate hashed value from password using current hash mechanism.
3915 * @param string $password
3916 * @return string password hash
3918 function hash_internal_user_password($password) {
3921 if (isset($CFG->passwordsaltmain)) {
3922 return md5($password.$CFG->passwordsaltmain);
3924 return md5($password);
3929 * Update password hash in user object.
3931 * @param stdClass $user (password property may be updated)
3932 * @param string $password plain text password
3933 * @return bool always returns true
3935 function update_internal_user_password($user, $password) {
3938 $authplugin = get_auth_plugin($user->auth);
3939 if ($authplugin->prevent_local_passwords()) {
3940 $hashedpassword = 'not cached';
3942 $hashedpassword = hash_internal_user_password($password);
3945 if ($user->password !== $hashedpassword) {
3946 $DB->set_field('user', 'password', $hashedpassword, array('id'=>$user->id));
3947 $user->password = $hashedpassword;
3954 * Get a complete user record, which includes all the info
3955 * in the user record.
3957 * Intended for setting as $USER session variable
3959 * @param string $field The user field to be checked for a given value.
3960 * @param string $value The value to match for $field.
3961 * @param int $mnethostid
3962 * @return mixed False, or A {@link $USER} object.
3964 function get_complete_user_data($field, $value, $mnethostid = null) {
3967 if (!$field || !$value) {
3971 /// Build the WHERE clause for an SQL query
3972 $params = array('fieldval'=>$value);
3973 $constraints = "$field = :fieldval AND deleted <> 1";
3975 // If we are loading user data based on anything other than id,
3976 // we must also restrict our search based on mnet host.
3977 if ($field != 'id') {
3978 if (empty($mnethostid)) {
3979 // if empty, we restrict to local users
3980 $mnethostid = $CFG->mnet_localhost_id;
3983 if (!empty($mnethostid)) {
3984 $params['mnethostid'] = $mnethostid;
3985 $constraints .= " AND mnethostid = :mnethostid";
3988 /// Get all the basic user data
3990 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
3994 /// Get various settings and preferences
3996 // preload preference cache
3997 check_user_preferences_loaded($user);
3999 // load course enrolment related stuff
4000 $user->lastcourseaccess = array(); // during last session
4001 $user->currentcourseaccess = array(); // during current session
4002 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid'=>$user->id))) {
4003 foreach ($lastaccesses as $lastaccess) {
4004 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4008 $sql = "SELECT g.id, g.courseid
4009 FROM {groups} g, {groups_members} gm
4010 WHERE gm.groupid=g.id AND gm.userid=?";
4012 // this is a special hack to speedup calendar display
4013 $user->groupmember = array();
4014 if (!isguestuser($user)) {
4015 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4016 foreach ($groups as $group) {
4017 if (!array_key_exists($group->courseid, $user->groupmember)) {
4018 $user->groupmember[$group->courseid] = array();
4020 $user->groupmember[$group->courseid][$group->id] = $group->id;
4025 /// Add the custom profile fields to the user record
4026 $user->profile = array();
4027 if (!isguestuser($user)) {
4028 require_once($CFG->dirroot.'/user/profile/lib.php');
4029 profile_load_custom_fields($user);
4032 /// Rewrite some variables if necessary
4033 if (!empty($user->description)) {
4034 $user->description = true; // No need to cart all of it around
4036 if (isguestuser($user)) {
4037 $user->lang = $CFG->lang; // Guest language always same as site
4038 $user->firstname = get_string('guestuser'); // Name always in current language
4039 $user->lastname = ' ';
4046 * Validate a password against the configured password policy
4049 * @param string $password the password to be checked against the password policy
4050 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4051 * @return bool true if the password is valid according to the policy. false otherwise.
4053 function check_password_policy($password, &$errmsg) {
4056 if (empty($CFG->passwordpolicy)) {
4060 $textlib = textlib_get_instance();
4062 if ($textlib->strlen($password) < $CFG->minpasswordlength) {
4063 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4066 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4067 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4070 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4071 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4074 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4075 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4078 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4079 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4081 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4082 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4085 if ($errmsg == '') {
4094 * When logging in, this function is run to set certain preferences
4095 * for the current SESSION
4100 function set_login_session_preferences() {
4101 global $SESSION, $CFG;
4103 $SESSION->justloggedin = true;
4105 unset($SESSION->lang);
4110 * Delete a course, including all related data from the database,
4111 * and any associated files.
4115 * @param mixed $courseorid The id of the course or course object to delete.
4116 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4117 * @return bool true if all the removals succeeded. false if there were any failures. If this
4118 * method returns false, some of the removals will probably have succeeded, and others
4119 * failed, but you have no way of knowing which.
4121 function delete_course($courseorid, $showfeedback = true) {
4124 if (is_object($courseorid)) {
4125 $courseid = $courseorid->id;
4126 $course = $courseorid;
4128 $courseid = $courseorid;
4129 if (!$course = $DB->get_record('course', array('id'=>$courseid))) {
4133 $context = get_context_instance(CONTEXT_COURSE, $courseid);
4135 // frontpage course can not be deleted!!
4136 if ($courseid == SITEID) {
4140 // make the course completely empty
4141 remove_course_contents($courseid, $showfeedback);
4143 // delete the course and related context instance
4144 delete_context(CONTEXT_COURSE, $courseid);
4145 $DB->delete_records("course", array("id"=>$courseid));
4148 $course->context = $context; // you can not fetch context in the event because it was already deleted
4149 events_trigger('course_deleted', $course);
4155 * Clear a course out completely, deleting all content
4156 * but don't delete the course itself.
4157 * This function does not verify any permissions.
4159 * Please note this function also deletes all user enrolments,
4160 * enrolment instances and role assignments.
4162 * @param int $courseid The id of the course that is being deleted
4163 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4164 * @return bool true if all the removals succeeded. false if there were any failures. If this
4165 * method returns false, some of the removals will probably have succeeded, and others
4166 * failed, but you have no way of knowing which.
4168 function remove_course_contents($courseid, $showfeedback = true) {
4169 global $CFG, $DB, $OUTPUT;
4170 require_once($CFG->libdir.'/completionlib.php');
4171 require_once($CFG->libdir.'/questionlib.php');
4172 require_once($CFG->libdir.'/gradelib.php');
4173 require_once($CFG->dirroot.'/group/lib.php');
4174 require_once($CFG->dirroot.'/tag/coursetagslib.php');
4176 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
4177 $context = get_context_instance(CONTEXT_COURSE, $courseid, MUST_EXIST);
4179 $strdeleted = get_string('deleted');
4181 // Delete course completion information,
4182 // this has to be done before grades and enrols
4183 $cc = new completion_info($course);
4184 $cc->clear_criteria();
4186 // remove roles and enrolments
4187 role_unassign_all(array('contextid'=>$context->id), true);
4188 enrol_course_delete($course);
4190 // Clean up course formats (iterate through all formats in the even the course format was ever changed)
4191 $formats = get_plugin_list('format');
4192 foreach ($formats as $format=>$formatdir) {
4193 $formatdelete = 'format_'.$format.'_delete_course';
4194 $formatlib = "$formatdir/lib.php";
4195 if (file_exists($formatlib)) {
4196 include_once($formatlib);
4197 if (function_exists($formatdelete)) {
4198 if ($showfeedback) {
4199 echo $OUTPUT->notification($strdeleted.' '.$format);
4201 $formatdelete($course->id);
4206 // Remove all data from gradebook - this needs to be done before course modules
4207 // because while deleting this information, the system may need to reference
4208 // the course modules that own the grades.
4209 remove_course_grades($courseid, $showfeedback);
4210 remove_grade_letters($context, $showfeedback);
4212 // Remove all data from availability and completion tables that is associated
4213 // with course-modules belonging to this course. Note this is done even if the
4214 // features are not enabled now, in case they were enabled previously
4215 $DB->delete_records_select('course_modules_completion',
4216 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4218 $DB->delete_records_select('course_modules_availability',
4219 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4222 // Delete course blocks - they may depend on modules so delete them first
4223 blocks_delete_all_for_context($context->id);
4225 // Delete every instance of every module
4226 if ($allmods = $DB->get_records('modules') ) {
4227 foreach ($allmods as $mod) {
4228 $modname = $mod->name;
4229 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
4230 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
4231 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
4233 if (file_exists($modfile)) {
4234 include_once($modfile);
4235 if (function_exists($moddelete)) {
4236 if ($instances = $DB->get_records($modname, array('course'=>$course->id))) {
4237 foreach ($instances as $instance) {
4238 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
4239 /// Delete activity context questions and question categories
4240 question_delete_activity($cm, $showfeedback);
4242 if ($moddelete($instance->id)) {
4246 echo $OUTPUT->notification('Could not delete '. $modname .' instance '. $instance->id .' ('. format_string($instance->name) .')');
4249 // delete cm and its context in correct order
4250 delete_context(CONTEXT_MODULE, $cm->id); // some callbacks may try to fetch context, better delete first
4251 $DB->delete_records('course_modules', array('id'=>$cm->id));
4256 //note: we should probably delete these anyway
4257 echo $OUTPUT->notification('Function '.$moddelete.'() doesn\'t exist!');
4260 if (function_exists($moddeletecourse)) {
4261 $moddeletecourse($course, $showfeedback);
4264 if ($showfeedback) {
4265 echo $OUTPUT->notification($strdeleted .' '. $count .' x '. $modname);
4270 // Delete any groups, removing members and grouping/course links first.
4271 groups_delete_groupings($course->id, $showfeedback);
4272 groups_delete_groups($course->id, $showfeedback);
4274 // Delete questions and question categories
4275 question_delete_course($course, $showfeedback);
4277 // Delete course tags
4278 coursetag_delete_course_tags($course->id, $showfeedback);
4280 // Delete legacy files (just in case some files are still left there after conversion to new file api)
4281 fulldelete($CFG->dataroot.'/'.$course->id);
4283 // cleanup course record - remove links to delted stuff
4284 $oldcourse = new stdClass();
4285 $oldcourse->id = $course->id;
4286 $oldcourse->summary = '';
4287 $oldcourse->modinfo = NULL;
4288 $oldcourse->legacyfiles = 0;
4289 $oldcourse->defaultgroupingid = 0;
4290 $oldcourse->enablecompletion = 0;
4291 $DB->update_record('course', $oldcourse);
4293 // Delete all related records in other tables that may have a courseid
4294 // This array stores the tables that need to be cleared, as
4295 // table_name => column_name that contains the course id.
4296 $tablestoclear = array(
4297 'event' => 'courseid', // Delete events
4298 'log' => 'course', // Delete logs
4299 'course_sections' => 'course', // Delete any course stuff
4300 'course_modules' => 'course',
4301 'course_display' => 'course',
4302 'backup_courses' => 'courseid', // Delete scheduled backup stuff
4303 'user_lastaccess' => 'courseid',
4304 'backup_log' => 'courseid'
4306 foreach ($tablestoclear as $table => $col) {
4307 $DB->delete_records($table, array($col=>$course->id));
4310 // Delete all remaining stuff linked to context,
4311 // such as remaining roles, files, comments, etc.
4312 // Keep the context record for now.
4313 delete_context(CONTEXT_COURSE, $course->id, false);
4316 $course->context = $context; // you can not access context in cron event later after course is deleted
4317 events_trigger('course_content_removed', $course);
4323 * Change dates in module - used from course reset.
4327 * @param string $modname forum, assignment, etc
4328 * @param array $fields array of date fields from mod table
4329 * @param int $timeshift time difference
4330 * @param int $courseid
4331 * @return bool success
4333 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid) {
4335 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
4338 foreach ($fields as $field) {
4339 $updatesql = "UPDATE {".$modname."}
4340 SET $field = $field + ?
4341 WHERE course=? AND $field<>0 AND $field<>0";
4342 $return = $DB->execute($updatesql, array($timeshift, $courseid)) && $return;
4345 $refreshfunction = $modname.'_refresh_events';
4346 if (function_exists($refreshfunction)) {
4347 $refreshfunction($courseid);
4354 * This function will empty a course of user data.
4355 * It will retain the activities and the structure of the course.
4357 * @param object $data an object containing all the settings including courseid (without magic quotes)
4358 * @return array status array of array component, item, error
4360 function reset_course_userdata($data) {
4361 global $CFG, $USER, $DB;