2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
83 define('PARAM_ALPHAEXT', 'alphaext');
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
98 define('PARAM_AUTH', 'auth');
101 * PARAM_BASE64 - Base 64 encoded format
103 define('PARAM_BASE64', 'base64');
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
108 define('PARAM_BOOL', 'bool');
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
114 define('PARAM_CAPABILITY', 'capability');
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119 * the input (required/optional_param or formslib) and then sanitse the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
123 define('PARAM_CLEANHTML', 'cleanhtml');
126 * PARAM_EMAIL - an email address following the RFC
128 define('PARAM_EMAIL', 'email');
131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
133 define('PARAM_FILE', 'file');
136 * PARAM_FLOAT - a real/floating point number.
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
146 define('PARAM_FLOAT', 'float');
149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
151 define('PARAM_HOST', 'host');
154 * PARAM_INT - integers only, use when expecting only numbers.
156 define('PARAM_INT', 'int');
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
161 define('PARAM_LANG', 'lang');
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
167 define('PARAM_LOCALURL', 'localurl');
170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
172 define('PARAM_NOTAGS', 'notags');
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
178 define('PARAM_PATH', 'path');
181 * PARAM_PEM - Privacy Enhanced Mail format
183 define('PARAM_PEM', 'pem');
186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
188 define('PARAM_PERMISSION', 'permission');
191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
193 define('PARAM_RAW', 'raw');
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
203 define('PARAM_SAFEDIR', 'safedir');
206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
208 define('PARAM_SAFEPATH', 'safepath');
211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
213 define('PARAM_SEQUENCE', 'sequence');
216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
218 define('PARAM_TAG', 'tag');
221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
223 define('PARAM_TAGLIST', 'taglist');
226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
228 define('PARAM_TEXT', 'text');
231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
233 define('PARAM_THEME', 'theme');
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
245 define('PARAM_USERNAME', 'username');
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
250 define('PARAM_STRINGID', 'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
256 * @deprecated since 2.0
258 define('PARAM_CLEAN', 'clean');
261 * PARAM_INTEGER - deprecated alias for PARAM_INT
262 * @deprecated since 2.0
264 define('PARAM_INTEGER', 'int');
267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268 * @deprecated since 2.0
270 define('PARAM_NUMBER', 'float');
273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274 * NOTE: originally alias for PARAM_APLHA
275 * @deprecated since 2.0
277 define('PARAM_ACTION', 'alphanumext');
280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
282 * @deprecated since 2.0
284 define('PARAM_FORMAT', 'alphanumext');
287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288 * @deprecated since 2.0
290 define('PARAM_MULTILANG', 'text');
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295 * America/Port-au-Prince)
297 define('PARAM_TIMEZONE', 'timezone');
300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
302 define('PARAM_CLEANFILE', 'file');
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
310 define('PARAM_COMPONENT', 'component');
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
317 define('PARAM_AREA', 'area');
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
324 define('PARAM_PLUGIN', 'plugin');
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
332 define('VALUE_REQUIRED', 1);
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
337 define('VALUE_OPTIONAL', 2);
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
342 define('VALUE_DEFAULT', 0);
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
347 define('NULL_NOT_ALLOWED', false);
350 * NULL_ALLOWED - the parameter can be set to null in the database
352 define('NULL_ALLOWED', true);
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
442 /** Unspecified module archetype */
443 define('MOD_ARCHETYPE_OTHER', 0);
444 /** Resource-like type module */
445 define('MOD_ARCHETYPE_RESOURCE', 1);
446 /** Assignment module archetype */
447 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448 /** System (not user-addable) module archetype */
449 define('MOD_ARCHETYPE_SYSTEM', 3);
452 * Return this from modname_get_types callback to use default display in activity chooser.
453 * Deprecated, will be removed in 3.5, TODO MDL-53697.
454 * @deprecated since Moodle 3.1
456 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
459 * Security token used for allowing access
460 * from external application such as web services.
461 * Scripts do not use any session, performance is relatively
462 * low because we need to load access info in each request.
463 * Scripts are executed in parallel.
465 define('EXTERNAL_TOKEN_PERMANENT', 0);
468 * Security token used for allowing access
469 * of embedded applications, the code is executed in the
470 * active user session. Token is invalidated after user logs out.
471 * Scripts are executed serially - normal session locking is used.
473 define('EXTERNAL_TOKEN_EMBEDDED', 1);
476 * The home page should be the site home
478 define('HOMEPAGE_SITE', 0);
480 * The home page should be the users my page
482 define('HOMEPAGE_MY', 1);
484 * The home page can be chosen by the user
486 define('HOMEPAGE_USER', 2);
489 * Hub directory url (should be moodle.org)
491 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
495 * Moodle.org url (should be moodle.org)
497 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
500 * Moodle mobile app service name
502 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
505 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
507 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
510 * Course display settings: display all sections on one page.
512 define('COURSE_DISPLAY_SINGLEPAGE', 0);
514 * Course display settings: split pages into a page per section.
516 define('COURSE_DISPLAY_MULTIPAGE', 1);
519 * Authentication constant: String used in password field when password is not stored.
521 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
523 // PARAMETER HANDLING.
526 * Returns a particular value for the named variable, taken from
527 * POST or GET. If the parameter doesn't exist then an error is
528 * thrown because we require this variable.
530 * This function should be used to initialise all required values
531 * in a script that are based on parameters. Usually it will be
533 * $id = required_param('id', PARAM_INT);
535 * Please note the $type parameter is now required and the value can not be array.
537 * @param string $parname the name of the page parameter we want
538 * @param string $type expected type of parameter
540 * @throws coding_exception
542 function required_param($parname, $type) {
543 if (func_num_args() != 2 or empty($parname) or empty($type)) {
544 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
546 // POST has precedence.
547 if (isset($_POST[$parname])) {
548 $param = $_POST[$parname];
549 } else if (isset($_GET[$parname])) {
550 $param = $_GET[$parname];
552 print_error('missingparam', '', '', $parname);
555 if (is_array($param)) {
556 debugging('Invalid array parameter detected in required_param(): '.$parname);
557 // TODO: switch to fatal error in Moodle 2.3.
558 return required_param_array($parname, $type);
561 return clean_param($param, $type);
565 * Returns a particular array value for the named variable, taken from
566 * POST or GET. If the parameter doesn't exist then an error is
567 * thrown because we require this variable.
569 * This function should be used to initialise all required values
570 * in a script that are based on parameters. Usually it will be
572 * $ids = required_param_array('ids', PARAM_INT);
574 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
576 * @param string $parname the name of the page parameter we want
577 * @param string $type expected type of parameter
579 * @throws coding_exception
581 function required_param_array($parname, $type) {
582 if (func_num_args() != 2 or empty($parname) or empty($type)) {
583 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
585 // POST has precedence.
586 if (isset($_POST[$parname])) {
587 $param = $_POST[$parname];
588 } else if (isset($_GET[$parname])) {
589 $param = $_GET[$parname];
591 print_error('missingparam', '', '', $parname);
593 if (!is_array($param)) {
594 print_error('missingparam', '', '', $parname);
598 foreach ($param as $key => $value) {
599 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
600 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
603 $result[$key] = clean_param($value, $type);
610 * Returns a particular value for the named variable, taken from
611 * POST or GET, otherwise returning a given default.
613 * This function should be used to initialise all optional values
614 * in a script that are based on parameters. Usually it will be
616 * $name = optional_param('name', 'Fred', PARAM_TEXT);
618 * Please note the $type parameter is now required and the value can not be array.
620 * @param string $parname the name of the page parameter we want
621 * @param mixed $default the default value to return if nothing is found
622 * @param string $type expected type of parameter
624 * @throws coding_exception
626 function optional_param($parname, $default, $type) {
627 if (func_num_args() != 3 or empty($parname) or empty($type)) {
628 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
631 // POST has precedence.
632 if (isset($_POST[$parname])) {
633 $param = $_POST[$parname];
634 } else if (isset($_GET[$parname])) {
635 $param = $_GET[$parname];
640 if (is_array($param)) {
641 debugging('Invalid array parameter detected in required_param(): '.$parname);
642 // TODO: switch to $default in Moodle 2.3.
643 return optional_param_array($parname, $default, $type);
646 return clean_param($param, $type);
650 * Returns a particular array value for the named variable, taken from
651 * POST or GET, otherwise returning a given default.
653 * This function should be used to initialise all optional values
654 * in a script that are based on parameters. Usually it will be
656 * $ids = optional_param('id', array(), PARAM_INT);
658 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
660 * @param string $parname the name of the page parameter we want
661 * @param mixed $default the default value to return if nothing is found
662 * @param string $type expected type of parameter
664 * @throws coding_exception
666 function optional_param_array($parname, $default, $type) {
667 if (func_num_args() != 3 or empty($parname) or empty($type)) {
668 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
671 // POST has precedence.
672 if (isset($_POST[$parname])) {
673 $param = $_POST[$parname];
674 } else if (isset($_GET[$parname])) {
675 $param = $_GET[$parname];
679 if (!is_array($param)) {
680 debugging('optional_param_array() expects array parameters only: '.$parname);
685 foreach ($param as $key => $value) {
686 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
687 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
690 $result[$key] = clean_param($value, $type);
697 * Strict validation of parameter values, the values are only converted
698 * to requested PHP type. Internally it is using clean_param, the values
699 * before and after cleaning must be equal - otherwise
700 * an invalid_parameter_exception is thrown.
701 * Objects and classes are not accepted.
703 * @param mixed $param
704 * @param string $type PARAM_ constant
705 * @param bool $allownull are nulls valid value?
706 * @param string $debuginfo optional debug information
707 * @return mixed the $param value converted to PHP type
708 * @throws invalid_parameter_exception if $param is not of given type
710 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
711 if (is_null($param)) {
712 if ($allownull == NULL_ALLOWED) {
715 throw new invalid_parameter_exception($debuginfo);
718 if (is_array($param) or is_object($param)) {
719 throw new invalid_parameter_exception($debuginfo);
722 $cleaned = clean_param($param, $type);
724 if ($type == PARAM_FLOAT) {
725 // Do not detect precision loss here.
726 if (is_float($param) or is_int($param)) {
728 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
729 throw new invalid_parameter_exception($debuginfo);
731 } else if ((string)$param !== (string)$cleaned) {
732 // Conversion to string is usually lossless.
733 throw new invalid_parameter_exception($debuginfo);
740 * Makes sure array contains only the allowed types, this function does not validate array key names!
743 * $options = clean_param($options, PARAM_INT);
746 * @param array $param the variable array we are cleaning
747 * @param string $type expected format of param after cleaning.
748 * @param bool $recursive clean recursive arrays
750 * @throws coding_exception
752 function clean_param_array(array $param = null, $type, $recursive = false) {
753 // Convert null to empty array.
754 $param = (array)$param;
755 foreach ($param as $key => $value) {
756 if (is_array($value)) {
758 $param[$key] = clean_param_array($value, $type, true);
760 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
763 $param[$key] = clean_param($value, $type);
770 * Used by {@link optional_param()} and {@link required_param()} to
771 * clean the variables and/or cast to specific types, based on
774 * $course->format = clean_param($course->format, PARAM_ALPHA);
775 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
778 * @param mixed $param the variable we are cleaning
779 * @param string $type expected format of param after cleaning.
781 * @throws coding_exception
783 function clean_param($param, $type) {
786 if (is_array($param)) {
787 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
788 } else if (is_object($param)) {
789 if (method_exists($param, '__toString')) {
790 $param = $param->__toString();
792 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
798 // No cleaning at all.
799 $param = fix_utf8($param);
802 case PARAM_RAW_TRIMMED:
803 // No cleaning, but strip leading and trailing whitespace.
804 $param = fix_utf8($param);
808 // General HTML cleaning, try to use more specific type if possible this is deprecated!
809 // Please use more specific type instead.
810 if (is_numeric($param)) {
813 $param = fix_utf8($param);
814 // Sweep for scripts, etc.
815 return clean_text($param);
817 case PARAM_CLEANHTML:
818 // Clean html fragment.
819 $param = fix_utf8($param);
820 // Sweep for scripts, etc.
821 $param = clean_text($param, FORMAT_HTML);
825 // Convert to integer.
830 return (float)$param;
833 // Remove everything not `a-z`.
834 return preg_replace('/[^a-zA-Z]/i', '', $param);
837 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
838 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
841 // Remove everything not `a-zA-Z0-9`.
842 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
844 case PARAM_ALPHANUMEXT:
845 // Remove everything not `a-zA-Z0-9_-`.
846 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
849 // Remove everything not `0-9,`.
850 return preg_replace('/[^0-9,]/i', '', $param);
853 // Convert to 1 or 0.
854 $tempstr = strtolower($param);
855 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
857 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
860 $param = empty($param) ? 0 : 1;
866 $param = fix_utf8($param);
867 return strip_tags($param);
870 // Leave only tags needed for multilang.
871 $param = fix_utf8($param);
872 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
873 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
875 if (strpos($param, '</lang>') !== false) {
876 // Old and future mutilang syntax.
877 $param = strip_tags($param, '<lang>');
878 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
882 foreach ($matches[0] as $match) {
883 if ($match === '</lang>') {
891 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
902 } else if (strpos($param, '</span>') !== false) {
903 // Current problematic multilang syntax.
904 $param = strip_tags($param, '<span>');
905 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
909 foreach ($matches[0] as $match) {
910 if ($match === '</span>') {
918 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
930 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
931 return strip_tags($param);
933 case PARAM_COMPONENT:
934 // We do not want any guessing here, either the name is correct or not
935 // please note only normalised component names are accepted.
936 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
939 if (strpos($param, '__') !== false) {
942 if (strpos($param, 'mod_') === 0) {
943 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
944 if (substr_count($param, '_') != 1) {
952 // We do not want any guessing here, either the name is correct or not.
953 if (!is_valid_plugin_name($param)) {
959 // Remove everything not a-zA-Z0-9_- .
960 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
963 // Remove everything not a-zA-Z0-9/_- .
964 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
967 // Strip all suspicious characters from filename.
968 $param = fix_utf8($param);
969 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
970 if ($param === '.' || $param === '..') {
976 // Strip all suspicious characters from file path.
977 $param = fix_utf8($param);
978 $param = str_replace('\\', '/', $param);
980 // Explode the path and clean each element using the PARAM_FILE rules.
981 $breadcrumb = explode('/', $param);
982 foreach ($breadcrumb as $key => $crumb) {
983 if ($crumb === '.' && $key === 0) {
984 // Special condition to allow for relative current path such as ./currentdirfile.txt.
986 $crumb = clean_param($crumb, PARAM_FILE);
988 $breadcrumb[$key] = $crumb;
990 $param = implode('/', $breadcrumb);
992 // Remove multiple current path (./././) and multiple slashes (///).
993 $param = preg_replace('~//+~', '/', $param);
994 $param = preg_replace('~/(\./)+~', '/', $param);
998 // Allow FQDN or IPv4 dotted quad.
999 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1000 // Match ipv4 dotted quad.
1001 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1002 // Confirm values are ok.
1003 if ( $match[0] > 255
1006 || $match[4] > 255 ) {
1007 // Hmmm, what kind of dotted quad is this?
1010 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1011 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1012 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1014 // All is ok - $param is respected.
1021 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1022 $param = fix_utf8($param);
1023 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1024 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1025 // All is ok, param is respected.
1032 case PARAM_LOCALURL:
1033 // Allow http absolute, root relative and relative URLs within wwwroot.
1034 $param = clean_param($param, PARAM_URL);
1035 if (!empty($param)) {
1037 // Simulate the HTTPS version of the site.
1038 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1040 if ($param === $CFG->wwwroot) {
1042 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1044 } else if (preg_match(':^/:', $param)) {
1045 // Root-relative, ok!
1046 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1047 // Absolute, and matches our wwwroot.
1048 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1049 // Absolute, and matches our httpswwwroot.
1051 // Relative - let's make sure there are no tricks.
1052 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1062 $param = trim($param);
1063 // PEM formatted strings may contain letters/numbers and the symbols:
1067 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1068 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1069 list($wholething, $body) = $matches;
1070 unset($wholething, $matches);
1071 $b64 = clean_param($body, PARAM_BASE64);
1073 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1081 if (!empty($param)) {
1082 // PEM formatted strings may contain letters/numbers and the symbols
1086 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1089 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1090 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1091 // than (or equal to) 64 characters long.
1092 for ($i=0, $j=count($lines); $i < $j; $i++) {
1094 if (64 < strlen($lines[$i])) {
1100 if (64 != strlen($lines[$i])) {
1104 return implode("\n", $lines);
1110 $param = fix_utf8($param);
1111 // Please note it is not safe to use the tag name directly anywhere,
1112 // it must be processed with s(), urlencode() before embedding anywhere.
1113 // Remove some nasties.
1114 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1115 // Convert many whitespace chars into one.
1116 $param = preg_replace('/\s+/u', ' ', $param);
1117 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1121 $param = fix_utf8($param);
1122 $tags = explode(',', $param);
1124 foreach ($tags as $tag) {
1125 $res = clean_param($tag, PARAM_TAG);
1131 return implode(',', $result);
1136 case PARAM_CAPABILITY:
1137 if (get_capability_info($param)) {
1143 case PARAM_PERMISSION:
1144 $param = (int)$param;
1145 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1152 $param = clean_param($param, PARAM_PLUGIN);
1153 if (empty($param)) {
1155 } else if (exists_auth_plugin($param)) {
1162 $param = clean_param($param, PARAM_SAFEDIR);
1163 if (get_string_manager()->translation_exists($param)) {
1166 // Specified language is not installed or param malformed.
1171 $param = clean_param($param, PARAM_PLUGIN);
1172 if (empty($param)) {
1174 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1176 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1179 // Specified theme is not installed.
1183 case PARAM_USERNAME:
1184 $param = fix_utf8($param);
1185 $param = trim($param);
1186 // Convert uppercase to lowercase MDL-16919.
1187 $param = core_text::strtolower($param);
1188 if (empty($CFG->extendedusernamechars)) {
1189 $param = str_replace(" " , "", $param);
1190 // Regular expression, eliminate all chars EXCEPT:
1191 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1192 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1197 $param = fix_utf8($param);
1198 if (validate_email($param)) {
1204 case PARAM_STRINGID:
1205 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1211 case PARAM_TIMEZONE:
1212 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1213 $param = fix_utf8($param);
1214 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1215 if (preg_match($timezonepattern, $param)) {
1222 // Doh! throw error, switched parameters in optional_param or another serious problem.
1223 print_error("unknownparamtype", '', '', $type);
1228 * Makes sure the data is using valid utf8, invalid characters are discarded.
1230 * Note: this function is not intended for full objects with methods and private properties.
1232 * @param mixed $value
1233 * @return mixed with proper utf-8 encoding
1235 function fix_utf8($value) {
1236 if (is_null($value) or $value === '') {
1239 } else if (is_string($value)) {
1240 if ((string)(int)$value === $value) {
1244 // No null bytes expected in our data, so let's remove it.
1245 $value = str_replace("\0", '', $value);
1247 // Note: this duplicates min_fix_utf8() intentionally.
1248 static $buggyiconv = null;
1249 if ($buggyiconv === null) {
1250 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1254 if (function_exists('mb_convert_encoding')) {
1255 $subst = mb_substitute_character();
1256 mb_substitute_character('');
1257 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1258 mb_substitute_character($subst);
1261 // Warn admins on admin/index.php page.
1266 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1271 } else if (is_array($value)) {
1272 foreach ($value as $k => $v) {
1273 $value[$k] = fix_utf8($v);
1277 } else if (is_object($value)) {
1278 // Do not modify original.
1279 $value = clone($value);
1280 foreach ($value as $k => $v) {
1281 $value->$k = fix_utf8($v);
1286 // This is some other type, no utf-8 here.
1292 * Return true if given value is integer or string with integer value
1294 * @param mixed $value String or Int
1295 * @return bool true if number, false if not
1297 function is_number($value) {
1298 if (is_int($value)) {
1300 } else if (is_string($value)) {
1301 return ((string)(int)$value) === $value;
1308 * Returns host part from url.
1310 * @param string $url full url
1311 * @return string host, null if not found
1313 function get_host_from_url($url) {
1314 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1322 * Tests whether anything was returned by text editor
1324 * This function is useful for testing whether something you got back from
1325 * the HTML editor actually contains anything. Sometimes the HTML editor
1326 * appear to be empty, but actually you get back a <br> tag or something.
1328 * @param string $string a string containing HTML.
1329 * @return boolean does the string contain any actual content - that is text,
1330 * images, objects, etc.
1332 function html_is_blank($string) {
1333 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1337 * Set a key in global configuration
1339 * Set a key/value pair in both this session's {@link $CFG} global variable
1340 * and in the 'config' database table for future sessions.
1342 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1343 * In that case it doesn't affect $CFG.
1345 * A NULL value will delete the entry.
1347 * NOTE: this function is called from lib/db/upgrade.php
1349 * @param string $name the key to set
1350 * @param string $value the value to set (without magic quotes)
1351 * @param string $plugin (optional) the plugin scope, default null
1352 * @return bool true or exception
1354 function set_config($name, $value, $plugin=null) {
1357 if (empty($plugin)) {
1358 if (!array_key_exists($name, $CFG->config_php_settings)) {
1359 // So it's defined for this invocation at least.
1360 if (is_null($value)) {
1363 // Settings from db are always strings.
1364 $CFG->$name = (string)$value;
1368 if ($DB->get_field('config', 'name', array('name' => $name))) {
1369 if ($value === null) {
1370 $DB->delete_records('config', array('name' => $name));
1372 $DB->set_field('config', 'value', $value, array('name' => $name));
1375 if ($value !== null) {
1376 $config = new stdClass();
1377 $config->name = $name;
1378 $config->value = $value;
1379 $DB->insert_record('config', $config, false);
1382 if ($name === 'siteidentifier') {
1383 cache_helper::update_site_identifier($value);
1385 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1388 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1389 if ($value===null) {
1390 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1392 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1395 if ($value !== null) {
1396 $config = new stdClass();
1397 $config->plugin = $plugin;
1398 $config->name = $name;
1399 $config->value = $value;
1400 $DB->insert_record('config_plugins', $config, false);
1403 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1410 * Get configuration values from the global config table
1411 * or the config_plugins table.
1413 * If called with one parameter, it will load all the config
1414 * variables for one plugin, and return them as an object.
1416 * If called with 2 parameters it will return a string single
1417 * value or false if the value is not found.
1419 * NOTE: this function is called from lib/db/upgrade.php
1421 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1422 * that we need only fetch it once per request.
1423 * @param string $plugin full component name
1424 * @param string $name default null
1425 * @return mixed hash-like object or single value, return false no config found
1426 * @throws dml_exception
1428 function get_config($plugin, $name = null) {
1431 static $siteidentifier = null;
1433 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1434 $forced =& $CFG->config_php_settings;
1438 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1439 $forced =& $CFG->forced_plugin_settings[$plugin];
1446 if ($siteidentifier === null) {
1448 // This may fail during installation.
1449 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1450 // install the database.
1451 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1452 } catch (dml_exception $ex) {
1453 // Set siteidentifier to false. We don't want to trip this continually.
1454 $siteidentifier = false;
1459 if (!empty($name)) {
1460 if (array_key_exists($name, $forced)) {
1461 return (string)$forced[$name];
1462 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1463 return $siteidentifier;
1467 $cache = cache::make('core', 'config');
1468 $result = $cache->get($plugin);
1469 if ($result === false) {
1470 // The user is after a recordset.
1472 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1474 // This part is not really used any more, but anyway...
1475 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1477 $cache->set($plugin, $result);
1480 if (!empty($name)) {
1481 if (array_key_exists($name, $result)) {
1482 return $result[$name];
1487 if ($plugin === 'core') {
1488 $result['siteidentifier'] = $siteidentifier;
1491 foreach ($forced as $key => $value) {
1492 if (is_null($value) or is_array($value) or is_object($value)) {
1493 // We do not want any extra mess here, just real settings that could be saved in db.
1494 unset($result[$key]);
1496 // Convert to string as if it went through the DB.
1497 $result[$key] = (string)$value;
1501 return (object)$result;
1505 * Removes a key from global configuration.
1507 * NOTE: this function is called from lib/db/upgrade.php
1509 * @param string $name the key to set
1510 * @param string $plugin (optional) the plugin scope
1511 * @return boolean whether the operation succeeded.
1513 function unset_config($name, $plugin=null) {
1516 if (empty($plugin)) {
1518 $DB->delete_records('config', array('name' => $name));
1519 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1521 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1522 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1529 * Remove all the config variables for a given plugin.
1531 * NOTE: this function is called from lib/db/upgrade.php
1533 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1534 * @return boolean whether the operation succeeded.
1536 function unset_all_config_for_plugin($plugin) {
1538 // Delete from the obvious config_plugins first.
1539 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1540 // Next delete any suspect settings from config.
1541 $like = $DB->sql_like('name', '?', true, true, false, '|');
1542 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1543 $DB->delete_records_select('config', $like, $params);
1544 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1545 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1551 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1553 * All users are verified if they still have the necessary capability.
1555 * @param string $value the value of the config setting.
1556 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1557 * @param bool $includeadmins include administrators.
1558 * @return array of user objects.
1560 function get_users_from_config($value, $capability, $includeadmins = true) {
1561 if (empty($value) or $value === '$@NONE@$') {
1565 // We have to make sure that users still have the necessary capability,
1566 // it should be faster to fetch them all first and then test if they are present
1567 // instead of validating them one-by-one.
1568 $users = get_users_by_capability(context_system::instance(), $capability);
1569 if ($includeadmins) {
1570 $admins = get_admins();
1571 foreach ($admins as $admin) {
1572 $users[$admin->id] = $admin;
1576 if ($value === '$@ALL@$') {
1580 $result = array(); // Result in correct order.
1581 $allowed = explode(',', $value);
1582 foreach ($allowed as $uid) {
1583 if (isset($users[$uid])) {
1584 $user = $users[$uid];
1585 $result[$user->id] = $user;
1594 * Invalidates browser caches and cached data in temp.
1596 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1597 * {@link phpunit_util::reset_dataroot()}
1601 function purge_all_caches() {
1604 reset_text_filters_cache();
1605 js_reset_all_caches();
1606 theme_reset_all_caches();
1607 get_string_manager()->reset_caches();
1608 core_text::reset_caches();
1609 if (class_exists('core_plugin_manager')) {
1610 core_plugin_manager::reset_caches();
1613 // Bump up cacherev field for all courses.
1615 increment_revision_number('course', 'cacherev', '');
1616 } catch (moodle_exception $e) {
1617 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1620 $DB->reset_caches();
1621 cache_helper::purge_all();
1623 // Purge all other caches: rss, simplepie, etc.
1624 remove_dir($CFG->cachedir.'', true);
1626 // Make sure cache dir is writable, throws exception if not.
1627 make_cache_directory('');
1629 // This is the only place where we purge local caches, we are only adding files there.
1630 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1631 remove_dir($CFG->localcachedir, true);
1632 set_config('localcachedirpurged', time());
1633 make_localcache_directory('', true);
1634 \core\task\manager::clear_static_caches();
1638 * Get volatile flags
1640 * @param string $type
1641 * @param int $changedsince default null
1642 * @return array records array
1644 function get_cache_flags($type, $changedsince = null) {
1647 $params = array('type' => $type, 'expiry' => time());
1648 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1649 if ($changedsince !== null) {
1650 $params['changedsince'] = $changedsince;
1651 $sqlwhere .= " AND timemodified > :changedsince";
1654 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1655 foreach ($flags as $flag) {
1656 $cf[$flag->name] = $flag->value;
1663 * Get volatile flags
1665 * @param string $type
1666 * @param string $name
1667 * @param int $changedsince default null
1668 * @return string|false The cache flag value or false
1670 function get_cache_flag($type, $name, $changedsince=null) {
1673 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1675 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1676 if ($changedsince !== null) {
1677 $params['changedsince'] = $changedsince;
1678 $sqlwhere .= " AND timemodified > :changedsince";
1681 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1685 * Set a volatile flag
1687 * @param string $type the "type" namespace for the key
1688 * @param string $name the key to set
1689 * @param string $value the value to set (without magic quotes) - null will remove the flag
1690 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1691 * @return bool Always returns true
1693 function set_cache_flag($type, $name, $value, $expiry = null) {
1696 $timemodified = time();
1697 if ($expiry === null || $expiry < $timemodified) {
1698 $expiry = $timemodified + 24 * 60 * 60;
1700 $expiry = (int)$expiry;
1703 if ($value === null) {
1704 unset_cache_flag($type, $name);
1708 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1709 // This is a potential problem in DEBUG_DEVELOPER.
1710 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1711 return true; // No need to update.
1714 $f->expiry = $expiry;
1715 $f->timemodified = $timemodified;
1716 $DB->update_record('cache_flags', $f);
1718 $f = new stdClass();
1719 $f->flagtype = $type;
1722 $f->expiry = $expiry;
1723 $f->timemodified = $timemodified;
1724 $DB->insert_record('cache_flags', $f);
1730 * Removes a single volatile flag
1732 * @param string $type the "type" namespace for the key
1733 * @param string $name the key to set
1736 function unset_cache_flag($type, $name) {
1738 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1743 * Garbage-collect volatile flags
1745 * @return bool Always returns true
1747 function gc_cache_flags() {
1749 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1753 // USER PREFERENCE API.
1756 * Refresh user preference cache. This is used most often for $USER
1757 * object that is stored in session, but it also helps with performance in cron script.
1759 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1762 * @category preference
1764 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1765 * @param int $cachelifetime Cache life time on the current page (in seconds)
1766 * @throws coding_exception
1769 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1771 // Static cache, we need to check on each page load, not only every 2 minutes.
1772 static $loadedusers = array();
1774 if (!isset($user->id)) {
1775 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1778 if (empty($user->id) or isguestuser($user->id)) {
1779 // No permanent storage for not-logged-in users and guest.
1780 if (!isset($user->preference)) {
1781 $user->preference = array();
1788 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1789 // Already loaded at least once on this page. Are we up to date?
1790 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1791 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1794 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1795 // No change since the lastcheck on this page.
1796 $user->preference['_lastloaded'] = $timenow;
1801 // OK, so we have to reload all preferences.
1802 $loadedusers[$user->id] = true;
1803 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1804 $user->preference['_lastloaded'] = $timenow;
1808 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1810 * NOTE: internal function, do not call from other code.
1814 * @param integer $userid the user whose prefs were changed.
1816 function mark_user_preferences_changed($userid) {
1819 if (empty($userid) or isguestuser($userid)) {
1820 // No cache flags for guest and not-logged-in users.
1824 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1828 * Sets a preference for the specified user.
1830 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1833 * @category preference
1835 * @param string $name The key to set as preference for the specified user
1836 * @param string $value The value to set for the $name key in the specified user's
1837 * record, null means delete current value.
1838 * @param stdClass|int|null $user A moodle user object or id, null means current user
1839 * @throws coding_exception
1840 * @return bool Always true or exception
1842 function set_user_preference($name, $value, $user = null) {
1845 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1846 throw new coding_exception('Invalid preference name in set_user_preference() call');
1849 if (is_null($value)) {
1850 // Null means delete current.
1851 return unset_user_preference($name, $user);
1852 } else if (is_object($value)) {
1853 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1854 } else if (is_array($value)) {
1855 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1857 // Value column maximum length is 1333 characters.
1858 $value = (string)$value;
1859 if (core_text::strlen($value) > 1333) {
1860 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1863 if (is_null($user)) {
1865 } else if (isset($user->id)) {
1866 // It is a valid object.
1867 } else if (is_numeric($user)) {
1868 $user = (object)array('id' => (int)$user);
1870 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1873 check_user_preferences_loaded($user);
1875 if (empty($user->id) or isguestuser($user->id)) {
1876 // No permanent storage for not-logged-in users and guest.
1877 $user->preference[$name] = $value;
1881 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1882 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1883 // Preference already set to this value.
1886 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1889 $preference = new stdClass();
1890 $preference->userid = $user->id;
1891 $preference->name = $name;
1892 $preference->value = $value;
1893 $DB->insert_record('user_preferences', $preference);
1896 // Update value in cache.
1897 $user->preference[$name] = $value;
1899 // Set reload flag for other sessions.
1900 mark_user_preferences_changed($user->id);
1906 * Sets a whole array of preferences for the current user
1908 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1911 * @category preference
1913 * @param array $prefarray An array of key/value pairs to be set
1914 * @param stdClass|int|null $user A moodle user object or id, null means current user
1915 * @return bool Always true or exception
1917 function set_user_preferences(array $prefarray, $user = null) {
1918 foreach ($prefarray as $name => $value) {
1919 set_user_preference($name, $value, $user);
1925 * Unsets a preference completely by deleting it from the database
1927 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1930 * @category preference
1932 * @param string $name The key to unset as preference for the specified user
1933 * @param stdClass|int|null $user A moodle user object or id, null means current user
1934 * @throws coding_exception
1935 * @return bool Always true or exception
1937 function unset_user_preference($name, $user = null) {
1940 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1941 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1944 if (is_null($user)) {
1946 } else if (isset($user->id)) {
1947 // It is a valid object.
1948 } else if (is_numeric($user)) {
1949 $user = (object)array('id' => (int)$user);
1951 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1954 check_user_preferences_loaded($user);
1956 if (empty($user->id) or isguestuser($user->id)) {
1957 // No permanent storage for not-logged-in user and guest.
1958 unset($user->preference[$name]);
1963 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1965 // Delete the preference from cache.
1966 unset($user->preference[$name]);
1968 // Set reload flag for other sessions.
1969 mark_user_preferences_changed($user->id);
1975 * Used to fetch user preference(s)
1977 * If no arguments are supplied this function will return
1978 * all of the current user preferences as an array.
1980 * If a name is specified then this function
1981 * attempts to return that particular preference value. If
1982 * none is found, then the optional value $default is returned,
1985 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1988 * @category preference
1990 * @param string $name Name of the key to use in finding a preference value
1991 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1992 * @param stdClass|int|null $user A moodle user object or id, null means current user
1993 * @throws coding_exception
1994 * @return string|mixed|null A string containing the value of a single preference. An
1995 * array with all of the preferences or null
1997 function get_user_preferences($name = null, $default = null, $user = null) {
2000 if (is_null($name)) {
2002 } else if (is_numeric($name) or $name === '_lastloaded') {
2003 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2006 if (is_null($user)) {
2008 } else if (isset($user->id)) {
2009 // Is a valid object.
2010 } else if (is_numeric($user)) {
2011 $user = (object)array('id' => (int)$user);
2013 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2016 check_user_preferences_loaded($user);
2020 return $user->preference;
2021 } else if (isset($user->preference[$name])) {
2022 // The single string value.
2023 return $user->preference[$name];
2025 // Default value (null if not specified).
2030 // FUNCTIONS FOR HANDLING TIME.
2033 * Given Gregorian date parts in user time produce a GMT timestamp.
2037 * @param int $year The year part to create timestamp of
2038 * @param int $month The month part to create timestamp of
2039 * @param int $day The day part to create timestamp of
2040 * @param int $hour The hour part to create timestamp of
2041 * @param int $minute The minute part to create timestamp of
2042 * @param int $second The second part to create timestamp of
2043 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2044 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2045 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2046 * applied only if timezone is 99 or string.
2047 * @return int GMT timestamp
2049 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2050 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2051 $date->setDate((int)$year, (int)$month, (int)$day);
2052 $date->setTime((int)$hour, (int)$minute, (int)$second);
2054 $time = $date->getTimestamp();
2056 // Moodle BC DST stuff.
2058 $time += dst_offset_on($time, $timezone);
2066 * Format a date/time (seconds) as weeks, days, hours etc as needed
2068 * Given an amount of time in seconds, returns string
2069 * formatted nicely as weeks, days, hours etc as needed
2077 * @param int $totalsecs Time in seconds
2078 * @param stdClass $str Should be a time object
2079 * @return string A nicely formatted date/time string
2081 function format_time($totalsecs, $str = null) {
2083 $totalsecs = abs($totalsecs);
2086 // Create the str structure the slow way.
2087 $str = new stdClass();
2088 $str->day = get_string('day');
2089 $str->days = get_string('days');
2090 $str->hour = get_string('hour');
2091 $str->hours = get_string('hours');
2092 $str->min = get_string('min');
2093 $str->mins = get_string('mins');
2094 $str->sec = get_string('sec');
2095 $str->secs = get_string('secs');
2096 $str->year = get_string('year');
2097 $str->years = get_string('years');
2100 $years = floor($totalsecs/YEARSECS);
2101 $remainder = $totalsecs - ($years*YEARSECS);
2102 $days = floor($remainder/DAYSECS);
2103 $remainder = $totalsecs - ($days*DAYSECS);
2104 $hours = floor($remainder/HOURSECS);
2105 $remainder = $remainder - ($hours*HOURSECS);
2106 $mins = floor($remainder/MINSECS);
2107 $secs = $remainder - ($mins*MINSECS);
2109 $ss = ($secs == 1) ? $str->sec : $str->secs;
2110 $sm = ($mins == 1) ? $str->min : $str->mins;
2111 $sh = ($hours == 1) ? $str->hour : $str->hours;
2112 $sd = ($days == 1) ? $str->day : $str->days;
2113 $sy = ($years == 1) ? $str->year : $str->years;
2122 $oyears = $years .' '. $sy;
2125 $odays = $days .' '. $sd;
2128 $ohours = $hours .' '. $sh;
2131 $omins = $mins .' '. $sm;
2134 $osecs = $secs .' '. $ss;
2138 return trim($oyears .' '. $odays);
2141 return trim($odays .' '. $ohours);
2144 return trim($ohours .' '. $omins);
2147 return trim($omins .' '. $osecs);
2152 return get_string('now');
2156 * Returns a formatted string that represents a date in user time.
2160 * @param int $date the timestamp in UTC, as obtained from the database.
2161 * @param string $format strftime format. You should probably get this using
2162 * get_string('strftime...', 'langconfig');
2163 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2164 * not 99 then daylight saving will not be added.
2165 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2166 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2167 * If false then the leading zero is maintained.
2168 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2169 * @return string the formatted date/time.
2171 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2172 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2173 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2177 * Returns a formatted date ensuring it is UTF-8.
2179 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2180 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2182 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2183 * @param string $format strftime format.
2184 * @param int|float|string $tz the user timezone
2185 * @return string the formatted date/time.
2186 * @since Moodle 2.3.3
2188 function date_format_string($date, $format, $tz = 99) {
2191 $localewincharset = null;
2192 // Get the calendar type user is using.
2193 if ($CFG->ostype == 'WINDOWS') {
2194 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2195 $localewincharset = $calendartype->locale_win_charset();
2198 if ($localewincharset) {
2199 $format = core_text::convert($format, 'utf-8', $localewincharset);
2202 date_default_timezone_set(core_date::get_user_timezone($tz));
2203 $datestring = strftime($format, $date);
2204 core_date::set_default_server_timezone();
2206 if ($localewincharset) {
2207 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2214 * Given a $time timestamp in GMT (seconds since epoch),
2215 * returns an array that represents the Gregorian date in user time
2219 * @param int $time Timestamp in GMT
2220 * @param float|int|string $timezone user timezone
2221 * @return array An array that represents the date in user time
2223 function usergetdate($time, $timezone=99) {
2224 date_default_timezone_set(core_date::get_user_timezone($timezone));
2225 $result = getdate($time);
2226 core_date::set_default_server_timezone();
2232 * Given a GMT timestamp (seconds since epoch), offsets it by
2233 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2235 * NOTE: this function does not include DST properly,
2236 * you should use the PHP date stuff instead!
2240 * @param int $date Timestamp in GMT
2241 * @param float|int|string $timezone user timezone
2244 function usertime($date, $timezone=99) {
2245 $userdate = new DateTime('@' . $date);
2246 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2247 $dst = dst_offset_on($date, $timezone);
2249 return $date - $userdate->getOffset() + $dst;
2253 * Given a time, return the GMT timestamp of the most recent midnight
2254 * for the current user.
2258 * @param int $date Timestamp in GMT
2259 * @param float|int|string $timezone user timezone
2260 * @return int Returns a GMT timestamp
2262 function usergetmidnight($date, $timezone=99) {
2264 $userdate = usergetdate($date, $timezone);
2266 // Time of midnight of this user's day, in GMT.
2267 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2272 * Returns a string that prints the user's timezone
2276 * @param float|int|string $timezone user timezone
2279 function usertimezone($timezone=99) {
2280 $tz = core_date::get_user_timezone($timezone);
2281 return core_date::get_localised_timezone($tz);
2285 * Returns a float or a string which denotes the user's timezone
2286 * 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)
2287 * means that for this timezone there are also DST rules to be taken into account
2288 * Checks various settings and picks the most dominant of those which have a value
2292 * @param float|int|string $tz timezone to calculate GMT time offset before
2293 * calculating user timezone, 99 is default user timezone
2294 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2295 * @return float|string
2297 function get_user_timezone($tz = 99) {
2302 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2303 isset($USER->timezone) ? $USER->timezone : 99,
2304 isset($CFG->timezone) ? $CFG->timezone : 99,
2309 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2310 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2311 $tz = $next['value'];
2313 return is_numeric($tz) ? (float) $tz : $tz;
2317 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2318 * - Note: Daylight saving only works for string timezones and not for float.
2322 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2323 * @param int|float|string $strtimezone user timezone
2326 function dst_offset_on($time, $strtimezone = null) {
2327 $tz = core_date::get_user_timezone($strtimezone);
2328 $date = new DateTime('@' . $time);
2329 $date->setTimezone(new DateTimeZone($tz));
2330 if ($date->format('I') == '1') {
2331 if ($tz === 'Australia/Lord_Howe') {
2340 * Calculates when the day appears in specific month
2344 * @param int $startday starting day of the month
2345 * @param int $weekday The day when week starts (normally taken from user preferences)
2346 * @param int $month The month whose day is sought
2347 * @param int $year The year of the month whose day is sought
2350 function find_day_in_month($startday, $weekday, $month, $year) {
2351 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2353 $daysinmonth = days_in_month($month, $year);
2354 $daysinweek = count($calendartype->get_weekdays());
2356 if ($weekday == -1) {
2357 // Don't care about weekday, so return:
2358 // abs($startday) if $startday != -1
2359 // $daysinmonth otherwise.
2360 return ($startday == -1) ? $daysinmonth : abs($startday);
2363 // From now on we 're looking for a specific weekday.
2364 // Give "end of month" its actual value, since we know it.
2365 if ($startday == -1) {
2366 $startday = -1 * $daysinmonth;
2369 // Starting from day $startday, the sign is the direction.
2370 if ($startday < 1) {
2371 $startday = abs($startday);
2372 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2374 // This is the last such weekday of the month.
2375 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2376 if ($lastinmonth > $daysinmonth) {
2377 $lastinmonth -= $daysinweek;
2380 // Find the first such weekday <= $startday.
2381 while ($lastinmonth > $startday) {
2382 $lastinmonth -= $daysinweek;
2385 return $lastinmonth;
2387 $indexweekday = dayofweek($startday, $month, $year);
2389 $diff = $weekday - $indexweekday;
2391 $diff += $daysinweek;
2394 // This is the first such weekday of the month equal to or after $startday.
2395 $firstfromindex = $startday + $diff;
2397 return $firstfromindex;
2402 * Calculate the number of days in a given month
2406 * @param int $month The month whose day count is sought
2407 * @param int $year The year of the month whose day count is sought
2410 function days_in_month($month, $year) {
2411 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2412 return $calendartype->get_num_days_in_month($year, $month);
2416 * Calculate the position in the week of a specific calendar day
2420 * @param int $day The day of the date whose position in the week is sought
2421 * @param int $month The month of the date whose position in the week is sought
2422 * @param int $year The year of the date whose position in the week is sought
2425 function dayofweek($day, $month, $year) {
2426 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2427 return $calendartype->get_weekday($year, $month, $day);
2430 // USER AUTHENTICATION AND LOGIN.
2433 * Returns full login url.
2435 * @return string login url
2437 function get_login_url() {
2440 $url = "$CFG->wwwroot/login/index.php";
2442 if (!empty($CFG->loginhttps)) {
2443 $url = str_replace('http:', 'https:', $url);
2450 * This function checks that the current user is logged in and has the
2451 * required privileges
2453 * This function checks that the current user is logged in, and optionally
2454 * whether they are allowed to be in a particular course and view a particular
2456 * If they are not logged in, then it redirects them to the site login unless
2457 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2458 * case they are automatically logged in as guests.
2459 * If $courseid is given and the user is not enrolled in that course then the
2460 * user is redirected to the course enrolment page.
2461 * If $cm is given and the course module is hidden and the user is not a teacher
2462 * in the course then the user is redirected to the course home page.
2464 * When $cm parameter specified, this function sets page layout to 'module'.
2465 * You need to change it manually later if some other layout needed.
2467 * @package core_access
2470 * @param mixed $courseorid id of the course or course object
2471 * @param bool $autologinguest default true
2472 * @param object $cm course module object
2473 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2474 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2475 * in order to keep redirects working properly. MDL-14495
2476 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2477 * @return mixed Void, exit, and die depending on path
2478 * @throws coding_exception
2479 * @throws require_login_exception
2481 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2482 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2484 // Must not redirect when byteserving already started.
2485 if (!empty($_SERVER['HTTP_RANGE'])) {
2486 $preventredirect = true;
2490 // We cannot redirect for AJAX scripts either.
2491 $preventredirect = true;
2494 // Setup global $COURSE, themes, language and locale.
2495 if (!empty($courseorid)) {
2496 if (is_object($courseorid)) {
2497 $course = $courseorid;
2498 } else if ($courseorid == SITEID) {
2499 $course = clone($SITE);
2501 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2504 if ($cm->course != $course->id) {
2505 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2507 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2508 if (!($cm instanceof cm_info)) {
2509 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2510 // db queries so this is not really a performance concern, however it is obviously
2511 // better if you use get_fast_modinfo to get the cm before calling this.
2512 $modinfo = get_fast_modinfo($course);
2513 $cm = $modinfo->get_cm($cm->id);
2517 // Do not touch global $COURSE via $PAGE->set_course(),
2518 // the reasons is we need to be able to call require_login() at any time!!
2521 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2525 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2526 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2527 // risk leading the user back to the AJAX request URL.
2528 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2529 $setwantsurltome = false;
2532 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2533 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2534 if ($preventredirect) {
2535 throw new require_login_session_timeout_exception();
2537 if ($setwantsurltome) {
2538 $SESSION->wantsurl = qualified_me();
2540 redirect(get_login_url());
2544 // If the user is not even logged in yet then make sure they are.
2545 if (!isloggedin()) {
2546 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2547 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2548 // Misconfigured site guest, just redirect to login page.
2549 redirect(get_login_url());
2550 exit; // Never reached.
2552 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2553 complete_user_login($guest);
2554 $USER->autologinguest = true;
2555 $SESSION->lang = $lang;
2557 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2558 if ($preventredirect) {
2559 throw new require_login_exception('You are not logged in');
2562 if ($setwantsurltome) {
2563 $SESSION->wantsurl = qualified_me();
2566 $referer = get_local_referer(false);
2567 if (!empty($referer)) {
2568 $SESSION->fromurl = $referer;
2571 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2572 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2573 foreach($authsequence as $authname) {
2574 $authplugin = get_auth_plugin($authname);
2575 $authplugin->pre_loginpage_hook();
2581 // If we're still not logged in then go to the login page
2582 if (!isloggedin()) {
2583 redirect(get_login_url());
2584 exit; // Never reached.
2589 // Loginas as redirection if needed.
2590 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2591 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2592 if ($USER->loginascontext->instanceid != $course->id) {
2593 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2598 // Check whether the user should be changing password (but only if it is REALLY them).
2599 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2600 $userauth = get_auth_plugin($USER->auth);
2601 if ($userauth->can_change_password() and !$preventredirect) {
2602 if ($setwantsurltome) {
2603 $SESSION->wantsurl = qualified_me();
2605 if ($changeurl = $userauth->change_password_url()) {
2606 // Use plugin custom url.
2607 redirect($changeurl);
2609 // Use moodle internal method.
2610 if (empty($CFG->loginhttps)) {
2611 redirect($CFG->wwwroot .'/login/change_password.php');
2613 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2614 redirect($wwwroot .'/login/change_password.php');
2618 print_error('nopasswordchangeforced', 'auth');
2622 // Check that the user account is properly set up.
2623 if (user_not_fully_set_up($USER)) {
2624 if ($preventredirect) {
2625 throw new require_login_exception('User not fully set-up');
2627 if ($setwantsurltome) {
2628 $SESSION->wantsurl = qualified_me();
2630 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2633 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2636 // Do not bother admins with any formalities.
2637 if (is_siteadmin()) {
2638 // Set the global $COURSE.
2640 $PAGE->set_cm($cm, $course);
2641 $PAGE->set_pagelayout('incourse');
2642 } else if (!empty($courseorid)) {
2643 $PAGE->set_course($course);
2645 // Set accesstime or the user will appear offline which messes up messaging.
2646 user_accesstime_log($course->id);
2650 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2651 if (!$USER->policyagreed and !is_siteadmin()) {
2652 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2653 if ($preventredirect) {
2654 throw new require_login_exception('Policy not agreed');
2656 if ($setwantsurltome) {
2657 $SESSION->wantsurl = qualified_me();
2659 redirect($CFG->wwwroot .'/user/policy.php');
2660 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2661 if ($preventredirect) {
2662 throw new require_login_exception('Policy not agreed');
2664 if ($setwantsurltome) {
2665 $SESSION->wantsurl = qualified_me();
2667 redirect($CFG->wwwroot .'/user/policy.php');
2671 // Fetch the system context, the course context, and prefetch its child contexts.
2672 $sysctx = context_system::instance();
2673 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2675 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2680 // If the site is currently under maintenance, then print a message.
2681 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2682 if ($preventredirect) {
2683 throw new require_login_exception('Maintenance in progress');
2686 print_maintenance_message();
2689 // Make sure the course itself is not hidden.
2690 if ($course->id == SITEID) {
2691 // Frontpage can not be hidden.
2693 if (is_role_switched($course->id)) {
2694 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2696 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2697 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2698 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2699 if ($preventredirect) {
2700 throw new require_login_exception('Course is hidden');
2702 $PAGE->set_context(null);
2703 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2704 // the navigation will mess up when trying to find it.
2705 navigation_node::override_active_url(new moodle_url('/'));
2706 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2711 // Is the user enrolled?
2712 if ($course->id == SITEID) {
2713 // Everybody is enrolled on the frontpage.
2715 if (\core\session\manager::is_loggedinas()) {
2716 // Make sure the REAL person can access this course first.
2717 $realuser = \core\session\manager::get_realuser();
2718 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2719 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2720 if ($preventredirect) {
2721 throw new require_login_exception('Invalid course login-as access');
2723 $PAGE->set_context(null);
2724 echo $OUTPUT->header();
2725 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2731 if (is_role_switched($course->id)) {
2732 // Ok, user had to be inside this course before the switch.
2735 } else if (is_viewing($coursecontext, $USER)) {
2736 // Ok, no need to mess with enrol.
2740 if (isset($USER->enrol['enrolled'][$course->id])) {
2741 if ($USER->enrol['enrolled'][$course->id] > time()) {
2743 if (isset($USER->enrol['tempguest'][$course->id])) {
2744 unset($USER->enrol['tempguest'][$course->id]);
2745 remove_temp_course_roles($coursecontext);
2749 unset($USER->enrol['enrolled'][$course->id]);
2752 if (isset($USER->enrol['tempguest'][$course->id])) {
2753 if ($USER->enrol['tempguest'][$course->id] == 0) {
2755 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2759 unset($USER->enrol['tempguest'][$course->id]);
2760 remove_temp_course_roles($coursecontext);
2766 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2767 if ($until !== false) {
2768 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2770 $until = ENROL_MAX_TIMESTAMP;
2772 $USER->enrol['enrolled'][$course->id] = $until;
2776 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2777 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2778 $enrols = enrol_get_plugins(true);
2779 // First ask all enabled enrol instances in course if they want to auto enrol user.
2780 foreach ($instances as $instance) {
2781 if (!isset($enrols[$instance->enrol])) {
2784 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2785 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2786 if ($until !== false) {
2788 $until = ENROL_MAX_TIMESTAMP;
2790 $USER->enrol['enrolled'][$course->id] = $until;
2795 // If not enrolled yet try to gain temporary guest access.
2797 foreach ($instances as $instance) {
2798 if (!isset($enrols[$instance->enrol])) {
2801 // Get a duration for the guest access, a timestamp in the future or false.
2802 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2803 if ($until !== false and $until > time()) {
2804 $USER->enrol['tempguest'][$course->id] = $until;
2815 if ($preventredirect) {
2816 throw new require_login_exception('Not enrolled');
2818 if ($setwantsurltome) {
2819 $SESSION->wantsurl = qualified_me();
2821 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2825 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2826 if ($cm && !$cm->uservisible) {
2827 if ($preventredirect) {
2828 throw new require_login_exception('Activity is hidden');
2830 if ($course->id != SITEID) {
2831 $url = new moodle_url('/course/view.php', array('id' => $course->id));
2833 $url = new moodle_url('/');
2835 redirect($url, get_string('activityiscurrentlyhidden'));
2838 // Set the global $COURSE.
2840 $PAGE->set_cm($cm, $course);
2841 $PAGE->set_pagelayout('incourse');
2842 } else if (!empty($courseorid)) {
2843 $PAGE->set_course($course);
2846 // Finally access granted, update lastaccess times.
2847 user_accesstime_log($course->id);
2852 * This function just makes sure a user is logged out.
2854 * @package core_access
2857 function require_logout() {
2860 if (!isloggedin()) {
2861 // This should not happen often, no need for hooks or events here.
2862 \core\session\manager::terminate_current();
2866 // Execute hooks before action.
2867 $authplugins = array();
2868 $authsequence = get_enabled_auth_plugins();
2869 foreach ($authsequence as $authname) {
2870 $authplugins[$authname] = get_auth_plugin($authname);
2871 $authplugins[$authname]->prelogout_hook();
2874 // Store info that gets removed during logout.
2875 $sid = session_id();
2876 $event = \core\event\user_loggedout::create(
2878 'userid' => $USER->id,
2879 'objectid' => $USER->id,
2880 'other' => array('sessionid' => $sid),
2883 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2884 $event->add_record_snapshot('sessions', $session);
2887 // Clone of $USER object to be used by auth plugins.
2888 $user = fullclone($USER);
2890 // Delete session record and drop $_SESSION content.
2891 \core\session\manager::terminate_current();
2893 // Trigger event AFTER action.
2896 // Hook to execute auth plugins redirection after event trigger.
2897 foreach ($authplugins as $authplugin) {
2898 $authplugin->postlogout_hook($user);
2903 * Weaker version of require_login()
2905 * This is a weaker version of {@link require_login()} which only requires login
2906 * when called from within a course rather than the site page, unless
2907 * the forcelogin option is turned on.
2908 * @see require_login()
2910 * @package core_access
2913 * @param mixed $courseorid The course object or id in question
2914 * @param bool $autologinguest Allow autologin guests if that is wanted
2915 * @param object $cm Course activity module if known
2916 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2917 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2918 * in order to keep redirects working properly. MDL-14495
2919 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2921 * @throws coding_exception
2923 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2924 global $CFG, $PAGE, $SITE;
2925 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2926 or (!is_object($courseorid) and $courseorid == SITEID));
2927 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2928 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2929 // db queries so this is not really a performance concern, however it is obviously
2930 // better if you use get_fast_modinfo to get the cm before calling this.
2931 if (is_object($courseorid)) {
2932 $course = $courseorid;
2934 $course = clone($SITE);
2936 $modinfo = get_fast_modinfo($course);
2937 $cm = $modinfo->get_cm($cm->id);
2939 if (!empty($CFG->forcelogin)) {
2940 // Login required for both SITE and courses.
2941 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2943 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2944 // Always login for hidden activities.
2945 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2947 } else if ($issite) {
2948 // Login for SITE not required.
2949 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
2950 if (!empty($courseorid)) {
2951 if (is_object($courseorid)) {
2952 $course = $courseorid;
2954 $course = clone $SITE;
2957 if ($cm->course != $course->id) {
2958 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2960 $PAGE->set_cm($cm, $course);
2961 $PAGE->set_pagelayout('incourse');
2963 $PAGE->set_course($course);
2966 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
2967 $PAGE->set_course($PAGE->course);
2969 user_accesstime_log(SITEID);
2973 // Course login always required.
2974 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2979 * Require key login. Function terminates with error if key not found or incorrect.
2981 * @uses NO_MOODLE_COOKIES
2982 * @uses PARAM_ALPHANUM
2983 * @param string $script unique script identifier
2984 * @param int $instance optional instance id
2985 * @return int Instance ID
2987 function require_user_key_login($script, $instance=null) {
2990 if (!NO_MOODLE_COOKIES) {
2991 print_error('sessioncookiesdisable');
2995 \core\session\manager::write_close();
2997 $keyvalue = required_param('key', PARAM_ALPHANUM);
2999 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3000 print_error('invalidkey');
3003 if (!empty($key->validuntil) and $key->validuntil < time()) {
3004 print_error('expiredkey');
3007 if ($key->iprestriction) {
3008 $remoteaddr = getremoteaddr(null);
3009 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3010 print_error('ipmismatch');
3014 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3015 print_error('invaliduserid');
3018 // Emulate normal session.
3019 enrol_check_plugins($user);
3020 \core\session\manager::set_user($user);
3022 // Note we are not using normal login.
3023 if (!defined('USER_KEY_LOGIN')) {
3024 define('USER_KEY_LOGIN', true);
3027 // Return instance id - it might be empty.
3028 return $key->instance;
3032 * Creates a new private user access key.
3034 * @param string $script unique target identifier
3035 * @param int $userid
3036 * @param int $instance optional instance id
3037 * @param string $iprestriction optional ip restricted access
3038 * @param timestamp $validuntil key valid only until given data
3039 * @return string access key value
3041 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3044 $key = new stdClass();
3045 $key->script = $script;
3046 $key->userid = $userid;
3047 $key->instance = $instance;
3048 $key->iprestriction = $iprestriction;
3049 $key->validuntil = $validuntil;
3050 $key->timecreated = time();
3052 // Something long and unique.
3053 $key->value = md5($userid.'_'.time().random_string(40));
3054 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3056 $key->value = md5($userid.'_'.time().random_string(40));
3058 $DB->insert_record('user_private_key', $key);
3063 * Delete the user's new private user access keys for a particular script.
3065 * @param string $script unique target identifier
3066 * @param int $userid
3069 function delete_user_key($script, $userid) {
3071 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3075 * Gets a private user access key (and creates one if one doesn't exist).
3077 * @param string $script unique target identifier
3078 * @param int $userid
3079 * @param int $instance optional instance id
3080 * @param string $iprestriction optional ip restricted access
3081 * @param timestamp $validuntil key valid only until given data
3082 * @return string access key value
3084 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3087 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3088 'instance' => $instance, 'iprestriction' => $iprestriction,
3089 'validuntil' => $validuntil))) {
3092 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3098 * Modify the user table by setting the currently logged in user's last login to now.
3100 * @return bool Always returns true
3102 function update_user_login_times() {
3105 if (isguestuser()) {
3106 // Do not update guest access times/ips for performance.
3112 $user = new stdClass();
3113 $user->id = $USER->id;
3115 // Make sure all users that logged in have some firstaccess.
3116 if ($USER->firstaccess == 0) {
3117 $USER->firstaccess = $user->firstaccess = $now;
3120 // Store the previous current as lastlogin.
3121 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3123 $USER->currentlogin = $user->currentlogin = $now;
3125 // Function user_accesstime_log() may not update immediately, better do it here.
3126 $USER->lastaccess = $user->lastaccess = $now;
3127 $USER->lastip = $user->lastip = getremoteaddr();
3129 // Note: do not call user_update_user() here because this is part of the login process,
3130 // the login event means that these fields were updated.
3131 $DB->update_record('user', $user);
3136 * Determines if a user has completed setting up their account.
3138 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3141 function user_not_fully_set_up($user) {
3142 if (isguestuser($user)) {
3145 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3149 * Check whether the user has exceeded the bounce threshold
3151 * @param stdClass $user A {@link $USER} object
3152 * @return bool true => User has exceeded bounce threshold
3154 function over_bounce_threshold($user) {
3157 if (empty($CFG->handlebounces)) {
3161 if (empty($user->id)) {
3162 // No real (DB) user, nothing to do here.
3166 // Set sensible defaults.
3167 if (empty($CFG->minbounces)) {
3168 $CFG->minbounces = 10;
3170 if (empty($CFG->bounceratio)) {
3171 $CFG->bounceratio = .20;
3175 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3176 $bouncecount = $bounce->value;
3178 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3179 $sendcount = $send->value;
3181 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3185 * Used to increment or reset email sent count
3187 * @param stdClass $user object containing an id
3188 * @param bool $reset will reset the count to 0
3191 function set_send_count($user, $reset=false) {
3194 if (empty($user->id)) {
3195 // No real (DB) user, nothing to do here.
3199 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3200 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3201 $DB->update_record('user_preferences', $pref);
3202 } else if (!empty($reset)) {
3203 // If it's not there and we're resetting, don't bother. Make a new one.
3204 $pref = new stdClass();
3205 $pref->name = 'email_send_count';
3207 $pref->userid = $user->id;
3208 $DB->insert_record('user_preferences', $pref, false);
3213 * Increment or reset user's email bounce count
3215 * @param stdClass $user object containing an id
3216 * @param bool $reset will reset the count to 0
3218 function set_bounce_count($user, $reset=false) {
3221 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3222 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3223 $DB->update_record('user_preferences', $pref);
3224 } else if (!empty($reset)) {
3225 // If it's not there and we're resetting, don't bother. Make a new one.
3226 $pref = new stdClass();
3227 $pref->name = 'email_bounce_count';
3229 $pref->userid = $user->id;
3230 $DB->insert_record('user_preferences', $pref, false);
3235 * Determines if the logged in user is currently moving an activity
3237 * @param int $courseid The id of the course being tested
3240 function ismoving($courseid) {
3243 if (!empty($USER->activitycopy)) {
3244 return ($USER->activitycopycourse == $courseid);
3250 * Returns a persons full name
3252 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3253 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3256 * @param stdClass $user A {@link $USER} object to get full name of.
3257 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3260 function fullname($user, $override=false) {
3261 global $CFG, $SESSION;
3263 if (!isset($user->firstname) and !isset($user->lastname)) {
3267 // Get all of the name fields.
3268 $allnames = get_all_user_name_fields();
3269 if ($CFG->debugdeveloper) {
3270 foreach ($allnames as $allname) {
3271 if (!property_exists($user, $allname)) {
3272 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3273 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3274 // Message has been sent, no point in sending the message multiple times.
3281 if (!empty($CFG->forcefirstname)) {
3282 $user->firstname = $CFG->forcefirstname;
3284 if (!empty($CFG->forcelastname)) {
3285 $user->lastname = $CFG->forcelastname;
3289 if (!empty($SESSION->fullnamedisplay)) {
3290 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3294 // If the fullnamedisplay setting is available, set the template to that.
3295 if (isset($CFG->fullnamedisplay)) {
3296 $template = $CFG->fullnamedisplay;
3298 // If the template is empty, or set to language, return the language string.
3299 if ((empty($template) || $template == 'language') && !$override) {
3300 return get_string('fullnamedisplay', null, $user);
3303 // Check to see if we are displaying according to the alternative full name format.
3305 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3306 // Default to show just the user names according to the fullnamedisplay string.
3307 return get_string('fullnamedisplay', null, $user);
3309 // If the override is true, then change the template to use the complete name.
3310 $template = $CFG->alternativefullnameformat;
3314 $requirednames = array();
3315 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3316 foreach ($allnames as $allname) {
3317 if (strpos($template, $allname) !== false) {
3318 $requirednames[] = $allname;
3322 $displayname = $template;
3323 // Switch in the actual data into the template.
3324 foreach ($requirednames as $altname) {
3325 if (isset($user->$altname)) {
3326 // Using empty() on the below if statement causes breakages.
3327 if ((string)$user->$altname == '') {
3328 $displayname = str_replace($altname, 'EMPTY', $displayname);
3330 $displayname = str_replace($altname, $user->$altname, $displayname);
3333 $displayname = str_replace($altname, 'EMPTY', $displayname);
3336 // Tidy up any misc. characters (Not perfect, but gets most characters).
3337 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3338 // katakana and parenthesis.
3339 $patterns = array();
3340 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3341 // filled in by a user.
3342 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3343 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3344 // This regular expression is to remove any double spaces in the display name.
3345 $patterns[] = '/\s{2,}/u';
3346 foreach ($patterns as $pattern) {
3347 $displayname = preg_replace($pattern, ' ', $displayname);
3350 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3351 $displayname = trim($displayname);
3352 if (empty($displayname)) {
3353 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3354 // people in general feel is a good setting to fall back on.
3355 $displayname = $user->firstname;
3357 return $displayname;
3361 * A centralised location for the all name fields. Returns an array / sql string snippet.
3363 * @param bool $returnsql True for an sql select field snippet.
3364 * @param string $tableprefix table query prefix to use in front of each field.
3365 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3366 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3367 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3368 * @return array|string All name fields.
3370 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3371 // This array is provided in this order because when called by fullname() (above) if firstname is before
3372 // firstnamephonetic str_replace() will change the wrong placeholder.
3373 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3374 'lastnamephonetic' => 'lastnamephonetic',
3375 'middlename' => 'middlename',
3376 'alternatename' => 'alternatename',
3377 'firstname' => 'firstname',
3378 'lastname' => 'lastname');
3380 // Let's add a prefix to the array of user name fields if provided.
3382 foreach ($alternatenames as $key => $altname) {
3383 $alternatenames[$key] = $prefix . $altname;
3387 // If we want the end result to have firstname and lastname at the front / top of the result.
3389 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3390 for ($i = 0; $i < 2; $i++) {
3391 // Get the last element.
3392 $lastelement = end($alternatenames);
3393 // Remove it from the array.
3394 unset($alternatenames[$lastelement]);
3395 // Put the element back on the top of the array.
3396 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3400 // Create an sql field snippet if requested.
3404 foreach ($alternatenames as $key => $altname) {
3405 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3408 foreach ($alternatenames as $key => $altname) {
3409 $alternatenames[$key] = $tableprefix . '.' . $altname;
3413 $alternatenames = implode(',', $alternatenames);
3415 return $alternatenames;
3419 * Reduces lines of duplicated code for getting user name fields.
3421 * See also {@link user_picture::unalias()}
3423 * @param object $addtoobject Object to add user name fields to.
3424 * @param object $secondobject Object that contains user name field information.
3425 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3426 * @param array $additionalfields Additional fields to be matched with data in the second object.
3427 * The key can be set to the user table field name.
3428 * @return object User name fields.
3430 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3431 $fields = get_all_user_name_fields(false, null, $prefix);
3432 if ($additionalfields) {
3433 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3434 // the key is a number and then sets the key to the array value.
3435 foreach ($additionalfields as $key => $value) {
3436 if (is_numeric($key)) {
3437 $additionalfields[$value] = $prefix . $value;
3438 unset($additionalfields[$key]);
3440 $additionalfields[$key] = $prefix . $value;
3443 $fields = array_merge($fields, $additionalfields);
3445 foreach ($fields as $key => $field) {
3446 // Important that we have all of the user name fields present in the object that we are sending back.
3447 $addtoobject->$key = '';
3448 if (isset($secondobject->$field)) {
3449 $addtoobject->$key = $secondobject->$field;
3452 return $addtoobject;
3456 * Returns an array of values in order of occurance in a provided string.
3457 * The key in the result is the character postion in the string.
3459 * @param array $values Values to be found in the string format
3460 * @param string $stringformat The string which may contain values being searched for.
3461 * @return array An array of values in order according to placement in the string format.
3463 function order_in_string($values, $stringformat) {
3464 $valuearray = array();
3465 foreach ($values as $value) {
3466 $pattern = "/$value\b/";
3467 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3468 if (preg_match($pattern, $stringformat)) {
3469 $replacement = "thing";
3470 // Replace the value with something more unique to ensure we get the right position when using strpos().
3471 $newformat = preg_replace($pattern, $replacement, $stringformat);
3472 $position = strpos($newformat, $replacement);
3473 $valuearray[$position] = $value;
3481 * Checks if current user is shown any extra fields when listing users.
3483 * @param object $context Context
3484 * @param array $already Array of fields that we're going to show anyway
3485 * so don't bother listing them
3486 * @return array Array of field names from user table, not including anything
3487 * listed in $already
3489 function get_extra_user_fields($context, $already = array()) {
3492 // Only users with permission get the extra fields.
3493 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3497 // Split showuseridentity on comma.
3498 if (empty($CFG->showuseridentity)) {
3499 // Explode gives wrong result with empty string.
3502 $extra = explode(',', $CFG->showuseridentity);
3505 foreach ($extra as $key => $field) {
3506 if (in_array($field, $already)) {
3507 unset($extra[$key]);
3512 // For consistency, if entries are removed from array, renumber it
3513 // so they are numbered as you would expect.
3514 $extra = array_merge($extra);
3520 * If the current user is to be shown extra user fields when listing or
3521 * selecting users, returns a string suitable for including in an SQL select
3522 * clause to retrieve those fields.
3524 * @param context $context Context
3525 * @param string $alias Alias of user table, e.g. 'u' (default none)
3526 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3527 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3528 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3530 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3531 $fields = get_extra_user_fields($context, $already);
3533 // Add punctuation for alias.
3534 if ($alias !== '') {
3537 foreach ($fields as $field) {
3538 $result .= ', ' . $alias . $field;
3540 $result .= ' AS ' . $prefix . $field;
3547 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3548 * @param string $field Field name, e.g. 'phone1'
3549 * @return string Text description taken from language file, e.g. 'Phone number'
3551 function get_user_field_name($field) {
3552 // Some fields have language strings which are not the same as field name.
3555 return get_string('webpage');
3558 return get_string('icqnumber');
3561 return get_string('skypeid');
3564 return get_string('aimid');
3567 return get_string('yahooid');
3570 return get_string('msnid');
3573 // Otherwise just use the same lang string.
3574 return get_string($field);
3578 * Returns whether a given authentication plugin exists.
3580 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3581 * @return boolean Whether the plugin is available.
3583 function exists_auth_plugin($auth) {
3586 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3587 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3593 * Checks if a given plugin is in the list of enabled authentication plugins.
3595 * @param string $auth Authentication plugin.
3596 * @return boolean Whether the plugin is enabled.
3598 function is_enabled_auth($auth) {
3603 $enabled = get_enabled_auth_plugins();
3605 return in_array($auth, $enabled);
3609 * Returns an authentication plugin instance.
3611 * @param string $auth name of authentication plugin
3612 * @return auth_plugin_base An instance of the required authentication plugin.
3614 function get_auth_plugin($auth) {
3617 // Check the plugin exists first.
3618 if (! exists_auth_plugin($auth)) {
3619 print_error('authpluginnotfound', 'debug', '', $auth);
3622 // Return auth plugin instance.
3623 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3624 $class = "auth_plugin_$auth";
3629 * Returns array of active auth plugins.
3631 * @param bool $fix fix $CFG->auth if needed
3634 function get_enabled_auth_plugins($fix=false) {
3637 $default = array('manual', 'nologin');
3639 if (empty($CFG->auth)) {
3642 $auths = explode(',', $CFG->auth);
3646 $auths = array_unique($auths);
3647 foreach ($auths as $k => $authname) {
3648 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3652 $newconfig = implode(',', $auths);
3653 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3654 set_config('auth', $newconfig);
3658 return (array_merge($default, $auths));
3662 * Returns true if an internal authentication method is being used.
3663 * if method not specified then, global default is assumed
3665 * @param string $auth Form of authentication required
3668 function is_internal_auth($auth) {
3669 // Throws error if bad $auth.
3670 $authplugin = get_auth_plugin($auth);
3671 return $authplugin->is_internal();
3675 * Returns true if the user is a 'restored' one.
3677 * Used in the login process to inform the user and allow him/her to reset the password
3679 * @param string $username username to be checked
3682 function is_restored_user($username) {
3685 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3689 * Returns an array of user fields
3691 * @return array User field/column names
3693 function get_user_fieldnames() {
3696 $fieldarray = $DB->get_columns('user');
3697 unset($fieldarray['id']);
3698 $fieldarray = array_keys($fieldarray);
3704 * Creates a bare-bones user record
3706 * @todo Outline auth types and provide code example
3708 * @param string $username New user's username to add to record
3709 * @param string $password New user's password to add to record
3710 * @param string $auth Form of authentication required
3711 * @return stdClass A complete user object
3713 function create_user_record($username, $password, $auth = 'manual') {
3715 require_once($CFG->dirroot.'/user/profile/lib.php');
3716 require_once($CFG->dirroot.'/user/lib.php');
3718 // Just in case check text case.
3719 $username = trim(core_text::strtolower($username));
3721 $authplugin = get_auth_plugin($auth);
3722 $customfields = $authplugin->get_custom_user_profile_fields();
3723 $newuser = new stdClass();
3724 if ($newinfo = $authplugin->get_userinfo($username)) {
3725 $newinfo = truncate_userinfo($newinfo);
3726 foreach ($newinfo as $key => $value) {
3727 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3728 $newuser->$key = $value;
3733 if (!empty($newuser->email)) {
3734 if (email_is_not_allowed($newuser->email)) {
3735 unset($newuser->email);
3739 if (!isset($newuser->city)) {
3740 $newuser->city = '';
3743 $newuser->auth = $auth;
3744 $newuser->username = $username;
3747 // user CFG lang for user if $newuser->lang is empty
3748 // or $user->lang is not an installed language.
3749 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3750 $newuser->lang = $CFG->lang;
3752 $newuser->confirmed = 1;
3753 $newuser->lastip = getremoteaddr();
3754 $newuser->timecreated = time();
3755 $newuser->timemodified = $newuser->timecreated;
3756 $newuser->mnethostid = $CFG->mnet_localhost_id;
3758 $newuser->id = user_create_user($newuser, false, false);
3760 // Save user profile data.
3761 profile_save_data($newuser);
3763 $user = get_complete_user_data('id', $newuser->id);
3764 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3765 set_user_preference('auth_forcepasswordchange', 1, $user);
3767 // Set the password.
3768 update_internal_user_password($user, $password);
3771 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3777 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3779 * @param string $username user's username to update the record
3780 * @return stdClass A complete user object
3782 function update_user_record($username) {
3784 // Just in case check text case.
3785 $username = trim(core_text::strtolower($username));
3787 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3788 return update_user_record_by_id($oldinfo->id);
3792 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3794 * @param int $id user id
3795 * @return stdClass A complete user object
3797 function update_user_record_by_id($id) {
3799 require_once($CFG->dirroot."/user/profile/lib.php");
3800 require_once($CFG->dirroot.'/user/lib.php');
3802 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3803 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3806 $userauth = get_auth_plugin($oldinfo->auth);
3808 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3809 $newinfo = truncate_userinfo($newinfo);
3810 $customfields = $userauth->get_custom_user_profile_fields();
3812 foreach ($newinfo as $key => $value) {
3813 $iscustom = in_array($key, $customfields);
3815 $key = strtolower($key);
3817 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3818 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3819 // Unknown or must not be changed.
3822 $confval = $userauth->config->{'field_updatelocal_' . $key};
3823 $lockval = $userauth->config->{'field_lock_' . $key};
3824 if (empty($confval) || empty($lockval)) {
3827 if ($confval === 'onlogin') {
3828 // MDL-4207 Don't overwrite modified user profile values with
3829 // empty LDAP values when 'unlocked if empty' is set. The purpose
3830 // of the setting 'unlocked if empty' is to allow the user to fill
3831 // in a value for the selected field _if LDAP is giving
3832 // nothing_ for this field. Thus it makes sense to let this value
3833 // stand in until LDAP is giving a value for this field.
3834 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3835 if ($iscustom || (in_array($key, $userauth->userfields) &&
3836 ((string)$oldinfo->$key !== (string)$value))) {
3837 $newuser[$key] = (string)$value;
3843 $newuser['id'] = $oldinfo->id;
3844 $newuser['timemodified'] = time();
3845 user_update_user((object) $newuser, false, false);
3847 // Save user profile data.
3848 profile_save_data((object) $newuser);
3851 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
3855 return get_complete_user_data('id', $oldinfo->id);
3859 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
3861 * @param array $info Array of user properties to truncate if needed
3862 * @return array The now truncated information that was passed in
3864 function truncate_userinfo(array $info) {
3865 // Define the limits.
3875 'institution' => 255,
3876 'department' => 255,
3883 // Apply where needed.
3884 foreach (array_keys($info) as $key) {
3885 if (!empty($limit[$key])) {
3886 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
3894 * Marks user deleted in internal user database and notifies the auth plugin.
3895 * Also unenrols user from all roles and does other cleanup.
3897 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3899 * @param stdClass $user full user object before delete
3900 * @return boolean success
3901 * @throws coding_exception if invalid $user parameter detected
3903 function delete_user(stdClass $user) {
3905 require_once($CFG->libdir.'/grouplib.php');
3906 require_once($CFG->libdir.'/gradelib.php');
3907 require_once($CFG->dirroot.'/message/lib.php');
3908 require_once($CFG->dirroot.'/user/lib.php');
3910 // Make sure nobody sends bogus record type as parameter.
3911 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
3912 throw new coding_exception('Invalid $user parameter in delete_user() detected');
3915 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
3916 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
3917 debugging('Attempt to delete unknown user account.');
3921 // There must be always exactly one guest record, originally the guest account was identified by username only,
3922 // now we use $CFG->siteguest for performance reasons.
3923 if ($user->username === 'guest' or isguestuser($user)) {
3924 debugging('Guest user account can not be deleted.');
3928 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
3929 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
3930 if ($user->auth === 'manual' and is_siteadmin($user)) {
3931 debugging('Local administrator accounts can not be deleted.');
3935 // Allow plugins to use this user object before we completely delete it.
3936 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
3937 foreach ($pluginsfunction as $plugintype => $plugins) {
3938 foreach ($plugins as $pluginfunction) {
3939 $pluginfunction($user);
3944 // Keep user record before updating it, as we have to pass this to user_deleted event.
3945 $olduser = clone $user;
3947 // Keep a copy of user context, we need it for event.
3948 $usercontext = context_user::instance($user->id);
3950 // Delete all grades - backup is kept in grade_grades_history table.
3951 grade_user_delete($user->id);
3953 // Move unread messages from this user to read.
3954 message_move_userfrom_unread2read($user->id);
3956 // TODO: remove from cohorts using standard API here.
3958 // Remove user tags.
3959 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
3961 // Unconditionally unenrol from all courses.
3962 enrol_user_delete($user);
3964 // Unenrol from all roles in all contexts.
3965 // This might be slow but it is really needed - modules might do some extra cleanup!
3966 role_unassign_all(array('userid' => $user->id));
3968 // Now do a brute force cleanup.
3970 // Remove from all cohorts.
3971 $DB->delete_records('cohort_members', array('userid' => $user->id));
3973 // Remove from all groups.
3974 $DB->delete_records('groups_members', array('userid' => $user->id));
3976 // Brute force unenrol from all courses.
3977 $DB->delete_records('user_enrolments', array('userid' => $user->id));
3979 // Purge user preferences.
3980 $DB->delete_records('user_preferences', array('userid' => $user->id));
3982 // Purge user extra profile info.
3983 $DB->delete_records('user_info_data', array('userid' => $user->id));
3985 // Purge log of previous password hashes.
3986 $DB->delete_records('user_password_history', array('userid' => $user->id));
3988 // Last course access not necessary either.
3989 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
3990 // Remove all user tokens.
3991 $DB->delete_records('external_tokens', array('userid' => $user->id));
3993 // Unauthorise the user for all services.
3994 $DB->delete_records('external_services_users', array('userid' => $user->id));
3996 // Remove users private keys.
3997 $DB->delete_records('user_private_key', array('userid' => $user->id));
3999 // Remove users customised pages.
4000 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4002 // Force logout - may fail if file based sessions used, sorry.
4003 \core\session\manager::kill_user_sessions($user->id);
4005 // Generate username from email address, or a fake email.
4006 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4007 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4009 // Workaround for bulk deletes of users with the same email address.
4010 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4014 // Mark internal user record as "deleted".
4015 $updateuser = new stdClass();
4016 $updateuser->id = $user->id;
4017 $updateuser->deleted = 1;
4018 $updateuser->username = $delname; // Remember it just in case.
4019 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4020 $updateuser->idnumber = ''; // Clear this field to free it up.
4021 $updateuser->picture = 0;
4022 $updateuser->timemodified = time();
4024 // Don't trigger update event, as user is being deleted.
4025 user_update_user($updateuser, false, false);
4027 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4028 context_helper::delete_instance(CONTEXT_USER, $user->id);
4030 // Any plugin that needs to cleanup should register this event.
4032 $event = \core\event\user_deleted::create(
4034 'objectid' => $user->id,
4035 'relateduserid' => $user->id,
4036 'context' => $usercontext,
4038 'username' => $user->username,
4039 'email' => $user->email,
4040 'idnumber' => $user->idnumber,
4041 'picture' => $user->picture,
4042 'mnethostid' => $user->mnethostid
4046 $event->add_record_snapshot('user', $olduser);
4049 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4050 // should know about this updated property persisted to the user's table.
4051 $user->timemodified = $updateuser->timemodified;
4053 // Notify auth plugin - do not block the delete even when plugin fails.
4054 $authplugin = get_auth_plugin($user->auth);
4055 $authplugin->user_delete($user);
4061 * Retrieve the guest user object.
4063 * @return stdClass A {@link $USER} object
4065 function guest_user() {
4068 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4069 $newuser->confirmed = 1;
4070 $newuser->lang = $CFG->lang;
4071 $newuser->lastip = getremoteaddr();
4078 * Authenticates a user against the chosen authentication mechanism
4080 * Given a username and password, this function looks them
4081 * up using the currently selected authentication mechanism,
4082 * and if the authentication is successful, it returns a
4083 * valid $user object from the 'user' table.
4085 * Uses auth_ functions from the currently active auth module
4087 * After authenticate_user_login() returns success, you will need to
4088 * log that the user has logged in, and call complete_user_login() to set
4091 * Note: this function works only with non-mnet accounts!
4093 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4094 * @param string $password User's password
4095 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4096 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4097 * @return stdClass|false A {@link $USER} object or false if error
4099 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4101 require_once("$CFG->libdir/authlib.php");
4103 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4104 // we have found the user
4106 } else if (!empty($CFG->authloginviaemail)) {
4107 if ($email = clean_param($username, PARAM_EMAIL)) {
4108 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4109 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4110 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4111 if (count($users) === 1) {
4112 // Use email for login only if unique.
4113 $user = reset($users);
4114 $user = get_complete_user_data('id', $user->id);
4115 $username = $user->username;
4121 $authsenabled = get_enabled_auth_plugins();
4124 // Use manual if auth not set.
4125 $auth = empty($user->auth) ? 'manual' : $user->auth;
4127 if (in_array($user->auth, $authsenabled)) {
4128 $authplugin = get_auth_plugin($user->auth);
4129 $authplugin->pre_user_login_hook($user);
4132 if (!empty($user->suspended)) {
4133 $failurereason = AUTH_LOGIN_SUSPENDED;
4135 // Trigger login failed event.
4136 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4137 'other' => array('username' => $username, 'reason' => $failurereason)));
4139 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4142 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4143 // Legacy way to suspend user.
4144 $failurereason = AUTH_LOGIN_SUSPENDED;
4146 // Trigger login failed event.
4147 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4148 'other' => array('username' => $username, 'reason' => $failurereason)));
4150 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4153 $auths = array($auth);
4156 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4157 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4158 $failurereason = AUTH_LOGIN_NOUSER;
4160 // Trigger login failed event.
4161 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4162 'reason' => $failurereason)));
4164 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4168 // User does not exist.
4169 $auths = $authsenabled;
4170 $user = new stdClass();
4174 if ($ignorelockout) {
4175 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4176 // or this function is called from a SSO script.
4177 } else if ($user->id) {
4178 // Verify login lockout after other ways that may prevent user login.
4179 if (login_is_lockedout($user)) {
4180 $failurereason = AUTH_LOGIN_LOCKOUT;
4182 // Trigger login failed event.
4183 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4184 'other' => array('username' => $username, 'reason' => $failurereason)));
4187 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4191 // We can not lockout non-existing accounts.
4194 foreach ($auths as $auth) {
4195 $authplugin = get_auth_plugin($auth);
4197 // On auth fail fall through to the next plugin.
4198 if (!$authplugin->user_login($username, $password)) {
4202 // Successful authentication.
4204 // User already exists in database.
4205 if (empty($user->auth)) {
4206 // For some reason auth isn't set yet.
4207 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4208 $user->auth = $auth;
4211 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4212 // the current hash algorithm while we have access to the user's password.
4213 update_internal_user_password($user, $password);
4215 if ($authplugin->is_synchronised_with_external()) {
4216 // Update user record from external DB.
4217 $user = update_user_record_by_id($user->id);
4220 // The user is authenticated but user creation may be disabled.
4221 if (!empty($CFG->authpreventaccountcreation)) {
4222 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4224 // Trigger login failed event.
4225 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4226 'reason' => $failurereason)));
4229 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4230 $_SERVER['HTTP_USER_AGENT']);
4233 $user = create_user_record($username, $password, $auth);
4237 $authplugin->sync_roles($user);
4239 foreach ($authsenabled as $hau) {
4240 $hauth = get_auth_plugin($hau);
4241 $hauth->user_authenticated_hook($user, $username, $password);
4244 if (empty($user->id)) {
4245 $failurereason = AUTH_LOGIN_NOUSER;
4246 // Trigger login failed event.
4247 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4248 'reason' => $failurereason)));
4253 if (!empty($user->suspended)) {
4254 // Just in case some auth plugin suspended account.
4255 $failurereason = AUTH_LOGIN_SUSPENDED;
4256 // Trigger login failed event.
4257 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4258 'other' => array('username' => $username, 'reason' => $failurereason)));
4260 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4264 login_attempt_valid($user);
4265 $failurereason = AUTH_LOGIN_OK;
4269 // Failed if all the plugins have failed.
4270 if (debugging('', DEBUG_ALL)) {
4271 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4275 login_attempt_failed($user);
4276 $failurereason = AUTH_LOGIN_FAILED;
4277 // Trigger login failed event.
4278 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4279 'other' => array('username' => $username, 'reason' => $failurereason)));
4282 $failurereason = AUTH_LOGIN_NOUSER;
4283 // Trigger login failed event.
4284 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4285 'reason' => $failurereason)));
4293 * Call to complete the user login process after authenticate_user_login()
4294 * has succeeded. It will setup the $USER variable and other required bits
4298 * - It will NOT log anything -- up to the caller to decide what to log.
4299 * - this function does not set any cookies any more!
4301 * @param stdClass $user
4302 * @return stdClass A {@link $USER} object - BC only, do not use