2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
83 define('PARAM_ALPHAEXT', 'alphaext');
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
98 define('PARAM_AUTH', 'auth');
101 * PARAM_BASE64 - Base 64 encoded format
103 define('PARAM_BASE64', 'base64');
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
108 define('PARAM_BOOL', 'bool');
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
114 define('PARAM_CAPABILITY', 'capability');
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when 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 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
146 define('PARAM_FLOAT', 'float');
149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
151 define('PARAM_HOST', 'host');
154 * PARAM_INT - integers only, use when expecting only numbers.
156 define('PARAM_INT', 'int');
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
161 define('PARAM_LANG', 'lang');
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
167 define('PARAM_LOCALURL', 'localurl');
170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
172 define('PARAM_NOTAGS', 'notags');
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
178 define('PARAM_PATH', 'path');
181 * PARAM_PEM - Privacy Enhanced Mail format
183 define('PARAM_PEM', 'pem');
186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
188 define('PARAM_PERMISSION', 'permission');
191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
193 define('PARAM_RAW', 'raw');
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
203 define('PARAM_SAFEDIR', 'safedir');
206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
208 define('PARAM_SAFEPATH', 'safepath');
211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
213 define('PARAM_SEQUENCE', 'sequence');
216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
218 define('PARAM_TAG', 'tag');
221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
223 define('PARAM_TAGLIST', 'taglist');
226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
228 define('PARAM_TEXT', 'text');
231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
233 define('PARAM_THEME', 'theme');
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
245 define('PARAM_USERNAME', 'username');
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
250 define('PARAM_STRINGID', 'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
256 * @deprecated since 2.0
258 define('PARAM_CLEAN', 'clean');
261 * PARAM_INTEGER - deprecated alias for PARAM_INT
262 * @deprecated since 2.0
264 define('PARAM_INTEGER', 'int');
267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268 * @deprecated since 2.0
270 define('PARAM_NUMBER', 'float');
273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274 * NOTE: originally alias for PARAM_APLHA
275 * @deprecated since 2.0
277 define('PARAM_ACTION', 'alphanumext');
280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
282 * @deprecated since 2.0
284 define('PARAM_FORMAT', 'alphanumext');
287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288 * @deprecated since 2.0
290 define('PARAM_MULTILANG', 'text');
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295 * America/Port-au-Prince)
297 define('PARAM_TIMEZONE', 'timezone');
300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
302 define('PARAM_CLEANFILE', 'file');
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
310 define('PARAM_COMPONENT', 'component');
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
317 define('PARAM_AREA', 'area');
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
324 define('PARAM_PLUGIN', 'plugin');
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
332 define('VALUE_REQUIRED', 1);
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
337 define('VALUE_OPTIONAL', 2);
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
342 define('VALUE_DEFAULT', 0);
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
347 define('NULL_NOT_ALLOWED', false);
350 * NULL_ALLOWED - the parameter can be set to null in the database
352 define('NULL_ALLOWED', true);
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
443 * Maximum filename char size
445 define('MAX_FILENAME_SIZE', 100);
447 /** Unspecified module archetype */
448 define('MOD_ARCHETYPE_OTHER', 0);
449 /** Resource-like type module */
450 define('MOD_ARCHETYPE_RESOURCE', 1);
451 /** Assignment module archetype */
452 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
453 /** System (not user-addable) module archetype */
454 define('MOD_ARCHETYPE_SYSTEM', 3);
457 * Security token used for allowing access
458 * from external application such as web services.
459 * Scripts do not use any session, performance is relatively
460 * low because we need to load access info in each request.
461 * Scripts are executed in parallel.
463 define('EXTERNAL_TOKEN_PERMANENT', 0);
466 * Security token used for allowing access
467 * of embedded applications, the code is executed in the
468 * active user session. Token is invalidated after user logs out.
469 * Scripts are executed serially - normal session locking is used.
471 define('EXTERNAL_TOKEN_EMBEDDED', 1);
474 * The home page should be the site home
476 define('HOMEPAGE_SITE', 0);
478 * The home page should be the users my page
480 define('HOMEPAGE_MY', 1);
482 * The home page can be chosen by the user
484 define('HOMEPAGE_USER', 2);
487 * Hub directory url (should be moodle.org)
489 define('HUB_HUBDIRECTORYURL', "https://hubdirectory.moodle.org");
493 * Moodle.net url (should be moodle.net)
495 define('HUB_MOODLEORGHUBURL', "https://moodle.net");
496 define('HUB_OLDMOODLEORGHUBURL', "http://hub.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;
847 // Remove everything not `a-z`.
848 return preg_replace('/[^a-zA-Z]/i', '', $param);
851 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
852 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
855 // Remove everything not `a-zA-Z0-9`.
856 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
858 case PARAM_ALPHANUMEXT:
859 // Remove everything not `a-zA-Z0-9_-`.
860 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
863 // Remove everything not `0-9,`.
864 return preg_replace('/[^0-9,]/i', '', $param);
867 // Convert to 1 or 0.
868 $tempstr = strtolower($param);
869 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
871 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
874 $param = empty($param) ? 0 : 1;
880 $param = fix_utf8($param);
881 return strip_tags($param);
884 // Leave only tags needed for multilang.
885 $param = fix_utf8($param);
886 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
887 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
889 if (strpos($param, '</lang>') !== false) {
890 // Old and future mutilang syntax.
891 $param = strip_tags($param, '<lang>');
892 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
896 foreach ($matches[0] as $match) {
897 if ($match === '</lang>') {
905 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
916 } else if (strpos($param, '</span>') !== false) {
917 // Current problematic multilang syntax.
918 $param = strip_tags($param, '<span>');
919 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
923 foreach ($matches[0] as $match) {
924 if ($match === '</span>') {
932 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
944 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
945 return strip_tags($param);
947 case PARAM_COMPONENT:
948 // We do not want any guessing here, either the name is correct or not
949 // please note only normalised component names are accepted.
950 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
953 if (strpos($param, '__') !== false) {
956 if (strpos($param, 'mod_') === 0) {
957 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
958 if (substr_count($param, '_') != 1) {
966 // We do not want any guessing here, either the name is correct or not.
967 if (!is_valid_plugin_name($param)) {
973 // Remove everything not a-zA-Z0-9_- .
974 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
977 // Remove everything not a-zA-Z0-9/_- .
978 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
981 // Strip all suspicious characters from filename.
982 $param = fix_utf8($param);
983 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
984 if ($param === '.' || $param === '..') {
990 // Strip all suspicious characters from file path.
991 $param = fix_utf8($param);
992 $param = str_replace('\\', '/', $param);
994 // Explode the path and clean each element using the PARAM_FILE rules.
995 $breadcrumb = explode('/', $param);
996 foreach ($breadcrumb as $key => $crumb) {
997 if ($crumb === '.' && $key === 0) {
998 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1000 $crumb = clean_param($crumb, PARAM_FILE);
1002 $breadcrumb[$key] = $crumb;
1004 $param = implode('/', $breadcrumb);
1006 // Remove multiple current path (./././) and multiple slashes (///).
1007 $param = preg_replace('~//+~', '/', $param);
1008 $param = preg_replace('~/(\./)+~', '/', $param);
1012 // Allow FQDN or IPv4 dotted quad.
1013 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1014 // Match ipv4 dotted quad.
1015 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1016 // Confirm values are ok.
1017 if ( $match[0] > 255
1020 || $match[4] > 255 ) {
1021 // Hmmm, what kind of dotted quad is this?
1024 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1025 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1026 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1028 // All is ok - $param is respected.
1037 $param = fix_utf8($param);
1038 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1039 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1040 // All is ok, param is respected.
1047 case PARAM_LOCALURL:
1048 // Allow http absolute, root relative and relative URLs within wwwroot.
1049 $param = clean_param($param, PARAM_URL);
1050 if (!empty($param)) {
1052 if ($param === $CFG->wwwroot) {
1054 } else if (preg_match(':^/:', $param)) {
1055 // Root-relative, ok!
1056 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1057 // Absolute, and matches our wwwroot.
1059 // Relative - let's make sure there are no tricks.
1060 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1070 $param = trim($param);
1071 // PEM formatted strings may contain letters/numbers and the symbols:
1075 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1076 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1077 list($wholething, $body) = $matches;
1078 unset($wholething, $matches);
1079 $b64 = clean_param($body, PARAM_BASE64);
1081 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1089 if (!empty($param)) {
1090 // PEM formatted strings may contain letters/numbers and the symbols
1094 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1097 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1098 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1099 // than (or equal to) 64 characters long.
1100 for ($i=0, $j=count($lines); $i < $j; $i++) {
1102 if (64 < strlen($lines[$i])) {
1108 if (64 != strlen($lines[$i])) {
1112 return implode("\n", $lines);
1118 $param = fix_utf8($param);
1119 // Please note it is not safe to use the tag name directly anywhere,
1120 // it must be processed with s(), urlencode() before embedding anywhere.
1121 // Remove some nasties.
1122 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1123 // Convert many whitespace chars into one.
1124 $param = preg_replace('/\s+/u', ' ', $param);
1125 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1129 $param = fix_utf8($param);
1130 $tags = explode(',', $param);
1132 foreach ($tags as $tag) {
1133 $res = clean_param($tag, PARAM_TAG);
1139 return implode(',', $result);
1144 case PARAM_CAPABILITY:
1145 if (get_capability_info($param)) {
1151 case PARAM_PERMISSION:
1152 $param = (int)$param;
1153 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1160 $param = clean_param($param, PARAM_PLUGIN);
1161 if (empty($param)) {
1163 } else if (exists_auth_plugin($param)) {
1170 $param = clean_param($param, PARAM_SAFEDIR);
1171 if (get_string_manager()->translation_exists($param)) {
1174 // Specified language is not installed or param malformed.
1179 $param = clean_param($param, PARAM_PLUGIN);
1180 if (empty($param)) {
1182 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1184 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1187 // Specified theme is not installed.
1191 case PARAM_USERNAME:
1192 $param = fix_utf8($param);
1193 $param = trim($param);
1194 // Convert uppercase to lowercase MDL-16919.
1195 $param = core_text::strtolower($param);
1196 if (empty($CFG->extendedusernamechars)) {
1197 $param = str_replace(" " , "", $param);
1198 // Regular expression, eliminate all chars EXCEPT:
1199 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1200 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1205 $param = fix_utf8($param);
1206 if (validate_email($param)) {
1212 case PARAM_STRINGID:
1213 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1219 case PARAM_TIMEZONE:
1220 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1221 $param = fix_utf8($param);
1222 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1223 if (preg_match($timezonepattern, $param)) {
1230 // Doh! throw error, switched parameters in optional_param or another serious problem.
1231 print_error("unknownparamtype", '', '', $type);
1236 * Whether the PARAM_* type is compatible in RTL.
1238 * Being compatible with RTL means that the data they contain can flow
1239 * from right-to-left or left-to-right without compromising the user experience.
1241 * Take URLs for example, they are not RTL compatible as they should always
1242 * flow from the left to the right. This also applies to numbers, email addresses,
1243 * configuration snippets, base64 strings, etc...
1245 * This function tries to best guess which parameters can contain localised strings.
1247 * @param string $paramtype Constant PARAM_*.
1250 function is_rtl_compatible($paramtype) {
1251 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1255 * Makes sure the data is using valid utf8, invalid characters are discarded.
1257 * Note: this function is not intended for full objects with methods and private properties.
1259 * @param mixed $value
1260 * @return mixed with proper utf-8 encoding
1262 function fix_utf8($value) {
1263 if (is_null($value) or $value === '') {
1266 } else if (is_string($value)) {
1267 if ((string)(int)$value === $value) {
1271 // No null bytes expected in our data, so let's remove it.
1272 $value = str_replace("\0", '', $value);
1274 // Note: this duplicates min_fix_utf8() intentionally.
1275 static $buggyiconv = null;
1276 if ($buggyiconv === null) {
1277 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1281 if (function_exists('mb_convert_encoding')) {
1282 $subst = mb_substitute_character();
1283 mb_substitute_character('');
1284 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1285 mb_substitute_character($subst);
1288 // Warn admins on admin/index.php page.
1293 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1298 } else if (is_array($value)) {
1299 foreach ($value as $k => $v) {
1300 $value[$k] = fix_utf8($v);
1304 } else if (is_object($value)) {
1305 // Do not modify original.
1306 $value = clone($value);
1307 foreach ($value as $k => $v) {
1308 $value->$k = fix_utf8($v);
1313 // This is some other type, no utf-8 here.
1319 * Return true if given value is integer or string with integer value
1321 * @param mixed $value String or Int
1322 * @return bool true if number, false if not
1324 function is_number($value) {
1325 if (is_int($value)) {
1327 } else if (is_string($value)) {
1328 return ((string)(int)$value) === $value;
1335 * Returns host part from url.
1337 * @param string $url full url
1338 * @return string host, null if not found
1340 function get_host_from_url($url) {
1341 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1349 * Tests whether anything was returned by text editor
1351 * This function is useful for testing whether something you got back from
1352 * the HTML editor actually contains anything. Sometimes the HTML editor
1353 * appear to be empty, but actually you get back a <br> tag or something.
1355 * @param string $string a string containing HTML.
1356 * @return boolean does the string contain any actual content - that is text,
1357 * images, objects, etc.
1359 function html_is_blank($string) {
1360 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1364 * Set a key in global configuration
1366 * Set a key/value pair in both this session's {@link $CFG} global variable
1367 * and in the 'config' database table for future sessions.
1369 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1370 * In that case it doesn't affect $CFG.
1372 * A NULL value will delete the entry.
1374 * NOTE: this function is called from lib/db/upgrade.php
1376 * @param string $name the key to set
1377 * @param string $value the value to set (without magic quotes)
1378 * @param string $plugin (optional) the plugin scope, default null
1379 * @return bool true or exception
1381 function set_config($name, $value, $plugin=null) {
1384 if (empty($plugin)) {
1385 if (!array_key_exists($name, $CFG->config_php_settings)) {
1386 // So it's defined for this invocation at least.
1387 if (is_null($value)) {
1390 // Settings from db are always strings.
1391 $CFG->$name = (string)$value;
1395 if ($DB->get_field('config', 'name', array('name' => $name))) {
1396 if ($value === null) {
1397 $DB->delete_records('config', array('name' => $name));
1399 $DB->set_field('config', 'value', $value, array('name' => $name));
1402 if ($value !== null) {
1403 $config = new stdClass();
1404 $config->name = $name;
1405 $config->value = $value;
1406 $DB->insert_record('config', $config, false);
1409 if ($name === 'siteidentifier') {
1410 cache_helper::update_site_identifier($value);
1412 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1415 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1416 if ($value===null) {
1417 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1419 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1422 if ($value !== null) {
1423 $config = new stdClass();
1424 $config->plugin = $plugin;
1425 $config->name = $name;
1426 $config->value = $value;
1427 $DB->insert_record('config_plugins', $config, false);
1430 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1437 * Get configuration values from the global config table
1438 * or the config_plugins table.
1440 * If called with one parameter, it will load all the config
1441 * variables for one plugin, and return them as an object.
1443 * If called with 2 parameters it will return a string single
1444 * value or false if the value is not found.
1446 * NOTE: this function is called from lib/db/upgrade.php
1448 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1449 * that we need only fetch it once per request.
1450 * @param string $plugin full component name
1451 * @param string $name default null
1452 * @return mixed hash-like object or single value, return false no config found
1453 * @throws dml_exception
1455 function get_config($plugin, $name = null) {
1458 static $siteidentifier = null;
1460 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1461 $forced =& $CFG->config_php_settings;
1465 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1466 $forced =& $CFG->forced_plugin_settings[$plugin];
1473 if ($siteidentifier === null) {
1475 // This may fail during installation.
1476 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1477 // install the database.
1478 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1479 } catch (dml_exception $ex) {
1480 // Set siteidentifier to false. We don't want to trip this continually.
1481 $siteidentifier = false;
1486 if (!empty($name)) {
1487 if (array_key_exists($name, $forced)) {
1488 return (string)$forced[$name];
1489 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1490 return $siteidentifier;
1494 $cache = cache::make('core', 'config');
1495 $result = $cache->get($plugin);
1496 if ($result === false) {
1497 // The user is after a recordset.
1499 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1501 // This part is not really used any more, but anyway...
1502 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1504 $cache->set($plugin, $result);
1507 if (!empty($name)) {
1508 if (array_key_exists($name, $result)) {
1509 return $result[$name];
1514 if ($plugin === 'core') {
1515 $result['siteidentifier'] = $siteidentifier;
1518 foreach ($forced as $key => $value) {
1519 if (is_null($value) or is_array($value) or is_object($value)) {
1520 // We do not want any extra mess here, just real settings that could be saved in db.
1521 unset($result[$key]);
1523 // Convert to string as if it went through the DB.
1524 $result[$key] = (string)$value;
1528 return (object)$result;
1532 * Removes a key from global configuration.
1534 * NOTE: this function is called from lib/db/upgrade.php
1536 * @param string $name the key to set
1537 * @param string $plugin (optional) the plugin scope
1538 * @return boolean whether the operation succeeded.
1540 function unset_config($name, $plugin=null) {
1543 if (empty($plugin)) {
1545 $DB->delete_records('config', array('name' => $name));
1546 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1548 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1549 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1556 * Remove all the config variables for a given plugin.
1558 * NOTE: this function is called from lib/db/upgrade.php
1560 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1561 * @return boolean whether the operation succeeded.
1563 function unset_all_config_for_plugin($plugin) {
1565 // Delete from the obvious config_plugins first.
1566 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1567 // Next delete any suspect settings from config.
1568 $like = $DB->sql_like('name', '?', true, true, false, '|');
1569 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1570 $DB->delete_records_select('config', $like, $params);
1571 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1572 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1578 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1580 * All users are verified if they still have the necessary capability.
1582 * @param string $value the value of the config setting.
1583 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1584 * @param bool $includeadmins include administrators.
1585 * @return array of user objects.
1587 function get_users_from_config($value, $capability, $includeadmins = true) {
1588 if (empty($value) or $value === '$@NONE@$') {
1592 // We have to make sure that users still have the necessary capability,
1593 // it should be faster to fetch them all first and then test if they are present
1594 // instead of validating them one-by-one.
1595 $users = get_users_by_capability(context_system::instance(), $capability);
1596 if ($includeadmins) {
1597 $admins = get_admins();
1598 foreach ($admins as $admin) {
1599 $users[$admin->id] = $admin;
1603 if ($value === '$@ALL@$') {
1607 $result = array(); // Result in correct order.
1608 $allowed = explode(',', $value);
1609 foreach ($allowed as $uid) {
1610 if (isset($users[$uid])) {
1611 $user = $users[$uid];
1612 $result[$user->id] = $user;
1621 * Invalidates browser caches and cached data in temp.
1625 function purge_all_caches() {
1630 * Selectively invalidate different types of cache.
1632 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1633 * areas alone or in combination.
1635 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1636 * 'muc' Purge MUC caches?
1637 * 'theme' Purge theme cache?
1638 * 'lang' Purge language string cache?
1639 * 'js' Purge javascript cache?
1640 * 'filter' Purge text filter cache?
1641 * 'other' Purge all other caches?
1643 function purge_caches($options = []) {
1644 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'filter', 'other'], false);
1645 if (empty(array_filter($options))) {
1646 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1648 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1650 if ($options['muc']) {
1651 cache_helper::purge_all();
1653 if ($options['theme']) {
1654 theme_reset_all_caches();
1656 if ($options['lang']) {
1657 get_string_manager()->reset_caches();
1659 if ($options['js']) {
1660 js_reset_all_caches();
1662 if ($options['filter']) {
1663 reset_text_filters_cache();
1665 if ($options['other']) {
1666 purge_other_caches();
1671 * Purge all non-MUC caches not otherwise purged in purge_caches.
1673 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1674 * {@link phpunit_util::reset_dataroot()}
1676 function purge_other_caches() {
1678 core_text::reset_caches();
1679 if (class_exists('core_plugin_manager')) {
1680 core_plugin_manager::reset_caches();
1683 // Bump up cacherev field for all courses.
1685 increment_revision_number('course', 'cacherev', '');
1686 } catch (moodle_exception $e) {
1687 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1690 $DB->reset_caches();
1692 // Purge all other caches: rss, simplepie, etc.
1694 remove_dir($CFG->cachedir.'', true);
1696 // Make sure cache dir is writable, throws exception if not.
1697 make_cache_directory('');
1699 // This is the only place where we purge local caches, we are only adding files there.
1700 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1701 remove_dir($CFG->localcachedir, true);
1702 set_config('localcachedirpurged', time());
1703 make_localcache_directory('', true);
1704 \core\task\manager::clear_static_caches();
1708 * Get volatile flags
1710 * @param string $type
1711 * @param int $changedsince default null
1712 * @return array records array
1714 function get_cache_flags($type, $changedsince = null) {
1717 $params = array('type' => $type, 'expiry' => time());
1718 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1719 if ($changedsince !== null) {
1720 $params['changedsince'] = $changedsince;
1721 $sqlwhere .= " AND timemodified > :changedsince";
1724 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1725 foreach ($flags as $flag) {
1726 $cf[$flag->name] = $flag->value;
1733 * Get volatile flags
1735 * @param string $type
1736 * @param string $name
1737 * @param int $changedsince default null
1738 * @return string|false The cache flag value or false
1740 function get_cache_flag($type, $name, $changedsince=null) {
1743 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1745 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1746 if ($changedsince !== null) {
1747 $params['changedsince'] = $changedsince;
1748 $sqlwhere .= " AND timemodified > :changedsince";
1751 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1755 * Set a volatile flag
1757 * @param string $type the "type" namespace for the key
1758 * @param string $name the key to set
1759 * @param string $value the value to set (without magic quotes) - null will remove the flag
1760 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1761 * @return bool Always returns true
1763 function set_cache_flag($type, $name, $value, $expiry = null) {
1766 $timemodified = time();
1767 if ($expiry === null || $expiry < $timemodified) {
1768 $expiry = $timemodified + 24 * 60 * 60;
1770 $expiry = (int)$expiry;
1773 if ($value === null) {
1774 unset_cache_flag($type, $name);
1778 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1779 // This is a potential problem in DEBUG_DEVELOPER.
1780 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1781 return true; // No need to update.
1784 $f->expiry = $expiry;
1785 $f->timemodified = $timemodified;
1786 $DB->update_record('cache_flags', $f);
1788 $f = new stdClass();
1789 $f->flagtype = $type;
1792 $f->expiry = $expiry;
1793 $f->timemodified = $timemodified;
1794 $DB->insert_record('cache_flags', $f);
1800 * Removes a single volatile flag
1802 * @param string $type the "type" namespace for the key
1803 * @param string $name the key to set
1806 function unset_cache_flag($type, $name) {
1808 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1813 * Garbage-collect volatile flags
1815 * @return bool Always returns true
1817 function gc_cache_flags() {
1819 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1823 // USER PREFERENCE API.
1826 * Refresh user preference cache. This is used most often for $USER
1827 * object that is stored in session, but it also helps with performance in cron script.
1829 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1832 * @category preference
1834 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1835 * @param int $cachelifetime Cache life time on the current page (in seconds)
1836 * @throws coding_exception
1839 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1841 // Static cache, we need to check on each page load, not only every 2 minutes.
1842 static $loadedusers = array();
1844 if (!isset($user->id)) {
1845 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1848 if (empty($user->id) or isguestuser($user->id)) {
1849 // No permanent storage for not-logged-in users and guest.
1850 if (!isset($user->preference)) {
1851 $user->preference = array();
1858 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1859 // Already loaded at least once on this page. Are we up to date?
1860 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1861 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1864 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1865 // No change since the lastcheck on this page.
1866 $user->preference['_lastloaded'] = $timenow;
1871 // OK, so we have to reload all preferences.
1872 $loadedusers[$user->id] = true;
1873 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1874 $user->preference['_lastloaded'] = $timenow;
1878 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1880 * NOTE: internal function, do not call from other code.
1884 * @param integer $userid the user whose prefs were changed.
1886 function mark_user_preferences_changed($userid) {
1889 if (empty($userid) or isguestuser($userid)) {
1890 // No cache flags for guest and not-logged-in users.
1894 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1898 * Sets a preference for the specified user.
1900 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1902 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1905 * @category preference
1907 * @param string $name The key to set as preference for the specified user
1908 * @param string $value The value to set for the $name key in the specified user's
1909 * record, null means delete current value.
1910 * @param stdClass|int|null $user A moodle user object or id, null means current user
1911 * @throws coding_exception
1912 * @return bool Always true or exception
1914 function set_user_preference($name, $value, $user = null) {
1917 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1918 throw new coding_exception('Invalid preference name in set_user_preference() call');
1921 if (is_null($value)) {
1922 // Null means delete current.
1923 return unset_user_preference($name, $user);
1924 } else if (is_object($value)) {
1925 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1926 } else if (is_array($value)) {
1927 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1929 // Value column maximum length is 1333 characters.
1930 $value = (string)$value;
1931 if (core_text::strlen($value) > 1333) {
1932 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1935 if (is_null($user)) {
1937 } else if (isset($user->id)) {
1938 // It is a valid object.
1939 } else if (is_numeric($user)) {
1940 $user = (object)array('id' => (int)$user);
1942 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1945 check_user_preferences_loaded($user);
1947 if (empty($user->id) or isguestuser($user->id)) {
1948 // No permanent storage for not-logged-in users and guest.
1949 $user->preference[$name] = $value;
1953 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1954 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1955 // Preference already set to this value.
1958 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1961 $preference = new stdClass();
1962 $preference->userid = $user->id;
1963 $preference->name = $name;
1964 $preference->value = $value;
1965 $DB->insert_record('user_preferences', $preference);
1968 // Update value in cache.
1969 $user->preference[$name] = $value;
1970 // Update the $USER in case where we've not a direct reference to $USER.
1971 if ($user !== $USER && $user->id == $USER->id) {
1972 $USER->preference[$name] = $value;
1975 // Set reload flag for other sessions.
1976 mark_user_preferences_changed($user->id);
1982 * Sets a whole array of preferences for the current user
1984 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1987 * @category preference
1989 * @param array $prefarray An array of key/value pairs to be set
1990 * @param stdClass|int|null $user A moodle user object or id, null means current user
1991 * @return bool Always true or exception
1993 function set_user_preferences(array $prefarray, $user = null) {
1994 foreach ($prefarray as $name => $value) {
1995 set_user_preference($name, $value, $user);
2001 * Unsets a preference completely by deleting it from the database
2003 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2006 * @category preference
2008 * @param string $name The key to unset as preference for the specified user
2009 * @param stdClass|int|null $user A moodle user object or id, null means current user
2010 * @throws coding_exception
2011 * @return bool Always true or exception
2013 function unset_user_preference($name, $user = null) {
2016 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2017 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2020 if (is_null($user)) {
2022 } else if (isset($user->id)) {
2023 // It is a valid object.
2024 } else if (is_numeric($user)) {
2025 $user = (object)array('id' => (int)$user);
2027 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2030 check_user_preferences_loaded($user);
2032 if (empty($user->id) or isguestuser($user->id)) {
2033 // No permanent storage for not-logged-in user and guest.
2034 unset($user->preference[$name]);
2039 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2041 // Delete the preference from cache.
2042 unset($user->preference[$name]);
2043 // Update the $USER in case where we've not a direct reference to $USER.
2044 if ($user !== $USER && $user->id == $USER->id) {
2045 unset($USER->preference[$name]);
2048 // Set reload flag for other sessions.
2049 mark_user_preferences_changed($user->id);
2055 * Used to fetch user preference(s)
2057 * If no arguments are supplied this function will return
2058 * all of the current user preferences as an array.
2060 * If a name is specified then this function
2061 * attempts to return that particular preference value. If
2062 * none is found, then the optional value $default is returned,
2065 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2068 * @category preference
2070 * @param string $name Name of the key to use in finding a preference value
2071 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2072 * @param stdClass|int|null $user A moodle user object or id, null means current user
2073 * @throws coding_exception
2074 * @return string|mixed|null A string containing the value of a single preference. An
2075 * array with all of the preferences or null
2077 function get_user_preferences($name = null, $default = null, $user = null) {
2080 if (is_null($name)) {
2082 } else if (is_numeric($name) or $name === '_lastloaded') {
2083 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2086 if (is_null($user)) {
2088 } else if (isset($user->id)) {
2089 // Is a valid object.
2090 } else if (is_numeric($user)) {
2091 if ($USER->id == $user) {
2094 $user = (object)array('id' => (int)$user);
2097 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2100 check_user_preferences_loaded($user);
2104 return $user->preference;
2105 } else if (isset($user->preference[$name])) {
2106 // The single string value.
2107 return $user->preference[$name];
2109 // Default value (null if not specified).
2114 // FUNCTIONS FOR HANDLING TIME.
2117 * Given Gregorian date parts in user time produce a GMT timestamp.
2121 * @param int $year The year part to create timestamp of
2122 * @param int $month The month part to create timestamp of
2123 * @param int $day The day part to create timestamp of
2124 * @param int $hour The hour part to create timestamp of
2125 * @param int $minute The minute part to create timestamp of
2126 * @param int $second The second part to create timestamp of
2127 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2128 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2129 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2130 * applied only if timezone is 99 or string.
2131 * @return int GMT timestamp
2133 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2134 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2135 $date->setDate((int)$year, (int)$month, (int)$day);
2136 $date->setTime((int)$hour, (int)$minute, (int)$second);
2138 $time = $date->getTimestamp();
2140 if ($time === false) {
2141 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2142 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2145 // Moodle BC DST stuff.
2147 $time += dst_offset_on($time, $timezone);
2155 * Format a date/time (seconds) as weeks, days, hours etc as needed
2157 * Given an amount of time in seconds, returns string
2158 * formatted nicely as years, days, hours etc as needed
2166 * @param int $totalsecs Time in seconds
2167 * @param stdClass $str Should be a time object
2168 * @return string A nicely formatted date/time string
2170 function format_time($totalsecs, $str = null) {
2172 $totalsecs = abs($totalsecs);
2175 // Create the str structure the slow way.
2176 $str = new stdClass();
2177 $str->day = get_string('day');
2178 $str->days = get_string('days');
2179 $str->hour = get_string('hour');
2180 $str->hours = get_string('hours');
2181 $str->min = get_string('min');
2182 $str->mins = get_string('mins');
2183 $str->sec = get_string('sec');
2184 $str->secs = get_string('secs');
2185 $str->year = get_string('year');
2186 $str->years = get_string('years');
2189 $years = floor($totalsecs/YEARSECS);
2190 $remainder = $totalsecs - ($years*YEARSECS);
2191 $days = floor($remainder/DAYSECS);
2192 $remainder = $totalsecs - ($days*DAYSECS);
2193 $hours = floor($remainder/HOURSECS);
2194 $remainder = $remainder - ($hours*HOURSECS);
2195 $mins = floor($remainder/MINSECS);
2196 $secs = $remainder - ($mins*MINSECS);
2198 $ss = ($secs == 1) ? $str->sec : $str->secs;
2199 $sm = ($mins == 1) ? $str->min : $str->mins;
2200 $sh = ($hours == 1) ? $str->hour : $str->hours;
2201 $sd = ($days == 1) ? $str->day : $str->days;
2202 $sy = ($years == 1) ? $str->year : $str->years;
2211 $oyears = $years .' '. $sy;
2214 $odays = $days .' '. $sd;
2217 $ohours = $hours .' '. $sh;
2220 $omins = $mins .' '. $sm;
2223 $osecs = $secs .' '. $ss;
2227 return trim($oyears .' '. $odays);
2230 return trim($odays .' '. $ohours);
2233 return trim($ohours .' '. $omins);
2236 return trim($omins .' '. $osecs);
2241 return get_string('now');
2245 * Returns a formatted string that represents a date in user time.
2249 * @param int $date the timestamp in UTC, as obtained from the database.
2250 * @param string $format strftime format. You should probably get this using
2251 * get_string('strftime...', 'langconfig');
2252 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2253 * not 99 then daylight saving will not be added.
2254 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2255 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2256 * If false then the leading zero is maintained.
2257 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2258 * @return string the formatted date/time.
2260 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2261 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2262 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2266 * Returns a html "time" tag with both the exact user date with timezone information
2267 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2271 * @param int $date the timestamp in UTC, as obtained from the database.
2272 * @param string $format strftime format. You should probably get this using
2273 * get_string('strftime...', 'langconfig');
2274 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2275 * not 99 then daylight saving will not be added.
2276 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2277 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2278 * If false then the leading zero is maintained.
2279 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2280 * @return string the formatted date/time.
2282 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2283 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2284 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2285 return $userdatestr;
2287 $machinedate = new DateTime();
2288 $machinedate->setTimestamp(intval($date));
2289 $machinedate->setTimezone(core_date::get_user_timezone_object());
2291 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2295 * Returns a formatted date ensuring it is UTF-8.
2297 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2298 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2300 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2301 * @param string $format strftime format.
2302 * @param int|float|string $tz the user timezone
2303 * @return string the formatted date/time.
2304 * @since Moodle 2.3.3
2306 function date_format_string($date, $format, $tz = 99) {
2309 $localewincharset = null;
2310 // Get the calendar type user is using.
2311 if ($CFG->ostype == 'WINDOWS') {
2312 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2313 $localewincharset = $calendartype->locale_win_charset();
2316 if ($localewincharset) {
2317 $format = core_text::convert($format, 'utf-8', $localewincharset);
2320 date_default_timezone_set(core_date::get_user_timezone($tz));
2321 $datestring = strftime($format, $date);
2322 core_date::set_default_server_timezone();
2324 if ($localewincharset) {
2325 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2332 * Given a $time timestamp in GMT (seconds since epoch),
2333 * returns an array that represents the Gregorian date in user time
2337 * @param int $time Timestamp in GMT
2338 * @param float|int|string $timezone user timezone
2339 * @return array An array that represents the date in user time
2341 function usergetdate($time, $timezone=99) {
2342 date_default_timezone_set(core_date::get_user_timezone($timezone));
2343 $result = getdate($time);
2344 core_date::set_default_server_timezone();
2350 * Given a GMT timestamp (seconds since epoch), offsets it by
2351 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2353 * NOTE: this function does not include DST properly,
2354 * you should use the PHP date stuff instead!
2358 * @param int $date Timestamp in GMT
2359 * @param float|int|string $timezone user timezone
2362 function usertime($date, $timezone=99) {
2363 $userdate = new DateTime('@' . $date);
2364 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2365 $dst = dst_offset_on($date, $timezone);
2367 return $date - $userdate->getOffset() + $dst;
2371 * Given a time, return the GMT timestamp of the most recent midnight
2372 * for the current user.
2376 * @param int $date Timestamp in GMT
2377 * @param float|int|string $timezone user timezone
2378 * @return int Returns a GMT timestamp
2380 function usergetmidnight($date, $timezone=99) {
2382 $userdate = usergetdate($date, $timezone);
2384 // Time of midnight of this user's day, in GMT.
2385 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2390 * Returns a string that prints the user's timezone
2394 * @param float|int|string $timezone user timezone
2397 function usertimezone($timezone=99) {
2398 $tz = core_date::get_user_timezone($timezone);
2399 return core_date::get_localised_timezone($tz);
2403 * Returns a float or a string which denotes the user's timezone
2404 * 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)
2405 * means that for this timezone there are also DST rules to be taken into account
2406 * Checks various settings and picks the most dominant of those which have a value
2410 * @param float|int|string $tz timezone to calculate GMT time offset before
2411 * calculating user timezone, 99 is default user timezone
2412 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2413 * @return float|string
2415 function get_user_timezone($tz = 99) {
2420 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2421 isset($USER->timezone) ? $USER->timezone : 99,
2422 isset($CFG->timezone) ? $CFG->timezone : 99,
2427 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2428 foreach ($timezones as $nextvalue) {
2429 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2433 return is_numeric($tz) ? (float) $tz : $tz;
2437 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2438 * - Note: Daylight saving only works for string timezones and not for float.
2442 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2443 * @param int|float|string $strtimezone user timezone
2446 function dst_offset_on($time, $strtimezone = null) {
2447 $tz = core_date::get_user_timezone($strtimezone);
2448 $date = new DateTime('@' . $time);
2449 $date->setTimezone(new DateTimeZone($tz));
2450 if ($date->format('I') == '1') {
2451 if ($tz === 'Australia/Lord_Howe') {
2460 * Calculates when the day appears in specific month
2464 * @param int $startday starting day of the month
2465 * @param int $weekday The day when week starts (normally taken from user preferences)
2466 * @param int $month The month whose day is sought
2467 * @param int $year The year of the month whose day is sought
2470 function find_day_in_month($startday, $weekday, $month, $year) {
2471 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2473 $daysinmonth = days_in_month($month, $year);
2474 $daysinweek = count($calendartype->get_weekdays());
2476 if ($weekday == -1) {
2477 // Don't care about weekday, so return:
2478 // abs($startday) if $startday != -1
2479 // $daysinmonth otherwise.
2480 return ($startday == -1) ? $daysinmonth : abs($startday);
2483 // From now on we 're looking for a specific weekday.
2484 // Give "end of month" its actual value, since we know it.
2485 if ($startday == -1) {
2486 $startday = -1 * $daysinmonth;
2489 // Starting from day $startday, the sign is the direction.
2490 if ($startday < 1) {
2491 $startday = abs($startday);
2492 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2494 // This is the last such weekday of the month.
2495 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2496 if ($lastinmonth > $daysinmonth) {
2497 $lastinmonth -= $daysinweek;
2500 // Find the first such weekday <= $startday.
2501 while ($lastinmonth > $startday) {
2502 $lastinmonth -= $daysinweek;
2505 return $lastinmonth;
2507 $indexweekday = dayofweek($startday, $month, $year);
2509 $diff = $weekday - $indexweekday;
2511 $diff += $daysinweek;
2514 // This is the first such weekday of the month equal to or after $startday.
2515 $firstfromindex = $startday + $diff;
2517 return $firstfromindex;
2522 * Calculate the number of days in a given month
2526 * @param int $month The month whose day count is sought
2527 * @param int $year The year of the month whose day count is sought
2530 function days_in_month($month, $year) {
2531 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2532 return $calendartype->get_num_days_in_month($year, $month);
2536 * Calculate the position in the week of a specific calendar day
2540 * @param int $day The day of the date whose position in the week is sought
2541 * @param int $month The month of the date whose position in the week is sought
2542 * @param int $year The year of the date whose position in the week is sought
2545 function dayofweek($day, $month, $year) {
2546 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2547 return $calendartype->get_weekday($year, $month, $day);
2550 // USER AUTHENTICATION AND LOGIN.
2553 * Returns full login url.
2555 * Any form submissions for authentication to this URL must include username,
2556 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2558 * @return string login url
2560 function get_login_url() {
2563 return "$CFG->wwwroot/login/index.php";
2567 * This function checks that the current user is logged in and has the
2568 * required privileges
2570 * This function checks that the current user is logged in, and optionally
2571 * whether they are allowed to be in a particular course and view a particular
2573 * If they are not logged in, then it redirects them to the site login unless
2574 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2575 * case they are automatically logged in as guests.
2576 * If $courseid is given and the user is not enrolled in that course then the
2577 * user is redirected to the course enrolment page.
2578 * If $cm is given and the course module is hidden and the user is not a teacher
2579 * in the course then the user is redirected to the course home page.
2581 * When $cm parameter specified, this function sets page layout to 'module'.
2582 * You need to change it manually later if some other layout needed.
2584 * @package core_access
2587 * @param mixed $courseorid id of the course or course object
2588 * @param bool $autologinguest default true
2589 * @param object $cm course module object
2590 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2591 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2592 * in order to keep redirects working properly. MDL-14495
2593 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2594 * @return mixed Void, exit, and die depending on path
2595 * @throws coding_exception
2596 * @throws require_login_exception
2597 * @throws moodle_exception
2599 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2600 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2602 // Must not redirect when byteserving already started.
2603 if (!empty($_SERVER['HTTP_RANGE'])) {
2604 $preventredirect = true;
2608 // We cannot redirect for AJAX scripts either.
2609 $preventredirect = true;
2612 // Setup global $COURSE, themes, language and locale.
2613 if (!empty($courseorid)) {
2614 if (is_object($courseorid)) {
2615 $course = $courseorid;
2616 } else if ($courseorid == SITEID) {
2617 $course = clone($SITE);
2619 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2622 if ($cm->course != $course->id) {
2623 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2625 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2626 if (!($cm instanceof cm_info)) {
2627 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2628 // db queries so this is not really a performance concern, however it is obviously
2629 // better if you use get_fast_modinfo to get the cm before calling this.
2630 $modinfo = get_fast_modinfo($course);
2631 $cm = $modinfo->get_cm($cm->id);
2635 // Do not touch global $COURSE via $PAGE->set_course(),
2636 // the reasons is we need to be able to call require_login() at any time!!
2639 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2643 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2644 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2645 // risk leading the user back to the AJAX request URL.
2646 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2647 $setwantsurltome = false;
2650 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2651 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2652 if ($preventredirect) {
2653 throw new require_login_session_timeout_exception();
2655 if ($setwantsurltome) {
2656 $SESSION->wantsurl = qualified_me();
2658 redirect(get_login_url());
2662 // If the user is not even logged in yet then make sure they are.
2663 if (!isloggedin()) {
2664 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2665 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2666 // Misconfigured site guest, just redirect to login page.
2667 redirect(get_login_url());
2668 exit; // Never reached.
2670 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2671 complete_user_login($guest);
2672 $USER->autologinguest = true;
2673 $SESSION->lang = $lang;
2675 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2676 if ($preventredirect) {
2677 throw new require_login_exception('You are not logged in');
2680 if ($setwantsurltome) {
2681 $SESSION->wantsurl = qualified_me();
2684 $referer = get_local_referer(false);
2685 if (!empty($referer)) {
2686 $SESSION->fromurl = $referer;
2689 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2690 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2691 foreach($authsequence as $authname) {
2692 $authplugin = get_auth_plugin($authname);
2693 $authplugin->pre_loginpage_hook();
2699 // If we're still not logged in then go to the login page
2700 if (!isloggedin()) {
2701 redirect(get_login_url());
2702 exit; // Never reached.
2707 // Loginas as redirection if needed.
2708 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2709 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2710 if ($USER->loginascontext->instanceid != $course->id) {
2711 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2716 // Check whether the user should be changing password (but only if it is REALLY them).
2717 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2718 $userauth = get_auth_plugin($USER->auth);
2719 if ($userauth->can_change_password() and !$preventredirect) {
2720 if ($setwantsurltome) {
2721 $SESSION->wantsurl = qualified_me();
2723 if ($changeurl = $userauth->change_password_url()) {
2724 // Use plugin custom url.
2725 redirect($changeurl);
2727 // Use moodle internal method.
2728 redirect($CFG->wwwroot .'/login/change_password.php');
2730 } else if ($userauth->can_change_password()) {
2731 throw new moodle_exception('forcepasswordchangenotice');
2733 throw new moodle_exception('nopasswordchangeforced', 'auth');
2737 // Check that the user account is properly set up. If we can't redirect to
2738 // edit their profile and this is not a WS request, perform just the lax check.
2739 // It will allow them to use filepicker on the profile edit page.
2741 if ($preventredirect && !WS_SERVER) {
2742 $usernotfullysetup = user_not_fully_set_up($USER, false);
2744 $usernotfullysetup = user_not_fully_set_up($USER, true);
2747 if ($usernotfullysetup) {
2748 if ($preventredirect) {
2749 throw new moodle_exception('usernotfullysetup');
2751 if ($setwantsurltome) {
2752 $SESSION->wantsurl = qualified_me();
2754 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2757 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2760 if (\core\session\manager::is_loggedinas()) {
2761 // During a "logged in as" session we should force all content to be cleaned because the
2762 // logged in user will be viewing potentially malicious user generated content.
2763 // See MDL-63786 for more details.
2764 $CFG->forceclean = true;
2767 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2769 // Do not bother admins with any formalities, except for activities pending deletion.
2770 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2771 // Set the global $COURSE.
2773 $PAGE->set_cm($cm, $course);
2774 $PAGE->set_pagelayout('incourse');
2775 } else if (!empty($courseorid)) {
2776 $PAGE->set_course($course);
2778 // Set accesstime or the user will appear offline which messes up messaging.
2779 // Do not update access time for webservice or ajax requests.
2780 if (!WS_SERVER && !AJAX_SCRIPT) {
2781 user_accesstime_log($course->id);
2784 foreach ($afterlogins as $plugintype => $plugins) {
2785 foreach ($plugins as $pluginfunction) {
2786 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2792 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2793 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2794 if (!defined('NO_SITEPOLICY_CHECK')) {
2795 define('NO_SITEPOLICY_CHECK', false);
2798 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2799 // Do not test if the script explicitly asked for skipping the site policies check.
2800 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2801 $manager = new \core_privacy\local\sitepolicy\manager();
2802 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2803 if ($preventredirect) {
2804 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2806 if ($setwantsurltome) {
2807 $SESSION->wantsurl = qualified_me();
2809 redirect($policyurl);
2813 // Fetch the system context, the course context, and prefetch its child contexts.
2814 $sysctx = context_system::instance();
2815 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2817 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2822 // If the site is currently under maintenance, then print a message.
2823 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2824 if ($preventredirect) {
2825 throw new require_login_exception('Maintenance in progress');
2827 $PAGE->set_context(null);
2828 print_maintenance_message();
2831 // Make sure the course itself is not hidden.
2832 if ($course->id == SITEID) {
2833 // Frontpage can not be hidden.
2835 if (is_role_switched($course->id)) {
2836 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2838 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2839 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2840 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2841 if ($preventredirect) {
2842 throw new require_login_exception('Course is hidden');
2844 $PAGE->set_context(null);
2845 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2846 // the navigation will mess up when trying to find it.
2847 navigation_node::override_active_url(new moodle_url('/'));
2848 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2853 // Is the user enrolled?
2854 if ($course->id == SITEID) {
2855 // Everybody is enrolled on the frontpage.
2857 if (\core\session\manager::is_loggedinas()) {
2858 // Make sure the REAL person can access this course first.
2859 $realuser = \core\session\manager::get_realuser();
2860 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2861 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2862 if ($preventredirect) {
2863 throw new require_login_exception('Invalid course login-as access');
2865 $PAGE->set_context(null);
2866 echo $OUTPUT->header();
2867 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2873 if (is_role_switched($course->id)) {
2874 // Ok, user had to be inside this course before the switch.
2877 } else if (is_viewing($coursecontext, $USER)) {
2878 // Ok, no need to mess with enrol.
2882 if (isset($USER->enrol['enrolled'][$course->id])) {
2883 if ($USER->enrol['enrolled'][$course->id] > time()) {
2885 if (isset($USER->enrol['tempguest'][$course->id])) {
2886 unset($USER->enrol['tempguest'][$course->id]);
2887 remove_temp_course_roles($coursecontext);
2891 unset($USER->enrol['enrolled'][$course->id]);
2894 if (isset($USER->enrol['tempguest'][$course->id])) {
2895 if ($USER->enrol['tempguest'][$course->id] == 0) {
2897 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2901 unset($USER->enrol['tempguest'][$course->id]);
2902 remove_temp_course_roles($coursecontext);
2908 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2909 if ($until !== false) {
2910 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2912 $until = ENROL_MAX_TIMESTAMP;
2914 $USER->enrol['enrolled'][$course->id] = $until;
2917 } else if (core_course_category::can_view_course_info($course)) {
2918 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2919 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2920 $enrols = enrol_get_plugins(true);
2921 // First ask all enabled enrol instances in course if they want to auto enrol user.
2922 foreach ($instances as $instance) {
2923 if (!isset($enrols[$instance->enrol])) {
2926 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2927 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2928 if ($until !== false) {
2930 $until = ENROL_MAX_TIMESTAMP;
2932 $USER->enrol['enrolled'][$course->id] = $until;
2937 // If not enrolled yet try to gain temporary guest access.
2939 foreach ($instances as $instance) {
2940 if (!isset($enrols[$instance->enrol])) {
2943 // Get a duration for the guest access, a timestamp in the future or false.
2944 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2945 if ($until !== false and $until > time()) {
2946 $USER->enrol['tempguest'][$course->id] = $until;
2953 // User is not enrolled and is not allowed to browse courses here.
2954 if ($preventredirect) {
2955 throw new require_login_exception('Course is not available');
2957 $PAGE->set_context(null);
2958 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2959 // the navigation will mess up when trying to find it.
2960 navigation_node::override_active_url(new moodle_url('/'));
2961 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2967 if ($preventredirect) {
2968 throw new require_login_exception('Not enrolled');
2970 if ($setwantsurltome) {
2971 $SESSION->wantsurl = qualified_me();
2973 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2977 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
2978 if ($cm && $cm->deletioninprogress) {
2979 if ($preventredirect) {
2980 throw new moodle_exception('activityisscheduledfordeletion');
2982 require_once($CFG->dirroot . '/course/lib.php');
2983 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
2986 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2987 if ($cm && !$cm->uservisible) {
2988 if ($preventredirect) {
2989 throw new require_login_exception('Activity is hidden');
2991 // Get the error message that activity is not available and why (if explanation can be shown to the user).
2992 $PAGE->set_course($course);
2993 $renderer = $PAGE->get_renderer('course');
2994 $message = $renderer->course_section_cm_unavailable_error_message($cm);
2995 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
2998 // Set the global $COURSE.
3000 $PAGE->set_cm($cm, $course);
3001 $PAGE->set_pagelayout('incourse');
3002 } else if (!empty($courseorid)) {
3003 $PAGE->set_course($course);
3006 foreach ($afterlogins as $plugintype => $plugins) {
3007 foreach ($plugins as $pluginfunction) {
3008 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3012 // Finally access granted, update lastaccess times.
3013 // Do not update access time for webservice or ajax requests.
3014 if (!WS_SERVER && !AJAX_SCRIPT) {
3015 user_accesstime_log($course->id);
3021 * This function just makes sure a user is logged out.
3023 * @package core_access
3026 function require_logout() {
3029 if (!isloggedin()) {
3030 // This should not happen often, no need for hooks or events here.
3031 \core\session\manager::terminate_current();
3035 // Execute hooks before action.
3036 $authplugins = array();
3037 $authsequence = get_enabled_auth_plugins();
3038 foreach ($authsequence as $authname) {
3039 $authplugins[$authname] = get_auth_plugin($authname);
3040 $authplugins[$authname]->prelogout_hook();
3043 // Store info that gets removed during logout.
3044 $sid = session_id();
3045 $event = \core\event\user_loggedout::create(
3047 'userid' => $USER->id,
3048 'objectid' => $USER->id,
3049 'other' => array('sessionid' => $sid),
3052 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3053 $event->add_record_snapshot('sessions', $session);
3056 // Clone of $USER object to be used by auth plugins.
3057 $user = fullclone($USER);
3059 // Delete session record and drop $_SESSION content.
3060 \core\session\manager::terminate_current();
3062 // Trigger event AFTER action.
3065 // Hook to execute auth plugins redirection after event trigger.
3066 foreach ($authplugins as $authplugin) {
3067 $authplugin->postlogout_hook($user);
3072 * Weaker version of require_login()
3074 * This is a weaker version of {@link require_login()} which only requires login
3075 * when called from within a course rather than the site page, unless
3076 * the forcelogin option is turned on.
3077 * @see require_login()
3079 * @package core_access
3082 * @param mixed $courseorid The course object or id in question
3083 * @param bool $autologinguest Allow autologin guests if that is wanted
3084 * @param object $cm Course activity module if known
3085 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3086 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3087 * in order to keep redirects working properly. MDL-14495
3088 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3090 * @throws coding_exception
3092 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3093 global $CFG, $PAGE, $SITE;
3094 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3095 or (!is_object($courseorid) and $courseorid == SITEID));
3096 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3097 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3098 // db queries so this is not really a performance concern, however it is obviously
3099 // better if you use get_fast_modinfo to get the cm before calling this.
3100 if (is_object($courseorid)) {
3101 $course = $courseorid;
3103 $course = clone($SITE);
3105 $modinfo = get_fast_modinfo($course);
3106 $cm = $modinfo->get_cm($cm->id);
3108 if (!empty($CFG->forcelogin)) {
3109 // Login required for both SITE and courses.
3110 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3112 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3113 // Always login for hidden activities.
3114 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3116 } else if (isloggedin() && !isguestuser()) {
3117 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3118 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3120 } else if ($issite) {
3121 // Login for SITE not required.
3122 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3123 if (!empty($courseorid)) {
3124 if (is_object($courseorid)) {
3125 $course = $courseorid;
3127 $course = clone $SITE;
3130 if ($cm->course != $course->id) {
3131 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3133 $PAGE->set_cm($cm, $course);
3134 $PAGE->set_pagelayout('incourse');
3136 $PAGE->set_course($course);
3139 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3140 $PAGE->set_course($PAGE->course);
3142 // Do not update access time for webservice or ajax requests.
3143 if (!WS_SERVER && !AJAX_SCRIPT) {
3144 user_accesstime_log(SITEID);
3149 // Course login always required.
3150 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3155 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3157 * @param string $keyvalue the key value
3158 * @param string $script unique script identifier
3159 * @param int $instance instance id
3160 * @return stdClass the key entry in the user_private_key table
3162 * @throws moodle_exception
3164 function validate_user_key($keyvalue, $script, $instance) {
3167 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3168 print_error('invalidkey');
3171 if (!empty($key->validuntil) and $key->validuntil < time()) {
3172 print_error('expiredkey');
3175 if ($key->iprestriction) {
3176 $remoteaddr = getremoteaddr(null);
3177 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3178 print_error('ipmismatch');
3185 * Require key login. Function terminates with error if key not found or incorrect.
3187 * @uses NO_MOODLE_COOKIES
3188 * @uses PARAM_ALPHANUM
3189 * @param string $script unique script identifier
3190 * @param int $instance optional instance id
3191 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3192 * @return int Instance ID
3194 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3197 if (!NO_MOODLE_COOKIES) {
3198 print_error('sessioncookiesdisable');
3202 \core\session\manager::write_close();
3204 if (null === $keyvalue) {
3205 $keyvalue = required_param('key', PARAM_ALPHANUM);
3208 $key = validate_user_key($keyvalue, $script, $instance);
3210 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3211 print_error('invaliduserid');
3214 // Emulate normal session.
3215 enrol_check_plugins($user);
3216 \core\session\manager::set_user($user);
3218 // Note we are not using normal login.
3219 if (!defined('USER_KEY_LOGIN')) {
3220 define('USER_KEY_LOGIN', true);
3223 // Return instance id - it might be empty.
3224 return $key->instance;
3228 * Creates a new private user access key.
3230 * @param string $script unique target identifier
3231 * @param int $userid
3232 * @param int $instance optional instance id
3233 * @param string $iprestriction optional ip restricted access
3234 * @param int $validuntil key valid only until given data
3235 * @return string access key value
3237 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3240 $key = new stdClass();
3241 $key->script = $script;
3242 $key->userid = $userid;
3243 $key->instance = $instance;
3244 $key->iprestriction = $iprestriction;
3245 $key->validuntil = $validuntil;
3246 $key->timecreated = time();
3248 // Something long and unique.
3249 $key->value = md5($userid.'_'.time().random_string(40));
3250 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3252 $key->value = md5($userid.'_'.time().random_string(40));
3254 $DB->insert_record('user_private_key', $key);
3259 * Delete the user's new private user access keys for a particular script.
3261 * @param string $script unique target identifier
3262 * @param int $userid
3265 function delete_user_key($script, $userid) {
3267 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3271 * Gets a private user access key (and creates one if one doesn't exist).
3273 * @param string $script unique target identifier
3274 * @param int $userid
3275 * @param int $instance optional instance id
3276 * @param string $iprestriction optional ip restricted access
3277 * @param int $validuntil key valid only until given date
3278 * @return string access key value
3280 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3283 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3284 'instance' => $instance, 'iprestriction' => $iprestriction,
3285 'validuntil' => $validuntil))) {
3288 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3294 * Modify the user table by setting the currently logged in user's last login to now.
3296 * @return bool Always returns true
3298 function update_user_login_times() {
3301 if (isguestuser()) {
3302 // Do not update guest access times/ips for performance.
3308 $user = new stdClass();
3309 $user->id = $USER->id;
3311 // Make sure all users that logged in have some firstaccess.
3312 if ($USER->firstaccess == 0) {
3313 $USER->firstaccess = $user->firstaccess = $now;
3316 // Store the previous current as lastlogin.
3317 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3319 $USER->currentlogin = $user->currentlogin = $now;
3321 // Function user_accesstime_log() may not update immediately, better do it here.
3322 $USER->lastaccess = $user->lastaccess = $now;
3323 $USER->lastip = $user->lastip = getremoteaddr();
3325 // Note: do not call user_update_user() here because this is part of the login process,
3326 // the login event means that these fields were updated.
3327 $DB->update_record('user', $user);
3332 * Determines if a user has completed setting up their account.
3334 * The lax mode (with $strict = false) has been introduced for special cases
3335 * only where we want to skip certain checks intentionally. This is valid in
3336 * certain mnet or ajax scenarios when the user cannot / should not be
3337 * redirected to edit their profile. In most cases, you should perform the
3340 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3341 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3344 function user_not_fully_set_up($user, $strict = true) {
3346 require_once($CFG->dirroot.'/user/profile/lib.php');
3348 if (isguestuser($user)) {
3352 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3357 if (empty($user->id)) {
3358 // Strict mode can be used with existing accounts only.
3361 if (!profile_has_required_custom_fields_set($user->id)) {
3370 * Check whether the user has exceeded the bounce threshold
3372 * @param stdClass $user A {@link $USER} object
3373 * @return bool true => User has exceeded bounce threshold
3375 function over_bounce_threshold($user) {
3378 if (empty($CFG->handlebounces)) {
3382 if (empty($user->id)) {
3383 // No real (DB) user, nothing to do here.
3387 // Set sensible defaults.
3388 if (empty($CFG->minbounces)) {
3389 $CFG->minbounces = 10;
3391 if (empty($CFG->bounceratio)) {
3392 $CFG->bounceratio = .20;
3396 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3397 $bouncecount = $bounce->value;
3399 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3400 $sendcount = $send->value;
3402 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3406 * Used to increment or reset email sent count
3408 * @param stdClass $user object containing an id
3409 * @param bool $reset will reset the count to 0
3412 function set_send_count($user, $reset=false) {
3415 if (empty($user->id)) {
3416 // No real (DB) user, nothing to do here.
3420 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3421 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3422 $DB->update_record('user_preferences', $pref);
3423 } else if (!empty($reset)) {
3424 // If it's not there and we're resetting, don't bother. Make a new one.
3425 $pref = new stdClass();
3426 $pref->name = 'email_send_count';
3428 $pref->userid = $user->id;
3429 $DB->insert_record('user_preferences', $pref, false);
3434 * Increment or reset user's email bounce count
3436 * @param stdClass $user object containing an id
3437 * @param bool $reset will reset the count to 0
3439 function set_bounce_count($user, $reset=false) {
3442 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3443 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3444 $DB->update_record('user_preferences', $pref);
3445 } else if (!empty($reset)) {
3446 // If it's not there and we're resetting, don't bother. Make a new one.
3447 $pref = new stdClass();
3448 $pref->name = 'email_bounce_count';
3450 $pref->userid = $user->id;
3451 $DB->insert_record('user_preferences', $pref, false);
3456 * Determines if the logged in user is currently moving an activity
3458 * @param int $courseid The id of the course being tested
3461 function ismoving($courseid) {
3464 if (!empty($USER->activitycopy)) {
3465 return ($USER->activitycopycourse == $courseid);
3471 * Returns a persons full name
3473 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3474 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3477 * @param stdClass $user A {@link $USER} object to get full name of.
3478 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3481 function fullname($user, $override=false) {
3482 global $CFG, $SESSION;
3484 if (!isset($user->firstname) and !isset($user->lastname)) {
3488 // Get all of the name fields.
3489 $allnames = get_all_user_name_fields();
3490 if ($CFG->debugdeveloper) {
3491 foreach ($allnames as $allname) {
3492 if (!property_exists($user, $allname)) {
3493 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3494 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3495 // Message has been sent, no point in sending the message multiple times.
3502 if (!empty($CFG->forcefirstname)) {
3503 $user->firstname = $CFG->forcefirstname;
3505 if (!empty($CFG->forcelastname)) {
3506 $user->lastname = $CFG->forcelastname;
3510 if (!empty($SESSION->fullnamedisplay)) {
3511 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3515 // If the fullnamedisplay setting is available, set the template to that.
3516 if (isset($CFG->fullnamedisplay)) {
3517 $template = $CFG->fullnamedisplay;
3519 // If the template is empty, or set to language, return the language string.
3520 if ((empty($template) || $template == 'language') && !$override) {
3521 return get_string('fullnamedisplay', null, $user);
3524 // Check to see if we are displaying according to the alternative full name format.
3526 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3527 // Default to show just the user names according to the fullnamedisplay string.
3528 return get_string('fullnamedisplay', null, $user);
3530 // If the override is true, then change the template to use the complete name.
3531 $template = $CFG->alternativefullnameformat;
3535 $requirednames = array();
3536 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3537 foreach ($allnames as $allname) {
3538 if (strpos($template, $allname) !== false) {
3539 $requirednames[] = $allname;
3543 $displayname = $template;
3544 // Switch in the actual data into the template.
3545 foreach ($requirednames as $altname) {
3546 if (isset($user->$altname)) {
3547 // Using empty() on the below if statement causes breakages.
3548 if ((string)$user->$altname == '') {
3549 $displayname = str_replace($altname, 'EMPTY', $displayname);
3551 $displayname = str_replace($altname, $user->$altname, $displayname);
3554 $displayname = str_replace($altname, 'EMPTY', $displayname);
3557 // Tidy up any misc. characters (Not perfect, but gets most characters).
3558 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3559 // katakana and parenthesis.
3560 $patterns = array();
3561 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3562 // filled in by a user.
3563 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3564 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3565 // This regular expression is to remove any double spaces in the display name.
3566 $patterns[] = '/\s{2,}/u';
3567 foreach ($patterns as $pattern) {
3568 $displayname = preg_replace($pattern, ' ', $displayname);
3571 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3572 $displayname = trim($displayname);
3573 if (empty($displayname)) {
3574 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3575 // people in general feel is a good setting to fall back on.
3576 $displayname = $user->firstname;
3578 return $displayname;
3582 * A centralised location for the all name fields. Returns an array / sql string snippet.
3584 * @param bool $returnsql True for an sql select field snippet.
3585 * @param string $tableprefix table query prefix to use in front of each field.
3586 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3587 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3588 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3589 * @return array|string All name fields.
3591 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3592 // This array is provided in this order because when called by fullname() (above) if firstname is before
3593 // firstnamephonetic str_replace() will change the wrong placeholder.
3594 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3595 'lastnamephonetic' => 'lastnamephonetic',
3596 'middlename' => 'middlename',
3597 'alternatename' => 'alternatename',
3598 'firstname' => 'firstname',
3599 'lastname' => 'lastname');
3601 // Let's add a prefix to the array of user name fields if provided.
3603 foreach ($alternatenames as $key => $altname) {
3604 $alternatenames[$key] = $prefix . $altname;
3608 // If we want the end result to have firstname and lastname at the front / top of the result.
3610 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3611 for ($i = 0; $i < 2; $i++) {
3612 // Get the last element.
3613 $lastelement = end($alternatenames);
3614 // Remove it from the array.
3615 unset($alternatenames[$lastelement]);
3616 // Put the element back on the top of the array.
3617 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3621 // Create an sql field snippet if requested.
3625 foreach ($alternatenames as $key => $altname) {
3626 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3629 foreach ($alternatenames as $key => $altname) {
3630 $alternatenames[$key] = $tableprefix . '.' . $altname;
3634 $alternatenames = implode(',', $alternatenames);
3636 return $alternatenames;
3640 * Reduces lines of duplicated code for getting user name fields.
3642 * See also {@link user_picture::unalias()}
3644 * @param object $addtoobject Object to ad