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 (English ascii letters [a-zA-Z]) 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 0-9 and English ascii letters [a-zA-Z] only.
88 define('PARAM_ALPHANUM', 'alphanum');
91 * PARAM_ALPHANUMEXT - expected numbers 0-9, letters (English ascii letters [a-zA-Z]) and _- only.
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 receiving
119 * the input (required/optional_param or formslib) and then sanitise 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 * Use PARAM_LOCALISEDFLOAT instead.
142 define('PARAM_FLOAT', 'float');
145 * PARAM_LOCALISEDFLOAT - a localised real/floating point number.
146 * This is preferred over PARAM_FLOAT for numbers typed in by the user.
147 * Cleans localised numbers to computer readable numbers; false for invalid numbers.
149 define('PARAM_LOCALISEDFLOAT', 'localisedfloat');
152 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
154 define('PARAM_HOST', 'host');
157 * PARAM_INT - integers only, use when expecting only numbers.
159 define('PARAM_INT', 'int');
162 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
164 define('PARAM_LANG', 'lang');
167 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
168 * others! Implies PARAM_URL!)
170 define('PARAM_LOCALURL', 'localurl');
173 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
175 define('PARAM_NOTAGS', 'notags');
178 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
179 * traversals note: the leading slash is not removed, window drive letter is not allowed
181 define('PARAM_PATH', 'path');
184 * PARAM_PEM - Privacy Enhanced Mail format
186 define('PARAM_PEM', 'pem');
189 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
191 define('PARAM_PERMISSION', 'permission');
194 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
196 define('PARAM_RAW', 'raw');
199 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
201 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
204 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
206 define('PARAM_SAFEDIR', 'safedir');
209 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
211 define('PARAM_SAFEPATH', 'safepath');
214 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
216 define('PARAM_SEQUENCE', 'sequence');
219 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
221 define('PARAM_TAG', 'tag');
224 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
226 define('PARAM_TAGLIST', 'taglist');
229 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
231 define('PARAM_TEXT', 'text');
234 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
236 define('PARAM_THEME', 'theme');
239 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
240 * http://localhost.localdomain/ is ok.
242 define('PARAM_URL', 'url');
245 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
246 * accounts, do NOT use when syncing with external systems!!
248 define('PARAM_USERNAME', 'username');
251 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
253 define('PARAM_STRINGID', 'stringid');
255 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
257 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
258 * It was one of the first types, that is why it is abused so much ;-)
259 * @deprecated since 2.0
261 define('PARAM_CLEAN', 'clean');
264 * PARAM_INTEGER - deprecated alias for PARAM_INT
265 * @deprecated since 2.0
267 define('PARAM_INTEGER', 'int');
270 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
271 * @deprecated since 2.0
273 define('PARAM_NUMBER', 'float');
276 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
277 * NOTE: originally alias for PARAM_APLHA
278 * @deprecated since 2.0
280 define('PARAM_ACTION', 'alphanumext');
283 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
284 * NOTE: originally alias for PARAM_APLHA
285 * @deprecated since 2.0
287 define('PARAM_FORMAT', 'alphanumext');
290 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
291 * @deprecated since 2.0
293 define('PARAM_MULTILANG', 'text');
296 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
297 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
298 * America/Port-au-Prince)
300 define('PARAM_TIMEZONE', 'timezone');
303 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
305 define('PARAM_CLEANFILE', 'file');
308 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
309 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
310 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
311 * NOTE: numbers and underscores are strongly discouraged in plugin names!
313 define('PARAM_COMPONENT', 'component');
316 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
317 * It is usually used together with context id and component.
318 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
320 define('PARAM_AREA', 'area');
323 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
324 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
325 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
327 define('PARAM_PLUGIN', 'plugin');
333 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
335 define('VALUE_REQUIRED', 1);
338 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
340 define('VALUE_OPTIONAL', 2);
343 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
345 define('VALUE_DEFAULT', 0);
348 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
350 define('NULL_NOT_ALLOWED', false);
353 * NULL_ALLOWED - the parameter can be set to null in the database
355 define('NULL_ALLOWED', true);
360 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
362 define('PAGE_COURSE_VIEW', 'course-view');
364 /** Get remote addr constant */
365 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
366 /** Get remote addr constant */
367 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
369 * GETREMOTEADDR_SKIP_DEFAULT defines the default behavior remote IP address validation.
371 define('GETREMOTEADDR_SKIP_DEFAULT', GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR|GETREMOTEADDR_SKIP_HTTP_CLIENT_IP);
373 // Blog access level constant declaration.
374 define ('BLOG_USER_LEVEL', 1);
375 define ('BLOG_GROUP_LEVEL', 2);
376 define ('BLOG_COURSE_LEVEL', 3);
377 define ('BLOG_SITE_LEVEL', 4);
378 define ('BLOG_GLOBAL_LEVEL', 5);
383 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
384 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
385 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
387 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
389 define('TAG_MAX_LENGTH', 50);
391 // Password policy constants.
392 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
393 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
394 define ('PASSWORD_DIGITS', '0123456789');
395 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
397 // Feature constants.
398 // Used for plugin_supports() to report features that are, or are not, supported by a module.
400 /** True if module can provide a grade */
401 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
402 /** True if module supports outcomes */
403 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
404 /** True if module supports advanced grading methods */
405 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
406 /** True if module controls the grade visibility over the gradebook */
407 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
408 /** True if module supports plagiarism plugins */
409 define('FEATURE_PLAGIARISM', 'plagiarism');
411 /** True if module has code to track whether somebody viewed it */
412 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
413 /** True if module has custom completion rules */
414 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
416 /** True if module has no 'view' page (like label) */
417 define('FEATURE_NO_VIEW_LINK', 'viewlink');
418 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
419 define('FEATURE_IDNUMBER', 'idnumber');
420 /** True if module supports groups */
421 define('FEATURE_GROUPS', 'groups');
422 /** True if module supports groupings */
423 define('FEATURE_GROUPINGS', 'groupings');
425 * True if module supports groupmembersonly (which no longer exists)
426 * @deprecated Since Moodle 2.8
428 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
430 /** Type of module */
431 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
432 /** True if module supports intro editor */
433 define('FEATURE_MOD_INTRO', 'mod_intro');
434 /** True if module has default completion */
435 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
437 define('FEATURE_COMMENT', 'comment');
439 define('FEATURE_RATE', 'rate');
440 /** True if module supports backup/restore of moodle2 format */
441 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
443 /** True if module can show description on course main page */
444 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
446 /** True if module uses the question bank */
447 define('FEATURE_USES_QUESTIONS', 'usesquestions');
450 * Maximum filename char size
452 define('MAX_FILENAME_SIZE', 100);
454 /** Unspecified module archetype */
455 define('MOD_ARCHETYPE_OTHER', 0);
456 /** Resource-like type module */
457 define('MOD_ARCHETYPE_RESOURCE', 1);
458 /** Assignment module archetype */
459 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
460 /** System (not user-addable) module archetype */
461 define('MOD_ARCHETYPE_SYSTEM', 3);
464 * Security token used for allowing access
465 * from external application such as web services.
466 * Scripts do not use any session, performance is relatively
467 * low because we need to load access info in each request.
468 * Scripts are executed in parallel.
470 define('EXTERNAL_TOKEN_PERMANENT', 0);
473 * Security token used for allowing access
474 * of embedded applications, the code is executed in the
475 * active user session. Token is invalidated after user logs out.
476 * Scripts are executed serially - normal session locking is used.
478 define('EXTERNAL_TOKEN_EMBEDDED', 1);
481 * The home page should be the site home
483 define('HOMEPAGE_SITE', 0);
485 * The home page should be the users my page
487 define('HOMEPAGE_MY', 1);
489 * The home page can be chosen by the user
491 define('HOMEPAGE_USER', 2);
494 * URL of the Moodle sites registration portal.
496 defined('HUB_MOODLEORGHUBURL') || define('HUB_MOODLEORGHUBURL', 'https://stats.moodle.org');
499 * Moodle mobile app service name
501 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
504 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
506 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
509 * Course display settings: display all sections on one page.
511 define('COURSE_DISPLAY_SINGLEPAGE', 0);
513 * Course display settings: split pages into a page per section.
515 define('COURSE_DISPLAY_MULTIPAGE', 1);
518 * Authentication constant: String used in password field when password is not stored.
520 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
523 * Email from header to never include via information.
525 define('EMAIL_VIA_NEVER', 0);
528 * Email from header to always include via information.
530 define('EMAIL_VIA_ALWAYS', 1);
533 * Email from header to only include via information if the address is no-reply.
535 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
537 // PARAMETER HANDLING.
540 * Returns a particular value for the named variable, taken from
541 * POST or GET. If the parameter doesn't exist then an error is
542 * thrown because we require this variable.
544 * This function should be used to initialise all required values
545 * in a script that are based on parameters. Usually it will be
547 * $id = required_param('id', PARAM_INT);
549 * Please note the $type parameter is now required and the value can not be array.
551 * @param string $parname the name of the page parameter we want
552 * @param string $type expected type of parameter
554 * @throws coding_exception
556 function required_param($parname, $type) {
557 if (func_num_args() != 2 or empty($parname) or empty($type)) {
558 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
560 // POST has precedence.
561 if (isset($_POST[$parname])) {
562 $param = $_POST[$parname];
563 } else if (isset($_GET[$parname])) {
564 $param = $_GET[$parname];
566 print_error('missingparam', '', '', $parname);
569 if (is_array($param)) {
570 debugging('Invalid array parameter detected in required_param(): '.$parname);
571 // TODO: switch to fatal error in Moodle 2.3.
572 return required_param_array($parname, $type);
575 return clean_param($param, $type);
579 * Returns a particular array value for the named variable, taken from
580 * POST or GET. If the parameter doesn't exist then an error is
581 * thrown because we require this variable.
583 * This function should be used to initialise all required values
584 * in a script that are based on parameters. Usually it will be
586 * $ids = required_param_array('ids', PARAM_INT);
588 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
590 * @param string $parname the name of the page parameter we want
591 * @param string $type expected type of parameter
593 * @throws coding_exception
595 function required_param_array($parname, $type) {
596 if (func_num_args() != 2 or empty($parname) or empty($type)) {
597 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
599 // POST has precedence.
600 if (isset($_POST[$parname])) {
601 $param = $_POST[$parname];
602 } else if (isset($_GET[$parname])) {
603 $param = $_GET[$parname];
605 print_error('missingparam', '', '', $parname);
607 if (!is_array($param)) {
608 print_error('missingparam', '', '', $parname);
612 foreach ($param as $key => $value) {
613 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
614 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
617 $result[$key] = clean_param($value, $type);
624 * Returns a particular value for the named variable, taken from
625 * POST or GET, otherwise returning a given default.
627 * This function should be used to initialise all optional values
628 * in a script that are based on parameters. Usually it will be
630 * $name = optional_param('name', 'Fred', PARAM_TEXT);
632 * Please note the $type parameter is now required and the value can not be array.
634 * @param string $parname the name of the page parameter we want
635 * @param mixed $default the default value to return if nothing is found
636 * @param string $type expected type of parameter
638 * @throws coding_exception
640 function optional_param($parname, $default, $type) {
641 if (func_num_args() != 3 or empty($parname) or empty($type)) {
642 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
645 // POST has precedence.
646 if (isset($_POST[$parname])) {
647 $param = $_POST[$parname];
648 } else if (isset($_GET[$parname])) {
649 $param = $_GET[$parname];
654 if (is_array($param)) {
655 debugging('Invalid array parameter detected in required_param(): '.$parname);
656 // TODO: switch to $default in Moodle 2.3.
657 return optional_param_array($parname, $default, $type);
660 return clean_param($param, $type);
664 * Returns a particular array value for the named variable, taken from
665 * POST or GET, otherwise returning a given default.
667 * This function should be used to initialise all optional values
668 * in a script that are based on parameters. Usually it will be
670 * $ids = optional_param('id', array(), PARAM_INT);
672 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
674 * @param string $parname the name of the page parameter we want
675 * @param mixed $default the default value to return if nothing is found
676 * @param string $type expected type of parameter
678 * @throws coding_exception
680 function optional_param_array($parname, $default, $type) {
681 if (func_num_args() != 3 or empty($parname) or empty($type)) {
682 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
685 // POST has precedence.
686 if (isset($_POST[$parname])) {
687 $param = $_POST[$parname];
688 } else if (isset($_GET[$parname])) {
689 $param = $_GET[$parname];
693 if (!is_array($param)) {
694 debugging('optional_param_array() expects array parameters only: '.$parname);
699 foreach ($param as $key => $value) {
700 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
701 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
704 $result[$key] = clean_param($value, $type);
711 * Strict validation of parameter values, the values are only converted
712 * to requested PHP type. Internally it is using clean_param, the values
713 * before and after cleaning must be equal - otherwise
714 * an invalid_parameter_exception is thrown.
715 * Objects and classes are not accepted.
717 * @param mixed $param
718 * @param string $type PARAM_ constant
719 * @param bool $allownull are nulls valid value?
720 * @param string $debuginfo optional debug information
721 * @return mixed the $param value converted to PHP type
722 * @throws invalid_parameter_exception if $param is not of given type
724 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
725 if (is_null($param)) {
726 if ($allownull == NULL_ALLOWED) {
729 throw new invalid_parameter_exception($debuginfo);
732 if (is_array($param) or is_object($param)) {
733 throw new invalid_parameter_exception($debuginfo);
736 $cleaned = clean_param($param, $type);
738 if ($type == PARAM_FLOAT) {
739 // Do not detect precision loss here.
740 if (is_float($param) or is_int($param)) {
742 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
743 throw new invalid_parameter_exception($debuginfo);
745 } else if ((string)$param !== (string)$cleaned) {
746 // Conversion to string is usually lossless.
747 throw new invalid_parameter_exception($debuginfo);
754 * Makes sure array contains only the allowed types, this function does not validate array key names!
757 * $options = clean_param($options, PARAM_INT);
760 * @param array $param the variable array we are cleaning
761 * @param string $type expected format of param after cleaning.
762 * @param bool $recursive clean recursive arrays
764 * @throws coding_exception
766 function clean_param_array(array $param = null, $type, $recursive = false) {
767 // Convert null to empty array.
768 $param = (array)$param;
769 foreach ($param as $key => $value) {
770 if (is_array($value)) {
772 $param[$key] = clean_param_array($value, $type, true);
774 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
777 $param[$key] = clean_param($value, $type);
784 * Used by {@link optional_param()} and {@link required_param()} to
785 * clean the variables and/or cast to specific types, based on
788 * $course->format = clean_param($course->format, PARAM_ALPHA);
789 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
792 * @param mixed $param the variable we are cleaning
793 * @param string $type expected format of param after cleaning.
795 * @throws coding_exception
797 function clean_param($param, $type) {
800 if (is_array($param)) {
801 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
802 } else if (is_object($param)) {
803 if (method_exists($param, '__toString')) {
804 $param = $param->__toString();
806 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
812 // No cleaning at all.
813 $param = fix_utf8($param);
816 case PARAM_RAW_TRIMMED:
817 // No cleaning, but strip leading and trailing whitespace.
818 $param = fix_utf8($param);
822 // General HTML cleaning, try to use more specific type if possible this is deprecated!
823 // Please use more specific type instead.
824 if (is_numeric($param)) {
827 $param = fix_utf8($param);
828 // Sweep for scripts, etc.
829 return clean_text($param);
831 case PARAM_CLEANHTML:
832 // Clean html fragment.
833 $param = fix_utf8($param);
834 // Sweep for scripts, etc.
835 $param = clean_text($param, FORMAT_HTML);
839 // Convert to integer.
844 return (float)$param;
846 case PARAM_LOCALISEDFLOAT:
848 return unformat_float($param, true);
851 // Remove everything not `a-z`.
852 return preg_replace('/[^a-zA-Z]/i', '', $param);
855 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
856 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
859 // Remove everything not `a-zA-Z0-9`.
860 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
862 case PARAM_ALPHANUMEXT:
863 // Remove everything not `a-zA-Z0-9_-`.
864 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
867 // Remove everything not `0-9,`.
868 return preg_replace('/[^0-9,]/i', '', $param);
871 // Convert to 1 or 0.
872 $tempstr = strtolower($param);
873 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
875 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
878 $param = empty($param) ? 0 : 1;
884 $param = fix_utf8($param);
885 return strip_tags($param);
888 // Leave only tags needed for multilang.
889 $param = fix_utf8($param);
890 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
891 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
893 if (strpos($param, '</lang>') !== false) {
894 // Old and future mutilang syntax.
895 $param = strip_tags($param, '<lang>');
896 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
900 foreach ($matches[0] as $match) {
901 if ($match === '</lang>') {
909 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
920 } else if (strpos($param, '</span>') !== false) {
921 // Current problematic multilang syntax.
922 $param = strip_tags($param, '<span>');
923 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
927 foreach ($matches[0] as $match) {
928 if ($match === '</span>') {
936 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
948 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
949 return strip_tags($param);
951 case PARAM_COMPONENT:
952 // We do not want any guessing here, either the name is correct or not
953 // please note only normalised component names are accepted.
954 if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
957 if (strpos($param, '__') !== false) {
960 if (strpos($param, 'mod_') === 0) {
961 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
962 if (substr_count($param, '_') != 1) {
970 // We do not want any guessing here, either the name is correct or not.
971 if (!is_valid_plugin_name($param)) {
977 // Remove everything not a-zA-Z0-9_- .
978 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
981 // Remove everything not a-zA-Z0-9/_- .
982 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
985 // Strip all suspicious characters from filename.
986 $param = fix_utf8($param);
987 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
988 if ($param === '.' || $param === '..') {
994 // Strip all suspicious characters from file path.
995 $param = fix_utf8($param);
996 $param = str_replace('\\', '/', $param);
998 // Explode the path and clean each element using the PARAM_FILE rules.
999 $breadcrumb = explode('/', $param);
1000 foreach ($breadcrumb as $key => $crumb) {
1001 if ($crumb === '.' && $key === 0) {
1002 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1004 $crumb = clean_param($crumb, PARAM_FILE);
1006 $breadcrumb[$key] = $crumb;
1008 $param = implode('/', $breadcrumb);
1010 // Remove multiple current path (./././) and multiple slashes (///).
1011 $param = preg_replace('~//+~', '/', $param);
1012 $param = preg_replace('~/(\./)+~', '/', $param);
1016 // Allow FQDN or IPv4 dotted quad.
1017 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1018 // Match ipv4 dotted quad.
1019 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1020 // Confirm values are ok.
1021 if ( $match[0] > 255
1024 || $match[4] > 255 ) {
1025 // Hmmm, what kind of dotted quad is this?
1028 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1029 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1030 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1032 // All is ok - $param is respected.
1041 $param = fix_utf8($param);
1042 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1043 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1044 // All is ok, param is respected.
1051 case PARAM_LOCALURL:
1052 // Allow http absolute, root relative and relative URLs within wwwroot.
1053 $param = clean_param($param, PARAM_URL);
1054 if (!empty($param)) {
1056 if ($param === $CFG->wwwroot) {
1058 } else if (preg_match(':^/:', $param)) {
1059 // Root-relative, ok!
1060 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1061 // Absolute, and matches our wwwroot.
1063 // Relative - let's make sure there are no tricks.
1064 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1074 $param = trim($param);
1075 // PEM formatted strings may contain letters/numbers and the symbols:
1079 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1080 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1081 list($wholething, $body) = $matches;
1082 unset($wholething, $matches);
1083 $b64 = clean_param($body, PARAM_BASE64);
1085 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1093 if (!empty($param)) {
1094 // PEM formatted strings may contain letters/numbers and the symbols
1098 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1101 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1102 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1103 // than (or equal to) 64 characters long.
1104 for ($i=0, $j=count($lines); $i < $j; $i++) {
1106 if (64 < strlen($lines[$i])) {
1112 if (64 != strlen($lines[$i])) {
1116 return implode("\n", $lines);
1122 $param = fix_utf8($param);
1123 // Please note it is not safe to use the tag name directly anywhere,
1124 // it must be processed with s(), urlencode() before embedding anywhere.
1125 // Remove some nasties.
1126 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1127 // Convert many whitespace chars into one.
1128 $param = preg_replace('/\s+/u', ' ', $param);
1129 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1133 $param = fix_utf8($param);
1134 $tags = explode(',', $param);
1136 foreach ($tags as $tag) {
1137 $res = clean_param($tag, PARAM_TAG);
1143 return implode(',', $result);
1148 case PARAM_CAPABILITY:
1149 if (get_capability_info($param)) {
1155 case PARAM_PERMISSION:
1156 $param = (int)$param;
1157 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1164 $param = clean_param($param, PARAM_PLUGIN);
1165 if (empty($param)) {
1167 } else if (exists_auth_plugin($param)) {
1174 $param = clean_param($param, PARAM_SAFEDIR);
1175 if (get_string_manager()->translation_exists($param)) {
1178 // Specified language is not installed or param malformed.
1183 $param = clean_param($param, PARAM_PLUGIN);
1184 if (empty($param)) {
1186 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1188 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1191 // Specified theme is not installed.
1195 case PARAM_USERNAME:
1196 $param = fix_utf8($param);
1197 $param = trim($param);
1198 // Convert uppercase to lowercase MDL-16919.
1199 $param = core_text::strtolower($param);
1200 if (empty($CFG->extendedusernamechars)) {
1201 $param = str_replace(" " , "", $param);
1202 // Regular expression, eliminate all chars EXCEPT:
1203 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1204 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1209 $param = fix_utf8($param);
1210 if (validate_email($param)) {
1216 case PARAM_STRINGID:
1217 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1223 case PARAM_TIMEZONE:
1224 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1225 $param = fix_utf8($param);
1226 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1227 if (preg_match($timezonepattern, $param)) {
1234 // Doh! throw error, switched parameters in optional_param or another serious problem.
1235 print_error("unknownparamtype", '', '', $type);
1240 * Whether the PARAM_* type is compatible in RTL.
1242 * Being compatible with RTL means that the data they contain can flow
1243 * from right-to-left or left-to-right without compromising the user experience.
1245 * Take URLs for example, they are not RTL compatible as they should always
1246 * flow from the left to the right. This also applies to numbers, email addresses,
1247 * configuration snippets, base64 strings, etc...
1249 * This function tries to best guess which parameters can contain localised strings.
1251 * @param string $paramtype Constant PARAM_*.
1254 function is_rtl_compatible($paramtype) {
1255 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1259 * Makes sure the data is using valid utf8, invalid characters are discarded.
1261 * Note: this function is not intended for full objects with methods and private properties.
1263 * @param mixed $value
1264 * @return mixed with proper utf-8 encoding
1266 function fix_utf8($value) {
1267 if (is_null($value) or $value === '') {
1270 } else if (is_string($value)) {
1271 if ((string)(int)$value === $value) {
1275 // No null bytes expected in our data, so let's remove it.
1276 $value = str_replace("\0", '', $value);
1278 // Note: this duplicates min_fix_utf8() intentionally.
1279 static $buggyiconv = null;
1280 if ($buggyiconv === null) {
1281 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1285 if (function_exists('mb_convert_encoding')) {
1286 $subst = mb_substitute_character();
1287 mb_substitute_character('');
1288 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1289 mb_substitute_character($subst);
1292 // Warn admins on admin/index.php page.
1297 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1302 } else if (is_array($value)) {
1303 foreach ($value as $k => $v) {
1304 $value[$k] = fix_utf8($v);
1308 } else if (is_object($value)) {
1309 // Do not modify original.
1310 $value = clone($value);
1311 foreach ($value as $k => $v) {
1312 $value->$k = fix_utf8($v);
1317 // This is some other type, no utf-8 here.
1323 * Return true if given value is integer or string with integer value
1325 * @param mixed $value String or Int
1326 * @return bool true if number, false if not
1328 function is_number($value) {
1329 if (is_int($value)) {
1331 } else if (is_string($value)) {
1332 return ((string)(int)$value) === $value;
1339 * Returns host part from url.
1341 * @param string $url full url
1342 * @return string host, null if not found
1344 function get_host_from_url($url) {
1345 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1353 * Tests whether anything was returned by text editor
1355 * This function is useful for testing whether something you got back from
1356 * the HTML editor actually contains anything. Sometimes the HTML editor
1357 * appear to be empty, but actually you get back a <br> tag or something.
1359 * @param string $string a string containing HTML.
1360 * @return boolean does the string contain any actual content - that is text,
1361 * images, objects, etc.
1363 function html_is_blank($string) {
1364 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1368 * Set a key in global configuration
1370 * Set a key/value pair in both this session's {@link $CFG} global variable
1371 * and in the 'config' database table for future sessions.
1373 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1374 * In that case it doesn't affect $CFG.
1376 * A NULL value will delete the entry.
1378 * NOTE: this function is called from lib/db/upgrade.php
1380 * @param string $name the key to set
1381 * @param string $value the value to set (without magic quotes)
1382 * @param string $plugin (optional) the plugin scope, default null
1383 * @return bool true or exception
1385 function set_config($name, $value, $plugin=null) {
1388 if (empty($plugin)) {
1389 if (!array_key_exists($name, $CFG->config_php_settings)) {
1390 // So it's defined for this invocation at least.
1391 if (is_null($value)) {
1394 // Settings from db are always strings.
1395 $CFG->$name = (string)$value;
1399 if ($DB->get_field('config', 'name', array('name' => $name))) {
1400 if ($value === null) {
1401 $DB->delete_records('config', array('name' => $name));
1403 $DB->set_field('config', 'value', $value, array('name' => $name));
1406 if ($value !== null) {
1407 $config = new stdClass();
1408 $config->name = $name;
1409 $config->value = $value;
1410 $DB->insert_record('config', $config, false);
1412 // When setting config during a Behat test (in the CLI script, not in the web browser
1413 // requests), remember which ones are set so that we can clear them later.
1414 if (defined('BEHAT_TEST')) {
1415 if (!property_exists($CFG, 'behat_cli_added_config')) {
1416 $CFG->behat_cli_added_config = [];
1418 $CFG->behat_cli_added_config[$name] = true;
1421 if ($name === 'siteidentifier') {
1422 cache_helper::update_site_identifier($value);
1424 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1427 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1428 if ($value===null) {
1429 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1431 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1434 if ($value !== null) {
1435 $config = new stdClass();
1436 $config->plugin = $plugin;
1437 $config->name = $name;
1438 $config->value = $value;
1439 $DB->insert_record('config_plugins', $config, false);
1442 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1449 * Get configuration values from the global config table
1450 * or the config_plugins table.
1452 * If called with one parameter, it will load all the config
1453 * variables for one plugin, and return them as an object.
1455 * If called with 2 parameters it will return a string single
1456 * value or false if the value is not found.
1458 * NOTE: this function is called from lib/db/upgrade.php
1460 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1461 * that we need only fetch it once per request.
1462 * @param string $plugin full component name
1463 * @param string $name default null
1464 * @return mixed hash-like object or single value, return false no config found
1465 * @throws dml_exception
1467 function get_config($plugin, $name = null) {
1470 static $siteidentifier = null;
1472 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1473 $forced =& $CFG->config_php_settings;
1477 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1478 $forced =& $CFG->forced_plugin_settings[$plugin];
1485 if ($siteidentifier === null) {
1487 // This may fail during installation.
1488 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1489 // install the database.
1490 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1491 } catch (dml_exception $ex) {
1492 // Set siteidentifier to false. We don't want to trip this continually.
1493 $siteidentifier = false;
1498 if (!empty($name)) {
1499 if (array_key_exists($name, $forced)) {
1500 return (string)$forced[$name];
1501 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1502 return $siteidentifier;
1506 $cache = cache::make('core', 'config');
1507 $result = $cache->get($plugin);
1508 if ($result === false) {
1509 // The user is after a recordset.
1511 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1513 // This part is not really used any more, but anyway...
1514 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1516 $cache->set($plugin, $result);
1519 if (!empty($name)) {
1520 if (array_key_exists($name, $result)) {
1521 return $result[$name];
1526 if ($plugin === 'core') {
1527 $result['siteidentifier'] = $siteidentifier;
1530 foreach ($forced as $key => $value) {
1531 if (is_null($value) or is_array($value) or is_object($value)) {
1532 // We do not want any extra mess here, just real settings that could be saved in db.
1533 unset($result[$key]);
1535 // Convert to string as if it went through the DB.
1536 $result[$key] = (string)$value;
1540 return (object)$result;
1544 * Removes a key from global configuration.
1546 * NOTE: this function is called from lib/db/upgrade.php
1548 * @param string $name the key to set
1549 * @param string $plugin (optional) the plugin scope
1550 * @return boolean whether the operation succeeded.
1552 function unset_config($name, $plugin=null) {
1555 if (empty($plugin)) {
1557 $DB->delete_records('config', array('name' => $name));
1558 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1560 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1561 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1568 * Remove all the config variables for a given plugin.
1570 * NOTE: this function is called from lib/db/upgrade.php
1572 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1573 * @return boolean whether the operation succeeded.
1575 function unset_all_config_for_plugin($plugin) {
1577 // Delete from the obvious config_plugins first.
1578 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1579 // Next delete any suspect settings from config.
1580 $like = $DB->sql_like('name', '?', true, true, false, '|');
1581 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1582 $DB->delete_records_select('config', $like, $params);
1583 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1584 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1590 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1592 * All users are verified if they still have the necessary capability.
1594 * @param string $value the value of the config setting.
1595 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1596 * @param bool $includeadmins include administrators.
1597 * @return array of user objects.
1599 function get_users_from_config($value, $capability, $includeadmins = true) {
1600 if (empty($value) or $value === '$@NONE@$') {
1604 // We have to make sure that users still have the necessary capability,
1605 // it should be faster to fetch them all first and then test if they are present
1606 // instead of validating them one-by-one.
1607 $users = get_users_by_capability(context_system::instance(), $capability);
1608 if ($includeadmins) {
1609 $admins = get_admins();
1610 foreach ($admins as $admin) {
1611 $users[$admin->id] = $admin;
1615 if ($value === '$@ALL@$') {
1619 $result = array(); // Result in correct order.
1620 $allowed = explode(',', $value);
1621 foreach ($allowed as $uid) {
1622 if (isset($users[$uid])) {
1623 $user = $users[$uid];
1624 $result[$user->id] = $user;
1633 * Invalidates browser caches and cached data in temp.
1637 function purge_all_caches() {
1642 * Selectively invalidate different types of cache.
1644 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1645 * areas alone or in combination.
1647 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1648 * 'muc' Purge MUC caches?
1649 * 'theme' Purge theme cache?
1650 * 'lang' Purge language string cache?
1651 * 'js' Purge javascript cache?
1652 * 'filter' Purge text filter cache?
1653 * 'other' Purge all other caches?
1655 function purge_caches($options = []) {
1656 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1657 if (empty(array_filter($options))) {
1658 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1660 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1662 if ($options['muc']) {
1663 cache_helper::purge_all();
1665 if ($options['theme']) {
1666 theme_reset_all_caches();
1668 if ($options['lang']) {
1669 get_string_manager()->reset_caches();
1671 if ($options['js']) {
1672 js_reset_all_caches();
1674 if ($options['template']) {
1675 template_reset_all_caches();
1677 if ($options['filter']) {
1678 reset_text_filters_cache();
1680 if ($options['other']) {
1681 purge_other_caches();
1686 * Purge all non-MUC caches not otherwise purged in purge_caches.
1688 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1689 * {@link phpunit_util::reset_dataroot()}
1691 function purge_other_caches() {
1693 core_text::reset_caches();
1694 if (class_exists('core_plugin_manager')) {
1695 core_plugin_manager::reset_caches();
1698 // Bump up cacherev field for all courses.
1700 increment_revision_number('course', 'cacherev', '');
1701 } catch (moodle_exception $e) {
1702 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1705 $DB->reset_caches();
1707 // Purge all other caches: rss, simplepie, etc.
1709 remove_dir($CFG->cachedir.'', true);
1711 // Make sure cache dir is writable, throws exception if not.
1712 make_cache_directory('');
1714 // This is the only place where we purge local caches, we are only adding files there.
1715 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1716 remove_dir($CFG->localcachedir, true);
1717 set_config('localcachedirpurged', time());
1718 make_localcache_directory('', true);
1719 \core\task\manager::clear_static_caches();
1723 * Get volatile flags
1725 * @param string $type
1726 * @param int $changedsince default null
1727 * @return array records array
1729 function get_cache_flags($type, $changedsince = null) {
1732 $params = array('type' => $type, 'expiry' => time());
1733 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1734 if ($changedsince !== null) {
1735 $params['changedsince'] = $changedsince;
1736 $sqlwhere .= " AND timemodified > :changedsince";
1739 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1740 foreach ($flags as $flag) {
1741 $cf[$flag->name] = $flag->value;
1748 * Get volatile flags
1750 * @param string $type
1751 * @param string $name
1752 * @param int $changedsince default null
1753 * @return string|false The cache flag value or false
1755 function get_cache_flag($type, $name, $changedsince=null) {
1758 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1760 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1761 if ($changedsince !== null) {
1762 $params['changedsince'] = $changedsince;
1763 $sqlwhere .= " AND timemodified > :changedsince";
1766 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1770 * Set a volatile flag
1772 * @param string $type the "type" namespace for the key
1773 * @param string $name the key to set
1774 * @param string $value the value to set (without magic quotes) - null will remove the flag
1775 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1776 * @return bool Always returns true
1778 function set_cache_flag($type, $name, $value, $expiry = null) {
1781 $timemodified = time();
1782 if ($expiry === null || $expiry < $timemodified) {
1783 $expiry = $timemodified + 24 * 60 * 60;
1785 $expiry = (int)$expiry;
1788 if ($value === null) {
1789 unset_cache_flag($type, $name);
1793 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1794 // This is a potential problem in DEBUG_DEVELOPER.
1795 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1796 return true; // No need to update.
1799 $f->expiry = $expiry;
1800 $f->timemodified = $timemodified;
1801 $DB->update_record('cache_flags', $f);
1803 $f = new stdClass();
1804 $f->flagtype = $type;
1807 $f->expiry = $expiry;
1808 $f->timemodified = $timemodified;
1809 $DB->insert_record('cache_flags', $f);
1815 * Removes a single volatile flag
1817 * @param string $type the "type" namespace for the key
1818 * @param string $name the key to set
1821 function unset_cache_flag($type, $name) {
1823 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1828 * Garbage-collect volatile flags
1830 * @return bool Always returns true
1832 function gc_cache_flags() {
1834 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1838 // USER PREFERENCE API.
1841 * Refresh user preference cache. This is used most often for $USER
1842 * object that is stored in session, but it also helps with performance in cron script.
1844 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1847 * @category preference
1849 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1850 * @param int $cachelifetime Cache life time on the current page (in seconds)
1851 * @throws coding_exception
1854 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1856 // Static cache, we need to check on each page load, not only every 2 minutes.
1857 static $loadedusers = array();
1859 if (!isset($user->id)) {
1860 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1863 if (empty($user->id) or isguestuser($user->id)) {
1864 // No permanent storage for not-logged-in users and guest.
1865 if (!isset($user->preference)) {
1866 $user->preference = array();
1873 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1874 // Already loaded at least once on this page. Are we up to date?
1875 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1876 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1879 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1880 // No change since the lastcheck on this page.
1881 $user->preference['_lastloaded'] = $timenow;
1886 // OK, so we have to reload all preferences.
1887 $loadedusers[$user->id] = true;
1888 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1889 $user->preference['_lastloaded'] = $timenow;
1893 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1895 * NOTE: internal function, do not call from other code.
1899 * @param integer $userid the user whose prefs were changed.
1901 function mark_user_preferences_changed($userid) {
1904 if (empty($userid) or isguestuser($userid)) {
1905 // No cache flags for guest and not-logged-in users.
1909 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1913 * Sets a preference for the specified user.
1915 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1917 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1920 * @category preference
1922 * @param string $name The key to set as preference for the specified user
1923 * @param string $value The value to set for the $name key in the specified user's
1924 * record, null means delete current value.
1925 * @param stdClass|int|null $user A moodle user object or id, null means current user
1926 * @throws coding_exception
1927 * @return bool Always true or exception
1929 function set_user_preference($name, $value, $user = null) {
1932 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1933 throw new coding_exception('Invalid preference name in set_user_preference() call');
1936 if (is_null($value)) {
1937 // Null means delete current.
1938 return unset_user_preference($name, $user);
1939 } else if (is_object($value)) {
1940 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1941 } else if (is_array($value)) {
1942 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1944 // Value column maximum length is 1333 characters.
1945 $value = (string)$value;
1946 if (core_text::strlen($value) > 1333) {
1947 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1950 if (is_null($user)) {
1952 } else if (isset($user->id)) {
1953 // It is a valid object.
1954 } else if (is_numeric($user)) {
1955 $user = (object)array('id' => (int)$user);
1957 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1960 check_user_preferences_loaded($user);
1962 if (empty($user->id) or isguestuser($user->id)) {
1963 // No permanent storage for not-logged-in users and guest.
1964 $user->preference[$name] = $value;
1968 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1969 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1970 // Preference already set to this value.
1973 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1976 $preference = new stdClass();
1977 $preference->userid = $user->id;
1978 $preference->name = $name;
1979 $preference->value = $value;
1980 $DB->insert_record('user_preferences', $preference);
1983 // Update value in cache.
1984 $user->preference[$name] = $value;
1985 // Update the $USER in case where we've not a direct reference to $USER.
1986 if ($user !== $USER && $user->id == $USER->id) {
1987 $USER->preference[$name] = $value;
1990 // Set reload flag for other sessions.
1991 mark_user_preferences_changed($user->id);
1997 * Sets a whole array of preferences for the current user
1999 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2002 * @category preference
2004 * @param array $prefarray An array of key/value pairs to be set
2005 * @param stdClass|int|null $user A moodle user object or id, null means current user
2006 * @return bool Always true or exception
2008 function set_user_preferences(array $prefarray, $user = null) {
2009 foreach ($prefarray as $name => $value) {
2010 set_user_preference($name, $value, $user);
2016 * Unsets a preference completely by deleting it from the database
2018 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2021 * @category preference
2023 * @param string $name The key to unset as preference for the specified user
2024 * @param stdClass|int|null $user A moodle user object or id, null means current user
2025 * @throws coding_exception
2026 * @return bool Always true or exception
2028 function unset_user_preference($name, $user = null) {
2031 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2032 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2035 if (is_null($user)) {
2037 } else if (isset($user->id)) {
2038 // It is a valid object.
2039 } else if (is_numeric($user)) {
2040 $user = (object)array('id' => (int)$user);
2042 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2045 check_user_preferences_loaded($user);
2047 if (empty($user->id) or isguestuser($user->id)) {
2048 // No permanent storage for not-logged-in user and guest.
2049 unset($user->preference[$name]);
2054 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2056 // Delete the preference from cache.
2057 unset($user->preference[$name]);
2058 // Update the $USER in case where we've not a direct reference to $USER.
2059 if ($user !== $USER && $user->id == $USER->id) {
2060 unset($USER->preference[$name]);
2063 // Set reload flag for other sessions.
2064 mark_user_preferences_changed($user->id);
2070 * Used to fetch user preference(s)
2072 * If no arguments are supplied this function will return
2073 * all of the current user preferences as an array.
2075 * If a name is specified then this function
2076 * attempts to return that particular preference value. If
2077 * none is found, then the optional value $default is returned,
2080 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2083 * @category preference
2085 * @param string $name Name of the key to use in finding a preference value
2086 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2087 * @param stdClass|int|null $user A moodle user object or id, null means current user
2088 * @throws coding_exception
2089 * @return string|mixed|null A string containing the value of a single preference. An
2090 * array with all of the preferences or null
2092 function get_user_preferences($name = null, $default = null, $user = null) {
2095 if (is_null($name)) {
2097 } else if (is_numeric($name) or $name === '_lastloaded') {
2098 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2101 if (is_null($user)) {
2103 } else if (isset($user->id)) {
2104 // Is a valid object.
2105 } else if (is_numeric($user)) {
2106 if ($USER->id == $user) {
2109 $user = (object)array('id' => (int)$user);
2112 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2115 check_user_preferences_loaded($user);
2119 return $user->preference;
2120 } else if (isset($user->preference[$name])) {
2121 // The single string value.
2122 return $user->preference[$name];
2124 // Default value (null if not specified).
2129 // FUNCTIONS FOR HANDLING TIME.
2132 * Given Gregorian date parts in user time produce a GMT timestamp.
2136 * @param int $year The year part to create timestamp of
2137 * @param int $month The month part to create timestamp of
2138 * @param int $day The day part to create timestamp of
2139 * @param int $hour The hour part to create timestamp of
2140 * @param int $minute The minute part to create timestamp of
2141 * @param int $second The second part to create timestamp of
2142 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2143 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2144 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2145 * applied only if timezone is 99 or string.
2146 * @return int GMT timestamp
2148 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2149 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2150 $date->setDate((int)$year, (int)$month, (int)$day);
2151 $date->setTime((int)$hour, (int)$minute, (int)$second);
2153 $time = $date->getTimestamp();
2155 if ($time === false) {
2156 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2157 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2160 // Moodle BC DST stuff.
2162 $time += dst_offset_on($time, $timezone);
2170 * Format a date/time (seconds) as weeks, days, hours etc as needed
2172 * Given an amount of time in seconds, returns string
2173 * formatted nicely as years, days, hours etc as needed
2181 * @param int $totalsecs Time in seconds
2182 * @param stdClass $str Should be a time object
2183 * @return string A nicely formatted date/time string
2185 function format_time($totalsecs, $str = null) {
2187 $totalsecs = abs($totalsecs);
2190 // Create the str structure the slow way.
2191 $str = new stdClass();
2192 $str->day = get_string('day');
2193 $str->days = get_string('days');
2194 $str->hour = get_string('hour');
2195 $str->hours = get_string('hours');
2196 $str->min = get_string('min');
2197 $str->mins = get_string('mins');
2198 $str->sec = get_string('sec');
2199 $str->secs = get_string('secs');
2200 $str->year = get_string('year');
2201 $str->years = get_string('years');
2204 $years = floor($totalsecs/YEARSECS);
2205 $remainder = $totalsecs - ($years*YEARSECS);
2206 $days = floor($remainder/DAYSECS);
2207 $remainder = $totalsecs - ($days*DAYSECS);
2208 $hours = floor($remainder/HOURSECS);
2209 $remainder = $remainder - ($hours*HOURSECS);
2210 $mins = floor($remainder/MINSECS);
2211 $secs = $remainder - ($mins*MINSECS);
2213 $ss = ($secs == 1) ? $str->sec : $str->secs;
2214 $sm = ($mins == 1) ? $str->min : $str->mins;
2215 $sh = ($hours == 1) ? $str->hour : $str->hours;
2216 $sd = ($days == 1) ? $str->day : $str->days;
2217 $sy = ($years == 1) ? $str->year : $str->years;
2226 $oyears = $years .' '. $sy;
2229 $odays = $days .' '. $sd;
2232 $ohours = $hours .' '. $sh;
2235 $omins = $mins .' '. $sm;
2238 $osecs = $secs .' '. $ss;
2242 return trim($oyears .' '. $odays);
2245 return trim($odays .' '. $ohours);
2248 return trim($ohours .' '. $omins);
2251 return trim($omins .' '. $osecs);
2256 return get_string('now');
2260 * Returns a formatted string that represents a date in user time.
2264 * @param int $date the timestamp in UTC, as obtained from the database.
2265 * @param string $format strftime format. You should probably get this using
2266 * get_string('strftime...', 'langconfig');
2267 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2268 * not 99 then daylight saving will not be added.
2269 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2270 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2271 * If false then the leading zero is maintained.
2272 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2273 * @return string the formatted date/time.
2275 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2276 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2277 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2281 * Returns a html "time" tag with both the exact user date with timezone information
2282 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2286 * @param int $date the timestamp in UTC, as obtained from the database.
2287 * @param string $format strftime format. You should probably get this using
2288 * get_string('strftime...', 'langconfig');
2289 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2290 * not 99 then daylight saving will not be added.
2291 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2292 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2293 * If false then the leading zero is maintained.
2294 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2295 * @return string the formatted date/time.
2297 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2298 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2299 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2300 return $userdatestr;
2302 $machinedate = new DateTime();
2303 $machinedate->setTimestamp(intval($date));
2304 $machinedate->setTimezone(core_date::get_user_timezone_object());
2306 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2310 * Returns a formatted date ensuring it is UTF-8.
2312 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2313 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2315 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2316 * @param string $format strftime format.
2317 * @param int|float|string $tz the user timezone
2318 * @return string the formatted date/time.
2319 * @since Moodle 2.3.3
2321 function date_format_string($date, $format, $tz = 99) {
2324 $localewincharset = null;
2325 // Get the calendar type user is using.
2326 if ($CFG->ostype == 'WINDOWS') {
2327 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2328 $localewincharset = $calendartype->locale_win_charset();
2331 if ($localewincharset) {
2332 $format = core_text::convert($format, 'utf-8', $localewincharset);
2335 date_default_timezone_set(core_date::get_user_timezone($tz));
2336 $datestring = strftime($format, $date);
2337 core_date::set_default_server_timezone();
2339 if ($localewincharset) {
2340 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2347 * Given a $time timestamp in GMT (seconds since epoch),
2348 * returns an array that represents the Gregorian date in user time
2352 * @param int $time Timestamp in GMT
2353 * @param float|int|string $timezone user timezone
2354 * @return array An array that represents the date in user time
2356 function usergetdate($time, $timezone=99) {
2357 date_default_timezone_set(core_date::get_user_timezone($timezone));
2358 $result = getdate($time);
2359 core_date::set_default_server_timezone();
2365 * Given a GMT timestamp (seconds since epoch), offsets it by
2366 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2368 * NOTE: this function does not include DST properly,
2369 * you should use the PHP date stuff instead!
2373 * @param int $date Timestamp in GMT
2374 * @param float|int|string $timezone user timezone
2377 function usertime($date, $timezone=99) {
2378 $userdate = new DateTime('@' . $date);
2379 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2380 $dst = dst_offset_on($date, $timezone);
2382 return $date - $userdate->getOffset() + $dst;
2386 * Get a formatted string representation of an interval between two unix timestamps.
2389 * $intervalstring = get_time_interval_string(12345600, 12345660);
2390 * Will produce the string:
2393 * @param int $time1 unix timestamp
2394 * @param int $time2 unix timestamp
2395 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2396 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2398 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2399 $dtdate = new DateTime();
2400 $dtdate->setTimeStamp($time1);
2401 $dtdate2 = new DateTime();
2402 $dtdate2->setTimeStamp($time2);
2403 $interval = $dtdate2->diff($dtdate);
2404 $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2405 return $interval->format($format);
2409 * Given a time, return the GMT timestamp of the most recent midnight
2410 * for the current user.
2414 * @param int $date Timestamp in GMT
2415 * @param float|int|string $timezone user timezone
2416 * @return int Returns a GMT timestamp
2418 function usergetmidnight($date, $timezone=99) {
2420 $userdate = usergetdate($date, $timezone);
2422 // Time of midnight of this user's day, in GMT.
2423 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2428 * Returns a string that prints the user's timezone
2432 * @param float|int|string $timezone user timezone
2435 function usertimezone($timezone=99) {
2436 $tz = core_date::get_user_timezone($timezone);
2437 return core_date::get_localised_timezone($tz);
2441 * Returns a float or a string which denotes the user's timezone
2442 * 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)
2443 * means that for this timezone there are also DST rules to be taken into account
2444 * Checks various settings and picks the most dominant of those which have a value
2448 * @param float|int|string $tz timezone to calculate GMT time offset before
2449 * calculating user timezone, 99 is default user timezone
2450 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2451 * @return float|string
2453 function get_user_timezone($tz = 99) {
2458 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2459 isset($USER->timezone) ? $USER->timezone : 99,
2460 isset($CFG->timezone) ? $CFG->timezone : 99,
2465 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2466 foreach ($timezones as $nextvalue) {
2467 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2471 return is_numeric($tz) ? (float) $tz : $tz;
2475 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2476 * - Note: Daylight saving only works for string timezones and not for float.
2480 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2481 * @param int|float|string $strtimezone user timezone
2484 function dst_offset_on($time, $strtimezone = null) {
2485 $tz = core_date::get_user_timezone($strtimezone);
2486 $date = new DateTime('@' . $time);
2487 $date->setTimezone(new DateTimeZone($tz));
2488 if ($date->format('I') == '1') {
2489 if ($tz === 'Australia/Lord_Howe') {
2498 * Calculates when the day appears in specific month
2502 * @param int $startday starting day of the month
2503 * @param int $weekday The day when week starts (normally taken from user preferences)
2504 * @param int $month The month whose day is sought
2505 * @param int $year The year of the month whose day is sought
2508 function find_day_in_month($startday, $weekday, $month, $year) {
2509 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2511 $daysinmonth = days_in_month($month, $year);
2512 $daysinweek = count($calendartype->get_weekdays());
2514 if ($weekday == -1) {
2515 // Don't care about weekday, so return:
2516 // abs($startday) if $startday != -1
2517 // $daysinmonth otherwise.
2518 return ($startday == -1) ? $daysinmonth : abs($startday);
2521 // From now on we 're looking for a specific weekday.
2522 // Give "end of month" its actual value, since we know it.
2523 if ($startday == -1) {
2524 $startday = -1 * $daysinmonth;
2527 // Starting from day $startday, the sign is the direction.
2528 if ($startday < 1) {
2529 $startday = abs($startday);
2530 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2532 // This is the last such weekday of the month.
2533 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2534 if ($lastinmonth > $daysinmonth) {
2535 $lastinmonth -= $daysinweek;
2538 // Find the first such weekday <= $startday.
2539 while ($lastinmonth > $startday) {
2540 $lastinmonth -= $daysinweek;
2543 return $lastinmonth;
2545 $indexweekday = dayofweek($startday, $month, $year);
2547 $diff = $weekday - $indexweekday;
2549 $diff += $daysinweek;
2552 // This is the first such weekday of the month equal to or after $startday.
2553 $firstfromindex = $startday + $diff;
2555 return $firstfromindex;
2560 * Calculate the number of days in a given month
2564 * @param int $month The month whose day count is sought
2565 * @param int $year The year of the month whose day count is sought
2568 function days_in_month($month, $year) {
2569 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2570 return $calendartype->get_num_days_in_month($year, $month);
2574 * Calculate the position in the week of a specific calendar day
2578 * @param int $day The day of the date whose position in the week is sought
2579 * @param int $month The month of the date whose position in the week is sought
2580 * @param int $year The year of the date whose position in the week is sought
2583 function dayofweek($day, $month, $year) {
2584 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2585 return $calendartype->get_weekday($year, $month, $day);
2588 // USER AUTHENTICATION AND LOGIN.
2591 * Returns full login url.
2593 * Any form submissions for authentication to this URL must include username,
2594 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2596 * @return string login url
2598 function get_login_url() {
2601 return "$CFG->wwwroot/login/index.php";
2605 * This function checks that the current user is logged in and has the
2606 * required privileges
2608 * This function checks that the current user is logged in, and optionally
2609 * whether they are allowed to be in a particular course and view a particular
2611 * If they are not logged in, then it redirects them to the site login unless
2612 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2613 * case they are automatically logged in as guests.
2614 * If $courseid is given and the user is not enrolled in that course then the
2615 * user is redirected to the course enrolment page.
2616 * If $cm is given and the course module is hidden and the user is not a teacher
2617 * in the course then the user is redirected to the course home page.
2619 * When $cm parameter specified, this function sets page layout to 'module'.
2620 * You need to change it manually later if some other layout needed.
2622 * @package core_access
2625 * @param mixed $courseorid id of the course or course object
2626 * @param bool $autologinguest default true
2627 * @param object $cm course module object
2628 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2629 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2630 * in order to keep redirects working properly. MDL-14495
2631 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2632 * @return mixed Void, exit, and die depending on path
2633 * @throws coding_exception
2634 * @throws require_login_exception
2635 * @throws moodle_exception
2637 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2638 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2640 // Must not redirect when byteserving already started.
2641 if (!empty($_SERVER['HTTP_RANGE'])) {
2642 $preventredirect = true;
2646 // We cannot redirect for AJAX scripts either.
2647 $preventredirect = true;
2650 // Setup global $COURSE, themes, language and locale.
2651 if (!empty($courseorid)) {
2652 if (is_object($courseorid)) {
2653 $course = $courseorid;
2654 } else if ($courseorid == SITEID) {
2655 $course = clone($SITE);
2657 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2660 if ($cm->course != $course->id) {
2661 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2663 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2664 if (!($cm instanceof cm_info)) {
2665 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2666 // db queries so this is not really a performance concern, however it is obviously
2667 // better if you use get_fast_modinfo to get the cm before calling this.
2668 $modinfo = get_fast_modinfo($course);
2669 $cm = $modinfo->get_cm($cm->id);
2673 // Do not touch global $COURSE via $PAGE->set_course(),
2674 // the reasons is we need to be able to call require_login() at any time!!
2677 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2681 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2682 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2683 // risk leading the user back to the AJAX request URL.
2684 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2685 $setwantsurltome = false;
2688 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2689 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2690 if ($preventredirect) {
2691 throw new require_login_session_timeout_exception();
2693 if ($setwantsurltome) {
2694 $SESSION->wantsurl = qualified_me();
2696 redirect(get_login_url());
2700 // If the user is not even logged in yet then make sure they are.
2701 if (!isloggedin()) {
2702 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2703 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2704 // Misconfigured site guest, just redirect to login page.
2705 redirect(get_login_url());
2706 exit; // Never reached.
2708 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2709 complete_user_login($guest);
2710 $USER->autologinguest = true;
2711 $SESSION->lang = $lang;
2713 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2714 if ($preventredirect) {
2715 throw new require_login_exception('You are not logged in');
2718 if ($setwantsurltome) {
2719 $SESSION->wantsurl = qualified_me();
2722 $referer = get_local_referer(false);
2723 if (!empty($referer)) {
2724 $SESSION->fromurl = $referer;
2727 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2728 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2729 foreach($authsequence as $authname) {
2730 $authplugin = get_auth_plugin($authname);
2731 $authplugin->pre_loginpage_hook();
2734 $modinfo = get_fast_modinfo($course);
2735 $cm = $modinfo->get_cm($cm->id);
2737 set_access_log_user();
2742 // If we're still not logged in then go to the login page
2743 if (!isloggedin()) {
2744 redirect(get_login_url());
2745 exit; // Never reached.
2750 // Loginas as redirection if needed.
2751 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2752 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2753 if ($USER->loginascontext->instanceid != $course->id) {
2754 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2759 // Check whether the user should be changing password (but only if it is REALLY them).
2760 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2761 $userauth = get_auth_plugin($USER->auth);
2762 if ($userauth->can_change_password() and !$preventredirect) {
2763 if ($setwantsurltome) {
2764 $SESSION->wantsurl = qualified_me();
2766 if ($changeurl = $userauth->change_password_url()) {
2767 // Use plugin custom url.
2768 redirect($changeurl);
2770 // Use moodle internal method.
2771 redirect($CFG->wwwroot .'/login/change_password.php');
2773 } else if ($userauth->can_change_password()) {
2774 throw new moodle_exception('forcepasswordchangenotice');
2776 throw new moodle_exception('nopasswordchangeforced', 'auth');
2780 // Check that the user account is properly set up. If we can't redirect to
2781 // edit their profile and this is not a WS request, perform just the lax check.
2782 // It will allow them to use filepicker on the profile edit page.
2784 if ($preventredirect && !WS_SERVER) {
2785 $usernotfullysetup = user_not_fully_set_up($USER, false);
2787 $usernotfullysetup = user_not_fully_set_up($USER, true);
2790 if ($usernotfullysetup) {
2791 if ($preventredirect) {
2792 throw new moodle_exception('usernotfullysetup');
2794 if ($setwantsurltome) {
2795 $SESSION->wantsurl = qualified_me();
2797 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2800 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2803 if (\core\session\manager::is_loggedinas()) {
2804 // During a "logged in as" session we should force all content to be cleaned because the
2805 // logged in user will be viewing potentially malicious user generated content.
2806 // See MDL-63786 for more details.
2807 $CFG->forceclean = true;
2810 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2812 // Do not bother admins with any formalities, except for activities pending deletion.
2813 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2814 // Set the global $COURSE.
2816 $PAGE->set_cm($cm, $course);
2817 $PAGE->set_pagelayout('incourse');
2818 } else if (!empty($courseorid)) {
2819 $PAGE->set_course($course);
2821 // Set accesstime or the user will appear offline which messes up messaging.
2822 // Do not update access time for webservice or ajax requests.
2823 if (!WS_SERVER && !AJAX_SCRIPT) {
2824 user_accesstime_log($course->id);
2827 foreach ($afterlogins as $plugintype => $plugins) {
2828 foreach ($plugins as $pluginfunction) {
2829 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2835 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2836 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2837 if (!defined('NO_SITEPOLICY_CHECK')) {
2838 define('NO_SITEPOLICY_CHECK', false);
2841 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2842 // Do not test if the script explicitly asked for skipping the site policies check.
2843 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2844 $manager = new \core_privacy\local\sitepolicy\manager();
2845 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2846 if ($preventredirect) {
2847 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2849 if ($setwantsurltome) {
2850 $SESSION->wantsurl = qualified_me();
2852 redirect($policyurl);
2856 // Fetch the system context, the course context, and prefetch its child contexts.
2857 $sysctx = context_system::instance();
2858 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2860 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2865 // If the site is currently under maintenance, then print a message.
2866 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2867 if ($preventredirect) {
2868 throw new require_login_exception('Maintenance in progress');
2870 $PAGE->set_context(null);
2871 print_maintenance_message();
2874 // Make sure the course itself is not hidden.
2875 if ($course->id == SITEID) {
2876 // Frontpage can not be hidden.
2878 if (is_role_switched($course->id)) {
2879 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2881 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2882 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2883 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2884 if ($preventredirect) {
2885 throw new require_login_exception('Course is hidden');
2887 $PAGE->set_context(null);
2888 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2889 // the navigation will mess up when trying to find it.
2890 navigation_node::override_active_url(new moodle_url('/'));
2891 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2896 // Is the user enrolled?
2897 if ($course->id == SITEID) {
2898 // Everybody is enrolled on the frontpage.
2900 if (\core\session\manager::is_loggedinas()) {
2901 // Make sure the REAL person can access this course first.
2902 $realuser = \core\session\manager::get_realuser();
2903 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2904 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2905 if ($preventredirect) {
2906 throw new require_login_exception('Invalid course login-as access');
2908 $PAGE->set_context(null);
2909 echo $OUTPUT->header();
2910 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2916 if (is_role_switched($course->id)) {
2917 // Ok, user had to be inside this course before the switch.
2920 } else if (is_viewing($coursecontext, $USER)) {
2921 // Ok, no need to mess with enrol.
2925 if (isset($USER->enrol['enrolled'][$course->id])) {
2926 if ($USER->enrol['enrolled'][$course->id] > time()) {
2928 if (isset($USER->enrol['tempguest'][$course->id])) {
2929 unset($USER->enrol['tempguest'][$course->id]);
2930 remove_temp_course_roles($coursecontext);
2934 unset($USER->enrol['enrolled'][$course->id]);
2937 if (isset($USER->enrol['tempguest'][$course->id])) {
2938 if ($USER->enrol['tempguest'][$course->id] == 0) {
2940 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2944 unset($USER->enrol['tempguest'][$course->id]);
2945 remove_temp_course_roles($coursecontext);
2951 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2952 if ($until !== false) {
2953 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2955 $until = ENROL_MAX_TIMESTAMP;
2957 $USER->enrol['enrolled'][$course->id] = $until;
2960 } else if (core_course_category::can_view_course_info($course)) {
2961 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2962 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2963 $enrols = enrol_get_plugins(true);
2964 // First ask all enabled enrol instances in course if they want to auto enrol user.
2965 foreach ($instances as $instance) {
2966 if (!isset($enrols[$instance->enrol])) {
2969 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2970 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2971 if ($until !== false) {
2973 $until = ENROL_MAX_TIMESTAMP;
2975 $USER->enrol['enrolled'][$course->id] = $until;
2980 // If not enrolled yet try to gain temporary guest access.
2982 foreach ($instances as $instance) {
2983 if (!isset($enrols[$instance->enrol])) {
2986 // Get a duration for the guest access, a timestamp in the future or false.
2987 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2988 if ($until !== false and $until > time()) {
2989 $USER->enrol['tempguest'][$course->id] = $until;
2996 // User is not enrolled and is not allowed to browse courses here.
2997 if ($preventredirect) {
2998 throw new require_login_exception('Course is not available');
3000 $PAGE->set_context(null);
3001 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3002 // the navigation will mess up when trying to find it.
3003 navigation_node::override_active_url(new moodle_url('/'));
3004 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3010 if ($preventredirect) {
3011 throw new require_login_exception('Not enrolled');
3013 if ($setwantsurltome) {
3014 $SESSION->wantsurl = qualified_me();
3016 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3020 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3021 if ($cm && $cm->deletioninprogress) {
3022 if ($preventredirect) {
3023 throw new moodle_exception('activityisscheduledfordeletion');
3025 require_once($CFG->dirroot . '/course/lib.php');
3026 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3029 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3030 if ($cm && !$cm->uservisible) {
3031 if ($preventredirect) {
3032 throw new require_login_exception('Activity is hidden');
3034 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3035 $PAGE->set_course($course);
3036 $renderer = $PAGE->get_renderer('course');
3037 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3038 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3041 // Set the global $COURSE.
3043 $PAGE->set_cm($cm, $course);
3044 $PAGE->set_pagelayout('incourse');
3045 } else if (!empty($courseorid)) {
3046 $PAGE->set_course($course);
3049 foreach ($afterlogins as $plugintype => $plugins) {
3050 foreach ($plugins as $pluginfunction) {
3051 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3055 // Finally access granted, update lastaccess times.
3056 // Do not update access time for webservice or ajax requests.
3057 if (!WS_SERVER && !AJAX_SCRIPT) {
3058 user_accesstime_log($course->id);
3063 * A convenience function for where we must be logged in as admin
3066 function require_admin() {
3067 require_login(null, false);
3068 require_capability('moodle/site:config', context_system::instance());
3072 * This function just makes sure a user is logged out.
3074 * @package core_access
3077 function require_logout() {
3080 if (!isloggedin()) {
3081 // This should not happen often, no need for hooks or events here.
3082 \core\session\manager::terminate_current();
3086 // Execute hooks before action.
3087 $authplugins = array();
3088 $authsequence = get_enabled_auth_plugins();
3089 foreach ($authsequence as $authname) {
3090 $authplugins[$authname] = get_auth_plugin($authname);
3091 $authplugins[$authname]->prelogout_hook();
3094 // Store info that gets removed during logout.
3095 $sid = session_id();
3096 $event = \core\event\user_loggedout::create(
3098 'userid' => $USER->id,
3099 'objectid' => $USER->id,
3100 'other' => array('sessionid' => $sid),
3103 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3104 $event->add_record_snapshot('sessions', $session);
3107 // Clone of $USER object to be used by auth plugins.
3108 $user = fullclone($USER);
3110 // Delete session record and drop $_SESSION content.
3111 \core\session\manager::terminate_current();
3113 // Trigger event AFTER action.
3116 // Hook to execute auth plugins redirection after event trigger.
3117 foreach ($authplugins as $authplugin) {
3118 $authplugin->postlogout_hook($user);
3123 * Weaker version of require_login()
3125 * This is a weaker version of {@link require_login()} which only requires login
3126 * when called from within a course rather than the site page, unless
3127 * the forcelogin option is turned on.
3128 * @see require_login()
3130 * @package core_access
3133 * @param mixed $courseorid The course object or id in question
3134 * @param bool $autologinguest Allow autologin guests if that is wanted
3135 * @param object $cm Course activity module if known
3136 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3137 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3138 * in order to keep redirects working properly. MDL-14495
3139 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3141 * @throws coding_exception
3143 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3144 global $CFG, $PAGE, $SITE;
3145 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3146 or (!is_object($courseorid) and $courseorid == SITEID));
3147 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3148 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3149 // db queries so this is not really a performance concern, however it is obviously
3150 // better if you use get_fast_modinfo to get the cm before calling this.
3151 if (is_object($courseorid)) {
3152 $course = $courseorid;
3154 $course = clone($SITE);
3156 $modinfo = get_fast_modinfo($course);
3157 $cm = $modinfo->get_cm($cm->id);
3159 if (!empty($CFG->forcelogin)) {
3160 // Login required for both SITE and courses.
3161 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3163 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3164 // Always login for hidden activities.
3165 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3167 } else if (isloggedin() && !isguestuser()) {
3168 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3169 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3171 } else if ($issite) {
3172 // Login for SITE not required.
3173 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3174 if (!empty($courseorid)) {
3175 if (is_object($courseorid)) {
3176 $course = $courseorid;
3178 $course = clone $SITE;
3181 if ($cm->course != $course->id) {
3182 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3184 $PAGE->set_cm($cm, $course);
3185 $PAGE->set_pagelayout('incourse');
3187 $PAGE->set_course($course);
3190 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3191 $PAGE->set_course($PAGE->course);
3193 // Do not update access time for webservice or ajax requests.
3194 if (!WS_SERVER && !AJAX_SCRIPT) {
3195 user_accesstime_log(SITEID);
3200 // Course login always required.
3201 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3206 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3208 * @param string $keyvalue the key value
3209 * @param string $script unique script identifier
3210 * @param int $instance instance id
3211 * @return stdClass the key entry in the user_private_key table
3213 * @throws moodle_exception
3215 function validate_user_key($keyvalue, $script, $instance) {
3218 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3219 print_error('invalidkey');
3222 if (!empty($key->validuntil) and $key->validuntil < time()) {
3223 print_error('expiredkey');
3226 if ($key->iprestriction) {
3227 $remoteaddr = getremoteaddr(null);
3228 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3229 print_error('ipmismatch');
3236 * Require key login. Function terminates with error if key not found or incorrect.
3238 * @uses NO_MOODLE_COOKIES
3239 * @uses PARAM_ALPHANUM
3240 * @param string $script unique script identifier
3241 * @param int $instance optional instance id
3242 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3243 * @return int Instance ID
3245 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3248 if (!NO_MOODLE_COOKIES) {
3249 print_error('sessioncookiesdisable');
3253 \core\session\manager::write_close();
3255 if (null === $keyvalue) {
3256 $keyvalue = required_param('key', PARAM_ALPHANUM);
3259 $key = validate_user_key($keyvalue, $script, $instance);
3261 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3262 print_error('invaliduserid');
3265 core_user::require_active_user($user, true, true);
3267 // Emulate normal session.
3268 enrol_check_plugins($user);
3269 \core\session\manager::set_user($user);
3271 // Note we are not using normal login.
3272 if (!defined('USER_KEY_LOGIN')) {
3273 define('USER_KEY_LOGIN', true);
3276 // Return instance id - it might be empty.
3277 return $key->instance;
3281 * Creates a new private user access key.
3283 * @param string $script unique target identifier
3284 * @param int $userid
3285 * @param int $instance optional instance id
3286 * @param string $iprestriction optional ip restricted access
3287 * @param int $validuntil key valid only until given data
3288 * @return string access key value
3290 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3293 $key = new stdClass();
3294 $key->script = $script;
3295 $key->userid = $userid;
3296 $key->instance = $instance;
3297 $key->iprestriction = $iprestriction;
3298 $key->validuntil = $validuntil;
3299 $key->timecreated = time();
3301 // Something long and unique.
3302 $key->value = md5($userid.'_'.time().random_string(40));
3303 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3305 $key->value = md5($userid.'_'.time().random_string(40));
3307 $DB->insert_record('user_private_key', $key);
3312 * Delete the user's new private user access keys for a particular script.
3314 * @param string $script unique target identifier
3315 * @param int $userid
3318 function delete_user_key($script, $userid) {
3320 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3324 * Gets a private user access key (and creates one if one doesn't exist).
3326 * @param string $script unique target identifier
3327 * @param int $userid
3328 * @param int $instance optional instance id
3329 * @param string $iprestriction optional ip restricted access
3330 * @param int $validuntil key valid only until given date
3331 * @return string access key value
3333 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3336 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3337 'instance' => $instance, 'iprestriction' => $iprestriction,
3338 'validuntil' => $validuntil))) {
3341 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3347 * Modify the user table by setting the currently logged in user's last login to now.
3349 * @return bool Always returns true
3351 function update_user_login_times() {
3354 if (isguestuser()) {
3355 // Do not update guest access times/ips for performance.
3361 $user = new stdClass();
3362 $user->id = $USER->id;
3364 // Make sure all users that logged in have some firstaccess.
3365 if ($USER->firstaccess == 0) {
3366 $USER->firstaccess = $user->firstaccess = $now;
3369 // Store the previous current as lastlogin.
3370 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3372 $USER->currentlogin = $user->currentlogin = $now;
3374 // Function user_accesstime_log() may not update immediately, better do it here.
3375 $USER->lastaccess = $user->lastaccess = $now;
3376 $USER->lastip = $user->lastip = getremoteaddr();
3378 // Note: do not call user_update_user() here because this is part of the login process,
3379 // the login event means that these fields were updated.
3380 $DB->update_record('user', $user);
3385 * Determines if a user has completed setting up their account.
3387 * The lax mode (with $strict = false) has been introduced for special cases
3388 * only where we want to skip certain checks intentionally. This is valid in
3389 * certain mnet or ajax scenarios when the user cannot / should not be
3390 * redirected to edit their profile. In most cases, you should perform the
3393 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3394 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3397 function user_not_fully_set_up($user, $strict = true) {
3399 require_once($CFG->dirroot.'/user/profile/lib.php');
3401 if (isguestuser($user)) {
3405 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3410 if (empty($user->id)) {
3411 // Strict mode can be used with existing accounts only.
3414 if (!profile_has_required_custom_fields_set($user->id)) {
3423 * Check whether the user has exceeded the bounce threshold
3425 * @param stdClass $user A {@link $USER} object
3426 * @return bool true => User has exceeded bounce threshold
3428 function over_bounce_threshold($user) {
3431 if (empty($CFG->handlebounces)) {
3435 if (empty($user->id)) {
3436 // No real (DB) user, nothing to do here.
3440 // Set sensible defaults.
3441 if (empty($CFG->minbounces)) {
3442 $CFG->minbounces = 10;
3444 if (empty($CFG->bounceratio)) {
3445 $CFG->bounceratio = .20;
3449 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3450 $bouncecount = $bounce->value;
3452 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3453 $sendcount = $send->value;
3455 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3459 * Used to increment or reset email sent count
3461 * @param stdClass $user object containing an id
3462 * @param bool $reset will reset the count to 0
3465 function set_send_count($user, $reset=false) {
3468 if (empty($user->id)) {
3469 // No real (DB) user, nothing to do here.
3473 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3474 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3475 $DB->update_record('user_preferences', $pref);
3476 } else if (!empty($reset)) {
3477 // If it's not there and we're resetting, don't bother. Make a new one.
3478 $pref = new stdClass();
3479 $pref->name = 'email_send_count';
3481 $pref->userid = $user->id;
3482 $DB->insert_record('user_preferences', $pref, false);
3487 * Increment or reset user's email bounce count
3489 * @param stdClass $user object containing an id
3490 * @param bool $reset will reset the count to 0
3492 function set_bounce_count($user, $reset=false) {
3495 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3496 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3497 $DB->update_record('user_preferences', $pref);
3498 } else if (!empty($reset)) {
3499 // If it's not there and we're resetting, don't bother. Make a new one.
3500 $pref = new stdClass();
3501 $pref->name = 'email_bounce_count';
3503 $pref->userid = $user->id;
3504 $DB->insert_record('user_preferences', $pref, false);
3509 * Determines if the logged in user is currently moving an activity
3511 * @param int $courseid The id of the course being tested
3514 function ismoving($courseid) {
3517 if (!empty($USER->activitycopy)) {
3518 return ($USER->activitycopycourse == $courseid);
3524 * Returns a persons full name
3526 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3527 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3528 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3529 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3531 * @param stdClass $user A {@link $USER} object to get full name of.
3532 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3535 function fullname($user, $override=false) {
3536 global $CFG, $SESSION;
3538 if (!isset($user->firstname) and !isset($user->lastname)) {
3542 // Get all of the name fields.
3543 $allnames = get_all_user_name_fields();
3544 if ($CFG->debugdeveloper) {
3545 foreach ($allnames as $allname) {
3546 if (!property_exists($user, $allname)) {
3547 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3548 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3549 // Message has been sent, no point in sending the message multiple times.
3556 if (!empty($CFG->forcefirstname)) {
3557 $user->firstname = $CFG->forcefirstname;
3559 if (!empty($CFG->forcelastname)) {
3560 $user->lastname = $CFG->forcelastname;
3564 if (!empty($SESSION->fullnamedisplay)) {
3565 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3569 // If the fullnamedisplay setting is available, set the template to that.
3570 if (isset($CFG->fullnamedisplay)) {
3571 $template = $CFG->fullnamedisplay;
3573 // If the template is empty, or set to language, return the language string.
3574 if ((empty($template) || $template == 'language') && !$override) {
3575 return get_string('fullnamedisplay', null, $user);
3578 // Check to see if we are displaying according to the alternative full name format.
3580 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3581 // Default to show just the user names according to the fullnamedisplay string.
3582 return get_string('fullnamedisplay', null, $user);
3584 // If the override is true, then change the template to use the complete name.
3585 $template = $CFG->alternativefullnameformat;
3589 $requirednames = array();
3590 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3591 foreach ($allnames as $allname) {
3592 if (strpos($template, $allname) !== false) {
3593 $requirednames[] = $allname;
3597 $displayname = $template;
3598 // Switch in the actual data into the template.
3599 foreach ($requirednames as $altname) {
3600 if (isset($user->$altname)) {
3601 // Using empty() on the below if statement causes breakages.
3602 if ((string)$user->$altname == '') {
3603 $displayname = str_replace($altname, 'EMPTY', $displayname);
3605 $displayname = str_replace($altname, $user->$altname, $displayname);
3608 $displayname = str_replace($altname, 'EMPTY', $displayname);
3611 // Tidy up any misc. characters (Not perfect, but gets most characters).
3612 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3613 // katakana and parenthesis.
3614 $patterns = array();
3615 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3616 // filled in by a user.
3617 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3618 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3619 // This regular expression is to remove any double spaces in the display name.
3620 $patterns[] = '/\s{2,}/u';
3621 foreach ($patterns as $pattern) {
3622 $displayname = preg_replace($pattern, ' ', $displayname);
3625 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3626 $displayname = trim($displayname);
3627 if (empty($displayname)) {
3628 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3629 // people in general feel is a good setting to fall back on.
3630 $displayname = $user->firstname;
3632 return $displayname;
3636 * A centralised location for the all name fields. Returns an array / sql string snippet.
3638 * @param bool $returnsql True for an sql select field snippet.
3639 * @param string $tableprefix table query prefix to use in front of each field.
3640 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3641 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3642 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3643 * @return array|string All name fields.
3645 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3646 // This array is provided in this order because when called