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 * Use PARAM_LOCALISEDFLOAT instead.
142 define('PARAM_FLOAT', 'float');
145 * PARAM_LOCALISEDFLOAT - a localised real/floating point number.
146 * This is preferred over PARAM_FLOAT for numbers typed in by the user.
147 * Cleans localised numbers to computer readable numbers; false for invalid numbers.
149 define('PARAM_LOCALISEDFLOAT', 'localisedfloat');
152 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
154 define('PARAM_HOST', 'host');
157 * PARAM_INT - integers only, use when expecting only numbers.
159 define('PARAM_INT', 'int');
162 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
164 define('PARAM_LANG', 'lang');
167 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
168 * others! Implies PARAM_URL!)
170 define('PARAM_LOCALURL', 'localurl');
173 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
175 define('PARAM_NOTAGS', 'notags');
178 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
179 * traversals note: the leading slash is not removed, window drive letter is not allowed
181 define('PARAM_PATH', 'path');
184 * PARAM_PEM - Privacy Enhanced Mail format
186 define('PARAM_PEM', 'pem');
189 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
191 define('PARAM_PERMISSION', 'permission');
194 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
196 define('PARAM_RAW', 'raw');
199 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
201 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
204 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
206 define('PARAM_SAFEDIR', 'safedir');
209 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
211 define('PARAM_SAFEPATH', 'safepath');
214 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
216 define('PARAM_SEQUENCE', 'sequence');
219 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
221 define('PARAM_TAG', 'tag');
224 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
226 define('PARAM_TAGLIST', 'taglist');
229 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
231 define('PARAM_TEXT', 'text');
234 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
236 define('PARAM_THEME', 'theme');
239 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
240 * http://localhost.localdomain/ is ok.
242 define('PARAM_URL', 'url');
245 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
246 * accounts, do NOT use when syncing with external systems!!
248 define('PARAM_USERNAME', 'username');
251 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
253 define('PARAM_STRINGID', 'stringid');
255 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
257 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
258 * It was one of the first types, that is why it is abused so much ;-)
259 * @deprecated since 2.0
261 define('PARAM_CLEAN', 'clean');
264 * PARAM_INTEGER - deprecated alias for PARAM_INT
265 * @deprecated since 2.0
267 define('PARAM_INTEGER', 'int');
270 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
271 * @deprecated since 2.0
273 define('PARAM_NUMBER', 'float');
276 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
277 * NOTE: originally alias for PARAM_APLHA
278 * @deprecated since 2.0
280 define('PARAM_ACTION', 'alphanumext');
283 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
284 * NOTE: originally alias for PARAM_APLHA
285 * @deprecated since 2.0
287 define('PARAM_FORMAT', 'alphanumext');
290 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
291 * @deprecated since 2.0
293 define('PARAM_MULTILANG', 'text');
296 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
297 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
298 * America/Port-au-Prince)
300 define('PARAM_TIMEZONE', 'timezone');
303 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
305 define('PARAM_CLEANFILE', 'file');
308 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
309 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
310 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
311 * NOTE: numbers and underscores are strongly discouraged in plugin names!
313 define('PARAM_COMPONENT', 'component');
316 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
317 * It is usually used together with context id and component.
318 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
320 define('PARAM_AREA', 'area');
323 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
324 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
325 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
327 define('PARAM_PLUGIN', 'plugin');
333 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
335 define('VALUE_REQUIRED', 1);
338 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
340 define('VALUE_OPTIONAL', 2);
343 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
345 define('VALUE_DEFAULT', 0);
348 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
350 define('NULL_NOT_ALLOWED', false);
353 * NULL_ALLOWED - the parameter can be set to null in the database
355 define('NULL_ALLOWED', true);
360 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
362 define('PAGE_COURSE_VIEW', 'course-view');
364 /** Get remote addr constant */
365 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
366 /** Get remote addr constant */
367 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
369 // Blog access level constant declaration.
370 define ('BLOG_USER_LEVEL', 1);
371 define ('BLOG_GROUP_LEVEL', 2);
372 define ('BLOG_COURSE_LEVEL', 3);
373 define ('BLOG_SITE_LEVEL', 4);
374 define ('BLOG_GLOBAL_LEVEL', 5);
379 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
380 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
381 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
383 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
385 define('TAG_MAX_LENGTH', 50);
387 // Password policy constants.
388 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
389 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
390 define ('PASSWORD_DIGITS', '0123456789');
391 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
393 // Feature constants.
394 // Used for plugin_supports() to report features that are, or are not, supported by a module.
396 /** True if module can provide a grade */
397 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
398 /** True if module supports outcomes */
399 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
400 /** True if module supports advanced grading methods */
401 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
402 /** True if module controls the grade visibility over the gradebook */
403 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
404 /** True if module supports plagiarism plugins */
405 define('FEATURE_PLAGIARISM', 'plagiarism');
407 /** True if module has code to track whether somebody viewed it */
408 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
409 /** True if module has custom completion rules */
410 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
412 /** True if module has no 'view' page (like label) */
413 define('FEATURE_NO_VIEW_LINK', 'viewlink');
414 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
415 define('FEATURE_IDNUMBER', 'idnumber');
416 /** True if module supports groups */
417 define('FEATURE_GROUPS', 'groups');
418 /** True if module supports groupings */
419 define('FEATURE_GROUPINGS', 'groupings');
421 * True if module supports groupmembersonly (which no longer exists)
422 * @deprecated Since Moodle 2.8
424 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
426 /** Type of module */
427 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
428 /** True if module supports intro editor */
429 define('FEATURE_MOD_INTRO', 'mod_intro');
430 /** True if module has default completion */
431 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
433 define('FEATURE_COMMENT', 'comment');
435 define('FEATURE_RATE', 'rate');
436 /** True if module supports backup/restore of moodle2 format */
437 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
439 /** True if module can show description on course main page */
440 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
442 /** True if module uses the question bank */
443 define('FEATURE_USES_QUESTIONS', 'usesquestions');
446 * Maximum filename char size
448 define('MAX_FILENAME_SIZE', 100);
450 /** Unspecified module archetype */
451 define('MOD_ARCHETYPE_OTHER', 0);
452 /** Resource-like type module */
453 define('MOD_ARCHETYPE_RESOURCE', 1);
454 /** Assignment module archetype */
455 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
456 /** System (not user-addable) module archetype */
457 define('MOD_ARCHETYPE_SYSTEM', 3);
460 * Security token used for allowing access
461 * from external application such as web services.
462 * Scripts do not use any session, performance is relatively
463 * low because we need to load access info in each request.
464 * Scripts are executed in parallel.
466 define('EXTERNAL_TOKEN_PERMANENT', 0);
469 * Security token used for allowing access
470 * of embedded applications, the code is executed in the
471 * active user session. Token is invalidated after user logs out.
472 * Scripts are executed serially - normal session locking is used.
474 define('EXTERNAL_TOKEN_EMBEDDED', 1);
477 * The home page should be the site home
479 define('HOMEPAGE_SITE', 0);
481 * The home page should be the users my page
483 define('HOMEPAGE_MY', 1);
485 * The home page can be chosen by the user
487 define('HOMEPAGE_USER', 2);
490 * Hub directory url (should be moodle.org)
492 define('HUB_HUBDIRECTORYURL', "https://hubdirectory.moodle.org");
496 * Moodle.net url (should be moodle.net)
498 define('HUB_MOODLEORGHUBURL', "https://moodle.net");
499 define('HUB_OLDMOODLEORGHUBURL', "http://hub.moodle.org");
502 * Moodle mobile app service name
504 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
507 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
509 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
512 * Course display settings: display all sections on one page.
514 define('COURSE_DISPLAY_SINGLEPAGE', 0);
516 * Course display settings: split pages into a page per section.
518 define('COURSE_DISPLAY_MULTIPAGE', 1);
521 * Authentication constant: String used in password field when password is not stored.
523 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
526 * Email from header to never include via information.
528 define('EMAIL_VIA_NEVER', 0);
531 * Email from header to always include via information.
533 define('EMAIL_VIA_ALWAYS', 1);
536 * Email from header to only include via information if the address is no-reply.
538 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
540 // PARAMETER HANDLING.
543 * Returns a particular value for the named variable, taken from
544 * POST or GET. If the parameter doesn't exist then an error is
545 * thrown because we require this variable.
547 * This function should be used to initialise all required values
548 * in a script that are based on parameters. Usually it will be
550 * $id = required_param('id', PARAM_INT);
552 * Please note the $type parameter is now required and the value can not be array.
554 * @param string $parname the name of the page parameter we want
555 * @param string $type expected type of parameter
557 * @throws coding_exception
559 function required_param($parname, $type) {
560 if (func_num_args() != 2 or empty($parname) or empty($type)) {
561 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
563 // POST has precedence.
564 if (isset($_POST[$parname])) {
565 $param = $_POST[$parname];
566 } else if (isset($_GET[$parname])) {
567 $param = $_GET[$parname];
569 print_error('missingparam', '', '', $parname);
572 if (is_array($param)) {
573 debugging('Invalid array parameter detected in required_param(): '.$parname);
574 // TODO: switch to fatal error in Moodle 2.3.
575 return required_param_array($parname, $type);
578 return clean_param($param, $type);
582 * Returns a particular array value for the named variable, taken from
583 * POST or GET. If the parameter doesn't exist then an error is
584 * thrown because we require this variable.
586 * This function should be used to initialise all required values
587 * in a script that are based on parameters. Usually it will be
589 * $ids = required_param_array('ids', PARAM_INT);
591 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
593 * @param string $parname the name of the page parameter we want
594 * @param string $type expected type of parameter
596 * @throws coding_exception
598 function required_param_array($parname, $type) {
599 if (func_num_args() != 2 or empty($parname) or empty($type)) {
600 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
602 // POST has precedence.
603 if (isset($_POST[$parname])) {
604 $param = $_POST[$parname];
605 } else if (isset($_GET[$parname])) {
606 $param = $_GET[$parname];
608 print_error('missingparam', '', '', $parname);
610 if (!is_array($param)) {
611 print_error('missingparam', '', '', $parname);
615 foreach ($param as $key => $value) {
616 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
617 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
620 $result[$key] = clean_param($value, $type);
627 * Returns a particular value for the named variable, taken from
628 * POST or GET, otherwise returning a given default.
630 * This function should be used to initialise all optional values
631 * in a script that are based on parameters. Usually it will be
633 * $name = optional_param('name', 'Fred', PARAM_TEXT);
635 * Please note the $type parameter is now required and the value can not be array.
637 * @param string $parname the name of the page parameter we want
638 * @param mixed $default the default value to return if nothing is found
639 * @param string $type expected type of parameter
641 * @throws coding_exception
643 function optional_param($parname, $default, $type) {
644 if (func_num_args() != 3 or empty($parname) or empty($type)) {
645 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
648 // POST has precedence.
649 if (isset($_POST[$parname])) {
650 $param = $_POST[$parname];
651 } else if (isset($_GET[$parname])) {
652 $param = $_GET[$parname];
657 if (is_array($param)) {
658 debugging('Invalid array parameter detected in required_param(): '.$parname);
659 // TODO: switch to $default in Moodle 2.3.
660 return optional_param_array($parname, $default, $type);
663 return clean_param($param, $type);
667 * Returns a particular array value for the named variable, taken from
668 * POST or GET, otherwise returning a given default.
670 * This function should be used to initialise all optional values
671 * in a script that are based on parameters. Usually it will be
673 * $ids = optional_param('id', array(), PARAM_INT);
675 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
677 * @param string $parname the name of the page parameter we want
678 * @param mixed $default the default value to return if nothing is found
679 * @param string $type expected type of parameter
681 * @throws coding_exception
683 function optional_param_array($parname, $default, $type) {
684 if (func_num_args() != 3 or empty($parname) or empty($type)) {
685 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
688 // POST has precedence.
689 if (isset($_POST[$parname])) {
690 $param = $_POST[$parname];
691 } else if (isset($_GET[$parname])) {
692 $param = $_GET[$parname];
696 if (!is_array($param)) {
697 debugging('optional_param_array() expects array parameters only: '.$parname);
702 foreach ($param as $key => $value) {
703 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
704 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
707 $result[$key] = clean_param($value, $type);
714 * Strict validation of parameter values, the values are only converted
715 * to requested PHP type. Internally it is using clean_param, the values
716 * before and after cleaning must be equal - otherwise
717 * an invalid_parameter_exception is thrown.
718 * Objects and classes are not accepted.
720 * @param mixed $param
721 * @param string $type PARAM_ constant
722 * @param bool $allownull are nulls valid value?
723 * @param string $debuginfo optional debug information
724 * @return mixed the $param value converted to PHP type
725 * @throws invalid_parameter_exception if $param is not of given type
727 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
728 if (is_null($param)) {
729 if ($allownull == NULL_ALLOWED) {
732 throw new invalid_parameter_exception($debuginfo);
735 if (is_array($param) or is_object($param)) {
736 throw new invalid_parameter_exception($debuginfo);
739 $cleaned = clean_param($param, $type);
741 if ($type == PARAM_FLOAT) {
742 // Do not detect precision loss here.
743 if (is_float($param) or is_int($param)) {
745 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
746 throw new invalid_parameter_exception($debuginfo);
748 } else if ((string)$param !== (string)$cleaned) {
749 // Conversion to string is usually lossless.
750 throw new invalid_parameter_exception($debuginfo);
757 * Makes sure array contains only the allowed types, this function does not validate array key names!
760 * $options = clean_param($options, PARAM_INT);
763 * @param array $param the variable array we are cleaning
764 * @param string $type expected format of param after cleaning.
765 * @param bool $recursive clean recursive arrays
767 * @throws coding_exception
769 function clean_param_array(array $param = null, $type, $recursive = false) {
770 // Convert null to empty array.
771 $param = (array)$param;
772 foreach ($param as $key => $value) {
773 if (is_array($value)) {
775 $param[$key] = clean_param_array($value, $type, true);
777 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
780 $param[$key] = clean_param($value, $type);
787 * Used by {@link optional_param()} and {@link required_param()} to
788 * clean the variables and/or cast to specific types, based on
791 * $course->format = clean_param($course->format, PARAM_ALPHA);
792 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
795 * @param mixed $param the variable we are cleaning
796 * @param string $type expected format of param after cleaning.
798 * @throws coding_exception
800 function clean_param($param, $type) {
803 if (is_array($param)) {
804 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
805 } else if (is_object($param)) {
806 if (method_exists($param, '__toString')) {
807 $param = $param->__toString();
809 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
815 // No cleaning at all.
816 $param = fix_utf8($param);
819 case PARAM_RAW_TRIMMED:
820 // No cleaning, but strip leading and trailing whitespace.
821 $param = fix_utf8($param);
825 // General HTML cleaning, try to use more specific type if possible this is deprecated!
826 // Please use more specific type instead.
827 if (is_numeric($param)) {
830 $param = fix_utf8($param);
831 // Sweep for scripts, etc.
832 return clean_text($param);
834 case PARAM_CLEANHTML:
835 // Clean html fragment.
836 $param = fix_utf8($param);
837 // Sweep for scripts, etc.
838 $param = clean_text($param, FORMAT_HTML);
842 // Convert to integer.
847 return (float)$param;
849 case PARAM_LOCALISEDFLOAT:
851 return unformat_float($param, true);
854 // Remove everything not `a-z`.
855 return preg_replace('/[^a-zA-Z]/i', '', $param);
858 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
859 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
862 // Remove everything not `a-zA-Z0-9`.
863 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
865 case PARAM_ALPHANUMEXT:
866 // Remove everything not `a-zA-Z0-9_-`.
867 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
870 // Remove everything not `0-9,`.
871 return preg_replace('/[^0-9,]/i', '', $param);
874 // Convert to 1 or 0.
875 $tempstr = strtolower($param);
876 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
878 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
881 $param = empty($param) ? 0 : 1;
887 $param = fix_utf8($param);
888 return strip_tags($param);
891 // Leave only tags needed for multilang.
892 $param = fix_utf8($param);
893 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
894 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
896 if (strpos($param, '</lang>') !== false) {
897 // Old and future mutilang syntax.
898 $param = strip_tags($param, '<lang>');
899 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
903 foreach ($matches[0] as $match) {
904 if ($match === '</lang>') {
912 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
923 } else if (strpos($param, '</span>') !== false) {
924 // Current problematic multilang syntax.
925 $param = strip_tags($param, '<span>');
926 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
930 foreach ($matches[0] as $match) {
931 if ($match === '</span>') {
939 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
951 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
952 return strip_tags($param);
954 case PARAM_COMPONENT:
955 // We do not want any guessing here, either the name is correct or not
956 // please note only normalised component names are accepted.
957 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
960 if (strpos($param, '__') !== false) {
963 if (strpos($param, 'mod_') === 0) {
964 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
965 if (substr_count($param, '_') != 1) {
973 // We do not want any guessing here, either the name is correct or not.
974 if (!is_valid_plugin_name($param)) {
980 // Remove everything not a-zA-Z0-9_- .
981 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
984 // Remove everything not a-zA-Z0-9/_- .
985 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
988 // Strip all suspicious characters from filename.
989 $param = fix_utf8($param);
990 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
991 if ($param === '.' || $param === '..') {
997 // Strip all suspicious characters from file path.
998 $param = fix_utf8($param);
999 $param = str_replace('\\', '/', $param);
1001 // Explode the path and clean each element using the PARAM_FILE rules.
1002 $breadcrumb = explode('/', $param);
1003 foreach ($breadcrumb as $key => $crumb) {
1004 if ($crumb === '.' && $key === 0) {
1005 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1007 $crumb = clean_param($crumb, PARAM_FILE);
1009 $breadcrumb[$key] = $crumb;
1011 $param = implode('/', $breadcrumb);
1013 // Remove multiple current path (./././) and multiple slashes (///).
1014 $param = preg_replace('~//+~', '/', $param);
1015 $param = preg_replace('~/(\./)+~', '/', $param);
1019 // Allow FQDN or IPv4 dotted quad.
1020 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1021 // Match ipv4 dotted quad.
1022 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1023 // Confirm values are ok.
1024 if ( $match[0] > 255
1027 || $match[4] > 255 ) {
1028 // Hmmm, what kind of dotted quad is this?
1031 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1032 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1033 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1035 // All is ok - $param is respected.
1044 $param = fix_utf8($param);
1045 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1046 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1047 // All is ok, param is respected.
1054 case PARAM_LOCALURL:
1055 // Allow http absolute, root relative and relative URLs within wwwroot.
1056 $param = clean_param($param, PARAM_URL);
1057 if (!empty($param)) {
1059 if ($param === $CFG->wwwroot) {
1061 } else if (preg_match(':^/:', $param)) {
1062 // Root-relative, ok!
1063 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1064 // Absolute, and matches our wwwroot.
1066 // Relative - let's make sure there are no tricks.
1067 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1077 $param = trim($param);
1078 // PEM formatted strings may contain letters/numbers and the symbols:
1082 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1083 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1084 list($wholething, $body) = $matches;
1085 unset($wholething, $matches);
1086 $b64 = clean_param($body, PARAM_BASE64);
1088 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1096 if (!empty($param)) {
1097 // PEM formatted strings may contain letters/numbers and the symbols
1101 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1104 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1105 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1106 // than (or equal to) 64 characters long.
1107 for ($i=0, $j=count($lines); $i < $j; $i++) {
1109 if (64 < strlen($lines[$i])) {
1115 if (64 != strlen($lines[$i])) {
1119 return implode("\n", $lines);
1125 $param = fix_utf8($param);
1126 // Please note it is not safe to use the tag name directly anywhere,
1127 // it must be processed with s(), urlencode() before embedding anywhere.
1128 // Remove some nasties.
1129 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1130 // Convert many whitespace chars into one.
1131 $param = preg_replace('/\s+/u', ' ', $param);
1132 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1136 $param = fix_utf8($param);
1137 $tags = explode(',', $param);
1139 foreach ($tags as $tag) {
1140 $res = clean_param($tag, PARAM_TAG);
1146 return implode(',', $result);
1151 case PARAM_CAPABILITY:
1152 if (get_capability_info($param)) {
1158 case PARAM_PERMISSION:
1159 $param = (int)$param;
1160 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1167 $param = clean_param($param, PARAM_PLUGIN);
1168 if (empty($param)) {
1170 } else if (exists_auth_plugin($param)) {
1177 $param = clean_param($param, PARAM_SAFEDIR);
1178 if (get_string_manager()->translation_exists($param)) {
1181 // Specified language is not installed or param malformed.
1186 $param = clean_param($param, PARAM_PLUGIN);
1187 if (empty($param)) {
1189 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1191 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1194 // Specified theme is not installed.
1198 case PARAM_USERNAME:
1199 $param = fix_utf8($param);
1200 $param = trim($param);
1201 // Convert uppercase to lowercase MDL-16919.
1202 $param = core_text::strtolower($param);
1203 if (empty($CFG->extendedusernamechars)) {
1204 $param = str_replace(" " , "", $param);
1205 // Regular expression, eliminate all chars EXCEPT:
1206 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1207 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1212 $param = fix_utf8($param);
1213 if (validate_email($param)) {
1219 case PARAM_STRINGID:
1220 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1226 case PARAM_TIMEZONE:
1227 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1228 $param = fix_utf8($param);
1229 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1230 if (preg_match($timezonepattern, $param)) {
1237 // Doh! throw error, switched parameters in optional_param or another serious problem.
1238 print_error("unknownparamtype", '', '', $type);
1243 * Whether the PARAM_* type is compatible in RTL.
1245 * Being compatible with RTL means that the data they contain can flow
1246 * from right-to-left or left-to-right without compromising the user experience.
1248 * Take URLs for example, they are not RTL compatible as they should always
1249 * flow from the left to the right. This also applies to numbers, email addresses,
1250 * configuration snippets, base64 strings, etc...
1252 * This function tries to best guess which parameters can contain localised strings.
1254 * @param string $paramtype Constant PARAM_*.
1257 function is_rtl_compatible($paramtype) {
1258 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1262 * Makes sure the data is using valid utf8, invalid characters are discarded.
1264 * Note: this function is not intended for full objects with methods and private properties.
1266 * @param mixed $value
1267 * @return mixed with proper utf-8 encoding
1269 function fix_utf8($value) {
1270 if (is_null($value) or $value === '') {
1273 } else if (is_string($value)) {
1274 if ((string)(int)$value === $value) {
1278 // No null bytes expected in our data, so let's remove it.
1279 $value = str_replace("\0", '', $value);
1281 // Note: this duplicates min_fix_utf8() intentionally.
1282 static $buggyiconv = null;
1283 if ($buggyiconv === null) {
1284 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1288 if (function_exists('mb_convert_encoding')) {
1289 $subst = mb_substitute_character();
1290 mb_substitute_character('');
1291 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1292 mb_substitute_character($subst);
1295 // Warn admins on admin/index.php page.
1300 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1305 } else if (is_array($value)) {
1306 foreach ($value as $k => $v) {
1307 $value[$k] = fix_utf8($v);
1311 } else if (is_object($value)) {
1312 // Do not modify original.
1313 $value = clone($value);
1314 foreach ($value as $k => $v) {
1315 $value->$k = fix_utf8($v);
1320 // This is some other type, no utf-8 here.
1326 * Return true if given value is integer or string with integer value
1328 * @param mixed $value String or Int
1329 * @return bool true if number, false if not
1331 function is_number($value) {
1332 if (is_int($value)) {
1334 } else if (is_string($value)) {
1335 return ((string)(int)$value) === $value;
1342 * Returns host part from url.
1344 * @param string $url full url
1345 * @return string host, null if not found
1347 function get_host_from_url($url) {
1348 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1356 * Tests whether anything was returned by text editor
1358 * This function is useful for testing whether something you got back from
1359 * the HTML editor actually contains anything. Sometimes the HTML editor
1360 * appear to be empty, but actually you get back a <br> tag or something.
1362 * @param string $string a string containing HTML.
1363 * @return boolean does the string contain any actual content - that is text,
1364 * images, objects, etc.
1366 function html_is_blank($string) {
1367 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1371 * Set a key in global configuration
1373 * Set a key/value pair in both this session's {@link $CFG} global variable
1374 * and in the 'config' database table for future sessions.
1376 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1377 * In that case it doesn't affect $CFG.
1379 * A NULL value will delete the entry.
1381 * NOTE: this function is called from lib/db/upgrade.php
1383 * @param string $name the key to set
1384 * @param string $value the value to set (without magic quotes)
1385 * @param string $plugin (optional) the plugin scope, default null
1386 * @return bool true or exception
1388 function set_config($name, $value, $plugin=null) {
1391 if (empty($plugin)) {
1392 if (!array_key_exists($name, $CFG->config_php_settings)) {
1393 // So it's defined for this invocation at least.
1394 if (is_null($value)) {
1397 // Settings from db are always strings.
1398 $CFG->$name = (string)$value;
1402 if ($DB->get_field('config', 'name', array('name' => $name))) {
1403 if ($value === null) {
1404 $DB->delete_records('config', array('name' => $name));
1406 $DB->set_field('config', 'value', $value, array('name' => $name));
1409 if ($value !== null) {
1410 $config = new stdClass();
1411 $config->name = $name;
1412 $config->value = $value;
1413 $DB->insert_record('config', $config, false);
1416 if ($name === 'siteidentifier') {
1417 cache_helper::update_site_identifier($value);
1419 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1422 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1423 if ($value===null) {
1424 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1426 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1429 if ($value !== null) {
1430 $config = new stdClass();
1431 $config->plugin = $plugin;
1432 $config->name = $name;
1433 $config->value = $value;
1434 $DB->insert_record('config_plugins', $config, false);
1437 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1444 * Get configuration values from the global config table
1445 * or the config_plugins table.
1447 * If called with one parameter, it will load all the config
1448 * variables for one plugin, and return them as an object.
1450 * If called with 2 parameters it will return a string single
1451 * value or false if the value is not found.
1453 * NOTE: this function is called from lib/db/upgrade.php
1455 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1456 * that we need only fetch it once per request.
1457 * @param string $plugin full component name
1458 * @param string $name default null
1459 * @return mixed hash-like object or single value, return false no config found
1460 * @throws dml_exception
1462 function get_config($plugin, $name = null) {
1465 static $siteidentifier = null;
1467 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1468 $forced =& $CFG->config_php_settings;
1472 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1473 $forced =& $CFG->forced_plugin_settings[$plugin];
1480 if ($siteidentifier === null) {
1482 // This may fail during installation.
1483 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1484 // install the database.
1485 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1486 } catch (dml_exception $ex) {
1487 // Set siteidentifier to false. We don't want to trip this continually.
1488 $siteidentifier = false;
1493 if (!empty($name)) {
1494 if (array_key_exists($name, $forced)) {
1495 return (string)$forced[$name];
1496 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1497 return $siteidentifier;
1501 $cache = cache::make('core', 'config');
1502 $result = $cache->get($plugin);
1503 if ($result === false) {
1504 // The user is after a recordset.
1506 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1508 // This part is not really used any more, but anyway...
1509 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1511 $cache->set($plugin, $result);
1514 if (!empty($name)) {
1515 if (array_key_exists($name, $result)) {
1516 return $result[$name];
1521 if ($plugin === 'core') {
1522 $result['siteidentifier'] = $siteidentifier;
1525 foreach ($forced as $key => $value) {
1526 if (is_null($value) or is_array($value) or is_object($value)) {
1527 // We do not want any extra mess here, just real settings that could be saved in db.
1528 unset($result[$key]);
1530 // Convert to string as if it went through the DB.
1531 $result[$key] = (string)$value;
1535 return (object)$result;
1539 * Removes a key from global configuration.
1541 * NOTE: this function is called from lib/db/upgrade.php
1543 * @param string $name the key to set
1544 * @param string $plugin (optional) the plugin scope
1545 * @return boolean whether the operation succeeded.
1547 function unset_config($name, $plugin=null) {
1550 if (empty($plugin)) {
1552 $DB->delete_records('config', array('name' => $name));
1553 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1555 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1556 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1563 * Remove all the config variables for a given plugin.
1565 * NOTE: this function is called from lib/db/upgrade.php
1567 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1568 * @return boolean whether the operation succeeded.
1570 function unset_all_config_for_plugin($plugin) {
1572 // Delete from the obvious config_plugins first.
1573 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1574 // Next delete any suspect settings from config.
1575 $like = $DB->sql_like('name', '?', true, true, false, '|');
1576 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1577 $DB->delete_records_select('config', $like, $params);
1578 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1579 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1585 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1587 * All users are verified if they still have the necessary capability.
1589 * @param string $value the value of the config setting.
1590 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1591 * @param bool $includeadmins include administrators.
1592 * @return array of user objects.
1594 function get_users_from_config($value, $capability, $includeadmins = true) {
1595 if (empty($value) or $value === '$@NONE@$') {
1599 // We have to make sure that users still have the necessary capability,
1600 // it should be faster to fetch them all first and then test if they are present
1601 // instead of validating them one-by-one.
1602 $users = get_users_by_capability(context_system::instance(), $capability);
1603 if ($includeadmins) {
1604 $admins = get_admins();
1605 foreach ($admins as $admin) {
1606 $users[$admin->id] = $admin;
1610 if ($value === '$@ALL@$') {
1614 $result = array(); // Result in correct order.
1615 $allowed = explode(',', $value);
1616 foreach ($allowed as $uid) {
1617 if (isset($users[$uid])) {
1618 $user = $users[$uid];
1619 $result[$user->id] = $user;
1628 * Invalidates browser caches and cached data in temp.
1632 function purge_all_caches() {
1637 * Selectively invalidate different types of cache.
1639 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1640 * areas alone or in combination.
1642 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1643 * 'muc' Purge MUC caches?
1644 * 'theme' Purge theme cache?
1645 * 'lang' Purge language string cache?
1646 * 'js' Purge javascript cache?
1647 * 'filter' Purge text filter cache?
1648 * 'other' Purge all other caches?
1650 function purge_caches($options = []) {
1651 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'filter', 'other'], false);
1652 if (empty(array_filter($options))) {
1653 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1655 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1657 if ($options['muc']) {
1658 cache_helper::purge_all();
1660 if ($options['theme']) {
1661 theme_reset_all_caches();
1663 if ($options['lang']) {
1664 get_string_manager()->reset_caches();
1666 if ($options['js']) {
1667 js_reset_all_caches();
1669 if ($options['filter']) {
1670 reset_text_filters_cache();
1672 if ($options['other']) {
1673 purge_other_caches();
1678 * Purge all non-MUC caches not otherwise purged in purge_caches.
1680 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1681 * {@link phpunit_util::reset_dataroot()}
1683 function purge_other_caches() {
1685 core_text::reset_caches();
1686 if (class_exists('core_plugin_manager')) {
1687 core_plugin_manager::reset_caches();
1690 // Bump up cacherev field for all courses.
1692 increment_revision_number('course', 'cacherev', '');
1693 } catch (moodle_exception $e) {
1694 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1697 $DB->reset_caches();
1699 // Purge all other caches: rss, simplepie, etc.
1701 remove_dir($CFG->cachedir.'', true);
1703 // Make sure cache dir is writable, throws exception if not.
1704 make_cache_directory('');
1706 // This is the only place where we purge local caches, we are only adding files there.
1707 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1708 remove_dir($CFG->localcachedir, true);
1709 set_config('localcachedirpurged', time());
1710 make_localcache_directory('', true);
1711 \core\task\manager::clear_static_caches();
1715 * Get volatile flags
1717 * @param string $type
1718 * @param int $changedsince default null
1719 * @return array records array
1721 function get_cache_flags($type, $changedsince = null) {
1724 $params = array('type' => $type, 'expiry' => time());
1725 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1726 if ($changedsince !== null) {
1727 $params['changedsince'] = $changedsince;
1728 $sqlwhere .= " AND timemodified > :changedsince";
1731 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1732 foreach ($flags as $flag) {
1733 $cf[$flag->name] = $flag->value;
1740 * Get volatile flags
1742 * @param string $type
1743 * @param string $name
1744 * @param int $changedsince default null
1745 * @return string|false The cache flag value or false
1747 function get_cache_flag($type, $name, $changedsince=null) {
1750 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1752 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1753 if ($changedsince !== null) {
1754 $params['changedsince'] = $changedsince;
1755 $sqlwhere .= " AND timemodified > :changedsince";
1758 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1762 * Set a volatile flag
1764 * @param string $type the "type" namespace for the key
1765 * @param string $name the key to set
1766 * @param string $value the value to set (without magic quotes) - null will remove the flag
1767 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1768 * @return bool Always returns true
1770 function set_cache_flag($type, $name, $value, $expiry = null) {
1773 $timemodified = time();
1774 if ($expiry === null || $expiry < $timemodified) {
1775 $expiry = $timemodified + 24 * 60 * 60;
1777 $expiry = (int)$expiry;
1780 if ($value === null) {
1781 unset_cache_flag($type, $name);
1785 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1786 // This is a potential problem in DEBUG_DEVELOPER.
1787 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1788 return true; // No need to update.
1791 $f->expiry = $expiry;
1792 $f->timemodified = $timemodified;
1793 $DB->update_record('cache_flags', $f);
1795 $f = new stdClass();
1796 $f->flagtype = $type;
1799 $f->expiry = $expiry;
1800 $f->timemodified = $timemodified;
1801 $DB->insert_record('cache_flags', $f);
1807 * Removes a single volatile flag
1809 * @param string $type the "type" namespace for the key
1810 * @param string $name the key to set
1813 function unset_cache_flag($type, $name) {
1815 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1820 * Garbage-collect volatile flags
1822 * @return bool Always returns true
1824 function gc_cache_flags() {
1826 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1830 // USER PREFERENCE API.
1833 * Refresh user preference cache. This is used most often for $USER
1834 * object that is stored in session, but it also helps with performance in cron script.
1836 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1839 * @category preference
1841 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1842 * @param int $cachelifetime Cache life time on the current page (in seconds)
1843 * @throws coding_exception
1846 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1848 // Static cache, we need to check on each page load, not only every 2 minutes.
1849 static $loadedusers = array();
1851 if (!isset($user->id)) {
1852 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1855 if (empty($user->id) or isguestuser($user->id)) {
1856 // No permanent storage for not-logged-in users and guest.
1857 if (!isset($user->preference)) {
1858 $user->preference = array();
1865 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1866 // Already loaded at least once on this page. Are we up to date?
1867 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1868 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1871 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1872 // No change since the lastcheck on this page.
1873 $user->preference['_lastloaded'] = $timenow;
1878 // OK, so we have to reload all preferences.
1879 $loadedusers[$user->id] = true;
1880 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1881 $user->preference['_lastloaded'] = $timenow;
1885 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1887 * NOTE: internal function, do not call from other code.
1891 * @param integer $userid the user whose prefs were changed.
1893 function mark_user_preferences_changed($userid) {
1896 if (empty($userid) or isguestuser($userid)) {
1897 // No cache flags for guest and not-logged-in users.
1901 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1905 * Sets a preference for the specified user.
1907 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1909 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1912 * @category preference
1914 * @param string $name The key to set as preference for the specified user
1915 * @param string $value The value to set for the $name key in the specified user's
1916 * record, null means delete current value.
1917 * @param stdClass|int|null $user A moodle user object or id, null means current user
1918 * @throws coding_exception
1919 * @return bool Always true or exception
1921 function set_user_preference($name, $value, $user = null) {
1924 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1925 throw new coding_exception('Invalid preference name in set_user_preference() call');
1928 if (is_null($value)) {
1929 // Null means delete current.
1930 return unset_user_preference($name, $user);
1931 } else if (is_object($value)) {
1932 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1933 } else if (is_array($value)) {
1934 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1936 // Value column maximum length is 1333 characters.
1937 $value = (string)$value;
1938 if (core_text::strlen($value) > 1333) {
1939 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1942 if (is_null($user)) {
1944 } else if (isset($user->id)) {
1945 // It is a valid object.
1946 } else if (is_numeric($user)) {
1947 $user = (object)array('id' => (int)$user);
1949 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1952 check_user_preferences_loaded($user);
1954 if (empty($user->id) or isguestuser($user->id)) {
1955 // No permanent storage for not-logged-in users and guest.
1956 $user->preference[$name] = $value;
1960 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1961 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1962 // Preference already set to this value.
1965 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1968 $preference = new stdClass();
1969 $preference->userid = $user->id;
1970 $preference->name = $name;
1971 $preference->value = $value;
1972 $DB->insert_record('user_preferences', $preference);
1975 // Update value in cache.
1976 $user->preference[$name] = $value;
1977 // Update the $USER in case where we've not a direct reference to $USER.
1978 if ($user !== $USER && $user->id == $USER->id) {
1979 $USER->preference[$name] = $value;
1982 // Set reload flag for other sessions.
1983 mark_user_preferences_changed($user->id);
1989 * Sets a whole array of preferences for the current user
1991 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1994 * @category preference
1996 * @param array $prefarray An array of key/value pairs to be set
1997 * @param stdClass|int|null $user A moodle user object or id, null means current user
1998 * @return bool Always true or exception
2000 function set_user_preferences(array $prefarray, $user = null) {
2001 foreach ($prefarray as $name => $value) {
2002 set_user_preference($name, $value, $user);
2008 * Unsets a preference completely by deleting it from the database
2010 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2013 * @category preference
2015 * @param string $name The key to unset as preference for the specified user
2016 * @param stdClass|int|null $user A moodle user object or id, null means current user
2017 * @throws coding_exception
2018 * @return bool Always true or exception
2020 function unset_user_preference($name, $user = null) {
2023 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2024 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2027 if (is_null($user)) {
2029 } else if (isset($user->id)) {
2030 // It is a valid object.
2031 } else if (is_numeric($user)) {
2032 $user = (object)array('id' => (int)$user);
2034 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2037 check_user_preferences_loaded($user);
2039 if (empty($user->id) or isguestuser($user->id)) {
2040 // No permanent storage for not-logged-in user and guest.
2041 unset($user->preference[$name]);
2046 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2048 // Delete the preference from cache.
2049 unset($user->preference[$name]);
2050 // Update the $USER in case where we've not a direct reference to $USER.
2051 if ($user !== $USER && $user->id == $USER->id) {
2052 unset($USER->preference[$name]);
2055 // Set reload flag for other sessions.
2056 mark_user_preferences_changed($user->id);
2062 * Used to fetch user preference(s)
2064 * If no arguments are supplied this function will return
2065 * all of the current user preferences as an array.
2067 * If a name is specified then this function
2068 * attempts to return that particular preference value. If
2069 * none is found, then the optional value $default is returned,
2072 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2075 * @category preference
2077 * @param string $name Name of the key to use in finding a preference value
2078 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2079 * @param stdClass|int|null $user A moodle user object or id, null means current user
2080 * @throws coding_exception
2081 * @return string|mixed|null A string containing the value of a single preference. An
2082 * array with all of the preferences or null
2084 function get_user_preferences($name = null, $default = null, $user = null) {
2087 if (is_null($name)) {
2089 } else if (is_numeric($name) or $name === '_lastloaded') {
2090 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2093 if (is_null($user)) {
2095 } else if (isset($user->id)) {
2096 // Is a valid object.
2097 } else if (is_numeric($user)) {
2098 if ($USER->id == $user) {
2101 $user = (object)array('id' => (int)$user);
2104 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2107 check_user_preferences_loaded($user);
2111 return $user->preference;
2112 } else if (isset($user->preference[$name])) {
2113 // The single string value.
2114 return $user->preference[$name];
2116 // Default value (null if not specified).
2121 // FUNCTIONS FOR HANDLING TIME.
2124 * Given Gregorian date parts in user time produce a GMT timestamp.
2128 * @param int $year The year part to create timestamp of
2129 * @param int $month The month part to create timestamp of
2130 * @param int $day The day part to create timestamp of
2131 * @param int $hour The hour part to create timestamp of
2132 * @param int $minute The minute part to create timestamp of
2133 * @param int $second The second part to create timestamp of
2134 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2135 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2136 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2137 * applied only if timezone is 99 or string.
2138 * @return int GMT timestamp
2140 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2141 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2142 $date->setDate((int)$year, (int)$month, (int)$day);
2143 $date->setTime((int)$hour, (int)$minute, (int)$second);
2145 $time = $date->getTimestamp();
2147 if ($time === false) {
2148 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2149 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2152 // Moodle BC DST stuff.
2154 $time += dst_offset_on($time, $timezone);
2162 * Format a date/time (seconds) as weeks, days, hours etc as needed
2164 * Given an amount of time in seconds, returns string
2165 * formatted nicely as years, days, hours etc as needed
2173 * @param int $totalsecs Time in seconds
2174 * @param stdClass $str Should be a time object
2175 * @return string A nicely formatted date/time string
2177 function format_time($totalsecs, $str = null) {
2179 $totalsecs = abs($totalsecs);
2182 // Create the str structure the slow way.
2183 $str = new stdClass();
2184 $str->day = get_string('day');
2185 $str->days = get_string('days');
2186 $str->hour = get_string('hour');
2187 $str->hours = get_string('hours');
2188 $str->min = get_string('min');
2189 $str->mins = get_string('mins');
2190 $str->sec = get_string('sec');
2191 $str->secs = get_string('secs');
2192 $str->year = get_string('year');
2193 $str->years = get_string('years');
2196 $years = floor($totalsecs/YEARSECS);
2197 $remainder = $totalsecs - ($years*YEARSECS);
2198 $days = floor($remainder/DAYSECS);
2199 $remainder = $totalsecs - ($days*DAYSECS);
2200 $hours = floor($remainder/HOURSECS);
2201 $remainder = $remainder - ($hours*HOURSECS);
2202 $mins = floor($remainder/MINSECS);
2203 $secs = $remainder - ($mins*MINSECS);
2205 $ss = ($secs == 1) ? $str->sec : $str->secs;
2206 $sm = ($mins == 1) ? $str->min : $str->mins;
2207 $sh = ($hours == 1) ? $str->hour : $str->hours;
2208 $sd = ($days == 1) ? $str->day : $str->days;
2209 $sy = ($years == 1) ? $str->year : $str->years;
2218 $oyears = $years .' '. $sy;
2221 $odays = $days .' '. $sd;
2224 $ohours = $hours .' '. $sh;
2227 $omins = $mins .' '. $sm;
2230 $osecs = $secs .' '. $ss;
2234 return trim($oyears .' '. $odays);
2237 return trim($odays .' '. $ohours);
2240 return trim($ohours .' '. $omins);
2243 return trim($omins .' '. $osecs);
2248 return get_string('now');
2252 * Returns a formatted string that represents a date in user time.
2256 * @param int $date the timestamp in UTC, as obtained from the database.
2257 * @param string $format strftime format. You should probably get this using
2258 * get_string('strftime...', 'langconfig');
2259 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2260 * not 99 then daylight saving will not be added.
2261 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2262 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2263 * If false then the leading zero is maintained.
2264 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2265 * @return string the formatted date/time.
2267 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2268 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2269 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2273 * Returns a html "time" tag with both the exact user date with timezone information
2274 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2278 * @param int $date the timestamp in UTC, as obtained from the database.
2279 * @param string $format strftime format. You should probably get this using
2280 * get_string('strftime...', 'langconfig');
2281 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2282 * not 99 then daylight saving will not be added.
2283 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2284 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2285 * If false then the leading zero is maintained.
2286 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2287 * @return string the formatted date/time.
2289 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2290 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2291 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2292 return $userdatestr;
2294 $machinedate = new DateTime();
2295 $machinedate->setTimestamp(intval($date));
2296 $machinedate->setTimezone(core_date::get_user_timezone_object());
2298 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2302 * Returns a formatted date ensuring it is UTF-8.
2304 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2305 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2307 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2308 * @param string $format strftime format.
2309 * @param int|float|string $tz the user timezone
2310 * @return string the formatted date/time.
2311 * @since Moodle 2.3.3
2313 function date_format_string($date, $format, $tz = 99) {
2316 $localewincharset = null;
2317 // Get the calendar type user is using.
2318 if ($CFG->ostype == 'WINDOWS') {
2319 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2320 $localewincharset = $calendartype->locale_win_charset();
2323 if ($localewincharset) {
2324 $format = core_text::convert($format, 'utf-8', $localewincharset);
2327 date_default_timezone_set(core_date::get_user_timezone($tz));
2328 $datestring = strftime($format, $date);
2329 core_date::set_default_server_timezone();
2331 if ($localewincharset) {
2332 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2339 * Given a $time timestamp in GMT (seconds since epoch),
2340 * returns an array that represents the Gregorian date in user time
2344 * @param int $time Timestamp in GMT
2345 * @param float|int|string $timezone user timezone
2346 * @return array An array that represents the date in user time
2348 function usergetdate($time, $timezone=99) {
2349 date_default_timezone_set(core_date::get_user_timezone($timezone));
2350 $result = getdate($time);
2351 core_date::set_default_server_timezone();
2357 * Given a GMT timestamp (seconds since epoch), offsets it by
2358 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2360 * NOTE: this function does not include DST properly,
2361 * you should use the PHP date stuff instead!
2365 * @param int $date Timestamp in GMT
2366 * @param float|int|string $timezone user timezone
2369 function usertime($date, $timezone=99) {
2370 $userdate = new DateTime('@' . $date);
2371 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2372 $dst = dst_offset_on($date, $timezone);
2374 return $date - $userdate->getOffset() + $dst;
2378 * Given a time, return the GMT timestamp of the most recent midnight
2379 * for the current user.
2383 * @param int $date Timestamp in GMT
2384 * @param float|int|string $timezone user timezone
2385 * @return int Returns a GMT timestamp
2387 function usergetmidnight($date, $timezone=99) {
2389 $userdate = usergetdate($date, $timezone);
2391 // Time of midnight of this user's day, in GMT.
2392 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2397 * Returns a string that prints the user's timezone
2401 * @param float|int|string $timezone user timezone
2404 function usertimezone($timezone=99) {
2405 $tz = core_date::get_user_timezone($timezone);
2406 return core_date::get_localised_timezone($tz);
2410 * Returns a float or a string which denotes the user's timezone
2411 * 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)
2412 * means that for this timezone there are also DST rules to be taken into account
2413 * Checks various settings and picks the most dominant of those which have a value
2417 * @param float|int|string $tz timezone to calculate GMT time offset before
2418 * calculating user timezone, 99 is default user timezone
2419 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2420 * @return float|string
2422 function get_user_timezone($tz = 99) {
2427 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2428 isset($USER->timezone) ? $USER->timezone : 99,
2429 isset($CFG->timezone) ? $CFG->timezone : 99,
2434 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2435 foreach ($timezones as $nextvalue) {
2436 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2440 return is_numeric($tz) ? (float) $tz : $tz;
2444 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2445 * - Note: Daylight saving only works for string timezones and not for float.
2449 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2450 * @param int|float|string $strtimezone user timezone
2453 function dst_offset_on($time, $strtimezone = null) {
2454 $tz = core_date::get_user_timezone($strtimezone);
2455 $date = new DateTime('@' . $time);
2456 $date->setTimezone(new DateTimeZone($tz));
2457 if ($date->format('I') == '1') {
2458 if ($tz === 'Australia/Lord_Howe') {
2467 * Calculates when the day appears in specific month
2471 * @param int $startday starting day of the month
2472 * @param int $weekday The day when week starts (normally taken from user preferences)
2473 * @param int $month The month whose day is sought
2474 * @param int $year The year of the month whose day is sought
2477 function find_day_in_month($startday, $weekday, $month, $year) {
2478 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2480 $daysinmonth = days_in_month($month, $year);
2481 $daysinweek = count($calendartype->get_weekdays());
2483 if ($weekday == -1) {
2484 // Don't care about weekday, so return:
2485 // abs($startday) if $startday != -1
2486 // $daysinmonth otherwise.
2487 return ($startday == -1) ? $daysinmonth : abs($startday);
2490 // From now on we 're looking for a specific weekday.
2491 // Give "end of month" its actual value, since we know it.
2492 if ($startday == -1) {
2493 $startday = -1 * $daysinmonth;
2496 // Starting from day $startday, the sign is the direction.
2497 if ($startday < 1) {
2498 $startday = abs($startday);
2499 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2501 // This is the last such weekday of the month.
2502 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2503 if ($lastinmonth > $daysinmonth) {
2504 $lastinmonth -= $daysinweek;
2507 // Find the first such weekday <= $startday.
2508 while ($lastinmonth > $startday) {
2509 $lastinmonth -= $daysinweek;
2512 return $lastinmonth;
2514 $indexweekday = dayofweek($startday, $month, $year);
2516 $diff = $weekday - $indexweekday;
2518 $diff += $daysinweek;
2521 // This is the first such weekday of the month equal to or after $startday.
2522 $firstfromindex = $startday + $diff;
2524 return $firstfromindex;
2529 * Calculate the number of days in a given month
2533 * @param int $month The month whose day count is sought
2534 * @param int $year The year of the month whose day count is sought
2537 function days_in_month($month, $year) {
2538 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2539 return $calendartype->get_num_days_in_month($year, $month);
2543 * Calculate the position in the week of a specific calendar day
2547 * @param int $day The day of the date whose position in the week is sought
2548 * @param int $month The month of the date whose position in the week is sought
2549 * @param int $year The year of the date whose position in the week is sought
2552 function dayofweek($day, $month, $year) {
2553 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2554 return $calendartype->get_weekday($year, $month, $day);
2557 // USER AUTHENTICATION AND LOGIN.
2560 * Returns full login url.
2562 * Any form submissions for authentication to this URL must include username,
2563 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2565 * @return string login url
2567 function get_login_url() {
2570 return "$CFG->wwwroot/login/index.php";
2574 * This function checks that the current user is logged in and has the
2575 * required privileges
2577 * This function checks that the current user is logged in, and optionally
2578 * whether they are allowed to be in a particular course and view a particular
2580 * If they are not logged in, then it redirects them to the site login unless
2581 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2582 * case they are automatically logged in as guests.
2583 * If $courseid is given and the user is not enrolled in that course then the
2584 * user is redirected to the course enrolment page.
2585 * If $cm is given and the course module is hidden and the user is not a teacher
2586 * in the course then the user is redirected to the course home page.
2588 * When $cm parameter specified, this function sets page layout to 'module'.
2589 * You need to change it manually later if some other layout needed.
2591 * @package core_access
2594 * @param mixed $courseorid id of the course or course object
2595 * @param bool $autologinguest default true
2596 * @param object $cm course module object
2597 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2598 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2599 * in order to keep redirects working properly. MDL-14495
2600 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2601 * @return mixed Void, exit, and die depending on path
2602 * @throws coding_exception
2603 * @throws require_login_exception
2604 * @throws moodle_exception
2606 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2607 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2609 // Must not redirect when byteserving already started.
2610 if (!empty($_SERVER['HTTP_RANGE'])) {
2611 $preventredirect = true;
2615 // We cannot redirect for AJAX scripts either.
2616 $preventredirect = true;
2619 // Setup global $COURSE, themes, language and locale.
2620 if (!empty($courseorid)) {
2621 if (is_object($courseorid)) {
2622 $course = $courseorid;
2623 } else if ($courseorid == SITEID) {
2624 $course = clone($SITE);
2626 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2629 if ($cm->course != $course->id) {
2630 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2632 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2633 if (!($cm instanceof cm_info)) {
2634 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2635 // db queries so this is not really a performance concern, however it is obviously
2636 // better if you use get_fast_modinfo to get the cm before calling this.
2637 $modinfo = get_fast_modinfo($course);
2638 $cm = $modinfo->get_cm($cm->id);
2642 // Do not touch global $COURSE via $PAGE->set_course(),
2643 // the reasons is we need to be able to call require_login() at any time!!
2646 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2650 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2651 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2652 // risk leading the user back to the AJAX request URL.
2653 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2654 $setwantsurltome = false;
2657 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2658 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2659 if ($preventredirect) {
2660 throw new require_login_session_timeout_exception();
2662 if ($setwantsurltome) {
2663 $SESSION->wantsurl = qualified_me();
2665 redirect(get_login_url());
2669 // If the user is not even logged in yet then make sure they are.
2670 if (!isloggedin()) {
2671 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2672 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2673 // Misconfigured site guest, just redirect to login page.
2674 redirect(get_login_url());
2675 exit; // Never reached.
2677 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2678 complete_user_login($guest);
2679 $USER->autologinguest = true;
2680 $SESSION->lang = $lang;
2682 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2683 if ($preventredirect) {
2684 throw new require_login_exception('You are not logged in');
2687 if ($setwantsurltome) {
2688 $SESSION->wantsurl = qualified_me();
2691 $referer = get_local_referer(false);
2692 if (!empty($referer)) {
2693 $SESSION->fromurl = $referer;
2696 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2697 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2698 foreach($authsequence as $authname) {
2699 $authplugin = get_auth_plugin($authname);
2700 $authplugin->pre_loginpage_hook();
2703 $modinfo = get_fast_modinfo($course);
2704 $cm = $modinfo->get_cm($cm->id);
2706 set_access_log_user();
2711 // If we're still not logged in then go to the login page
2712 if (!isloggedin()) {
2713 redirect(get_login_url());
2714 exit; // Never reached.
2719 // Loginas as redirection if needed.
2720 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2721 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2722 if ($USER->loginascontext->instanceid != $course->id) {
2723 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2728 // Check whether the user should be changing password (but only if it is REALLY them).
2729 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2730 $userauth = get_auth_plugin($USER->auth);
2731 if ($userauth->can_change_password() and !$preventredirect) {
2732 if ($setwantsurltome) {
2733 $SESSION->wantsurl = qualified_me();
2735 if ($changeurl = $userauth->change_password_url()) {
2736 // Use plugin custom url.
2737 redirect($changeurl);
2739 // Use moodle internal method.
2740 redirect($CFG->wwwroot .'/login/change_password.php');
2742 } else if ($userauth->can_change_password()) {
2743 throw new moodle_exception('forcepasswordchangenotice');
2745 throw new moodle_exception('nopasswordchangeforced', 'auth');
2749 // Check that the user account is properly set up. If we can't redirect to
2750 // edit their profile and this is not a WS request, perform just the lax check.
2751 // It will allow them to use filepicker on the profile edit page.
2753 if ($preventredirect && !WS_SERVER) {
2754 $usernotfullysetup = user_not_fully_set_up($USER, false);
2756 $usernotfullysetup = user_not_fully_set_up($USER, true);
2759 if ($usernotfullysetup) {
2760 if ($preventredirect) {
2761 throw new moodle_exception('usernotfullysetup');
2763 if ($setwantsurltome) {
2764 $SESSION->wantsurl = qualified_me();
2766 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2769 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2772 if (\core\session\manager::is_loggedinas()) {
2773 // During a "logged in as" session we should force all content to be cleaned because the
2774 // logged in user will be viewing potentially malicious user generated content.
2775 // See MDL-63786 for more details.
2776 $CFG->forceclean = true;
2779 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2781 // Do not bother admins with any formalities, except for activities pending deletion.
2782 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2783 // Set the global $COURSE.
2785 $PAGE->set_cm($cm, $course);
2786 $PAGE->set_pagelayout('incourse');
2787 } else if (!empty($courseorid)) {
2788 $PAGE->set_course($course);
2790 // Set accesstime or the user will appear offline which messes up messaging.
2791 // Do not update access time for webservice or ajax requests.
2792 if (!WS_SERVER && !AJAX_SCRIPT) {
2793 user_accesstime_log($course->id);
2796 foreach ($afterlogins as $plugintype => $plugins) {
2797 foreach ($plugins as $pluginfunction) {
2798 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2804 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2805 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2806 if (!defined('NO_SITEPOLICY_CHECK')) {
2807 define('NO_SITEPOLICY_CHECK', false);
2810 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2811 // Do not test if the script explicitly asked for skipping the site policies check.
2812 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2813 $manager = new \core_privacy\local\sitepolicy\manager();
2814 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2815 if ($preventredirect) {
2816 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2818 if ($setwantsurltome) {
2819 $SESSION->wantsurl = qualified_me();
2821 redirect($policyurl);
2825 // Fetch the system context, the course context, and prefetch its child contexts.
2826 $sysctx = context_system::instance();
2827 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2829 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2834 // If the site is currently under maintenance, then print a message.
2835 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2836 if ($preventredirect) {
2837 throw new require_login_exception('Maintenance in progress');
2839 $PAGE->set_context(null);
2840 print_maintenance_message();
2843 // Make sure the course itself is not hidden.
2844 if ($course->id == SITEID) {
2845 // Frontpage can not be hidden.
2847 if (is_role_switched($course->id)) {
2848 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2850 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2851 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2852 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2853 if ($preventredirect) {
2854 throw new require_login_exception('Course is hidden');
2856 $PAGE->set_context(null);
2857 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2858 // the navigation will mess up when trying to find it.
2859 navigation_node::override_active_url(new moodle_url('/'));
2860 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2865 // Is the user enrolled?
2866 if ($course->id == SITEID) {
2867 // Everybody is enrolled on the frontpage.
2869 if (\core\session\manager::is_loggedinas()) {
2870 // Make sure the REAL person can access this course first.
2871 $realuser = \core\session\manager::get_realuser();
2872 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2873 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2874 if ($preventredirect) {
2875 throw new require_login_exception('Invalid course login-as access');
2877 $PAGE->set_context(null);
2878 echo $OUTPUT->header();
2879 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2885 if (is_role_switched($course->id)) {
2886 // Ok, user had to be inside this course before the switch.
2889 } else if (is_viewing($coursecontext, $USER)) {
2890 // Ok, no need to mess with enrol.
2894 if (isset($USER->enrol['enrolled'][$course->id])) {
2895 if ($USER->enrol['enrolled'][$course->id] > time()) {
2897 if (isset($USER->enrol['tempguest'][$course->id])) {
2898 unset($USER->enrol['tempguest'][$course->id]);
2899 remove_temp_course_roles($coursecontext);
2903 unset($USER->enrol['enrolled'][$course->id]);
2906 if (isset($USER->enrol['tempguest'][$course->id])) {
2907 if ($USER->enrol['tempguest'][$course->id] == 0) {
2909 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2913 unset($USER->enrol['tempguest'][$course->id]);
2914 remove_temp_course_roles($coursecontext);
2920 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2921 if ($until !== false) {
2922 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2924 $until = ENROL_MAX_TIMESTAMP;
2926 $USER->enrol['enrolled'][$course->id] = $until;
2929 } else if (core_course_category::can_view_course_info($course)) {
2930 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2931 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2932 $enrols = enrol_get_plugins(true);
2933 // First ask all enabled enrol instances in course if they want to auto enrol user.
2934 foreach ($instances as $instance) {
2935 if (!isset($enrols[$instance->enrol])) {
2938 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2939 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2940 if ($until !== false) {
2942 $until = ENROL_MAX_TIMESTAMP;
2944 $USER->enrol['enrolled'][$course->id] = $until;
2949 // If not enrolled yet try to gain temporary guest access.
2951 foreach ($instances as $instance) {
2952 if (!isset($enrols[$instance->enrol])) {
2955 // Get a duration for the guest access, a timestamp in the future or false.
2956 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2957 if ($until !== false and $until > time()) {
2958 $USER->enrol['tempguest'][$course->id] = $until;
2965 // User is not enrolled and is not allowed to browse courses here.
2966 if ($preventredirect) {
2967 throw new require_login_exception('Course is not available');
2969 $PAGE->set_context(null);
2970 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2971 // the navigation will mess up when trying to find it.
2972 navigation_node::override_active_url(new moodle_url('/'));
2973 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2979 if ($preventredirect) {
2980 throw new require_login_exception('Not enrolled');
2982 if ($setwantsurltome) {
2983 $SESSION->wantsurl = qualified_me();
2985 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2989 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
2990 if ($cm && $cm->deletioninprogress) {
2991 if ($preventredirect) {
2992 throw new moodle_exception('activityisscheduledfordeletion');
2994 require_once($CFG->dirroot . '/course/lib.php');
2995 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
2998 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2999 if ($cm && !$cm->uservisible) {
3000 if ($preventredirect) {
3001 throw new require_login_exception('Activity is hidden');
3003 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3004 $PAGE->set_course($course);
3005 $renderer = $PAGE->get_renderer('course');
3006 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3007 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3010 // Set the global $COURSE.
3012 $PAGE->set_cm($cm, $course);
3013 $PAGE->set_pagelayout('incourse');
3014 } else if (!empty($courseorid)) {
3015 $PAGE->set_course($course);
3018 foreach ($afterlogins as $plugintype => $plugins) {
3019 foreach ($plugins as $pluginfunction) {
3020 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3024 // Finally access granted, update lastaccess times.
3025 // Do not update access time for webservice or ajax requests.
3026 if (!WS_SERVER && !AJAX_SCRIPT) {
3027 user_accesstime_log($course->id);
3033 * This function just makes sure a user is logged out.
3035 * @package core_access
3038 function require_logout() {
3041 if (!isloggedin()) {
3042 // This should not happen often, no need for hooks or events here.
3043 \core\session\manager::terminate_current();
3047 // Execute hooks before action.
3048 $authplugins = array();
3049 $authsequence = get_enabled_auth_plugins();
3050 foreach ($authsequence as $authname) {
3051 $authplugins[$authname] = get_auth_plugin($authname);
3052 $authplugins[$authname]->prelogout_hook();
3055 // Store info that gets removed during logout.
3056 $sid = session_id();
3057 $event = \core\event\user_loggedout::create(
3059 'userid' => $USER->id,
3060 'objectid' => $USER->id,
3061 'other' => array('sessionid' => $sid),
3064 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3065 $event->add_record_snapshot('sessions', $session);
3068 // Clone of $USER object to be used by auth plugins.
3069 $user = fullclone($USER);
3071 // Delete session record and drop $_SESSION content.
3072 \core\session\manager::terminate_current();
3074 // Trigger event AFTER action.
3077 // Hook to execute auth plugins redirection after event trigger.
3078 foreach ($authplugins as $authplugin) {
3079 $authplugin->postlogout_hook($user);
3084 * Weaker version of require_login()
3086 * This is a weaker version of {@link require_login()} which only requires login
3087 * when called from within a course rather than the site page, unless
3088 * the forcelogin option is turned on.
3089 * @see require_login()
3091 * @package core_access
3094 * @param mixed $courseorid The course object or id in question
3095 * @param bool $autologinguest Allow autologin guests if that is wanted
3096 * @param object $cm Course activity module if known
3097 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3098 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3099 * in order to keep redirects working properly. MDL-14495
3100 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3102 * @throws coding_exception
3104 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3105 global $CFG, $PAGE, $SITE;
3106 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3107 or (!is_object($courseorid) and $courseorid == SITEID));
3108 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3109 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3110 // db queries so this is not really a performance concern, however it is obviously
3111 // better if you use get_fast_modinfo to get the cm before calling this.
3112 if (is_object($courseorid)) {
3113 $course = $courseorid;
3115 $course = clone($SITE);
3117 $modinfo = get_fast_modinfo($course);
3118 $cm = $modinfo->get_cm($cm->id);
3120 if (!empty($CFG->forcelogin)) {
3121 // Login required for both SITE and courses.
3122 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3124 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3125 // Always login for hidden activities.
3126 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3128 } else if (isloggedin() && !isguestuser()) {
3129 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3130 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3132 } else if ($issite) {
3133 // Login for SITE not required.
3134 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3135 if (!empty($courseorid)) {
3136 if (is_object($courseorid)) {
3137 $course = $courseorid;
3139 $course = clone $SITE;
3142 if ($cm->course != $course->id) {
3143 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3145 $PAGE->set_cm($cm, $course);
3146 $PAGE->set_pagelayout('incourse');
3148 $PAGE->set_course($course);
3151 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3152 $PAGE->set_course($PAGE->course);
3154 // Do not update access time for webservice or ajax requests.
3155 if (!WS_SERVER && !AJAX_SCRIPT) {
3156 user_accesstime_log(SITEID);
3161 // Course login always required.
3162 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3167 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3169 * @param string $keyvalue the key value
3170 * @param string $script unique script identifier
3171 * @param int $instance instance id
3172 * @return stdClass the key entry in the user_private_key table
3174 * @throws moodle_exception
3176 function validate_user_key($keyvalue, $script, $instance) {
3179 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3180 print_error('invalidkey');
3183 if (!empty($key->validuntil) and $key->validuntil < time()) {
3184 print_error('expiredkey');
3187 if ($key->iprestriction) {
3188 $remoteaddr = getremoteaddr(null);
3189 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3190 print_error('ipmismatch');
3197 * Require key login. Function terminates with error if key not found or incorrect.
3199 * @uses NO_MOODLE_COOKIES
3200 * @uses PARAM_ALPHANUM
3201 * @param string $script unique script identifier
3202 * @param int $instance optional instance id
3203 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3204 * @return int Instance ID
3206 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3209 if (!NO_MOODLE_COOKIES) {
3210 print_error('sessioncookiesdisable');
3214 \core\session\manager::write_close();
3216 if (null === $keyvalue) {
3217 $keyvalue = required_param('key', PARAM_ALPHANUM);
3220 $key = validate_user_key($keyvalue, $script, $instance);
3222 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3223 print_error('invaliduserid');
3226 // Emulate normal session.
3227 enrol_check_plugins($user);
3228 \core\session\manager::set_user($user);
3230 // Note we are not using normal login.
3231 if (!defined('USER_KEY_LOGIN')) {
3232 define('USER_KEY_LOGIN', true);
3235 // Return instance id - it might be empty.
3236 return $key->instance;
3240 * Creates a new private user access key.
3242 * @param string $script unique target identifier
3243 * @param int $userid
3244 * @param int $instance optional instance id
3245 * @param string $iprestriction optional ip restricted access
3246 * @param int $validuntil key valid only until given data
3247 * @return string access key value
3249 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3252 $key = new stdClass();
3253 $key->script = $script;
3254 $key->userid = $userid;
3255 $key->instance = $instance;
3256 $key->iprestriction = $iprestriction;
3257 $key->validuntil = $validuntil;
3258 $key->timecreated = time();
3260 // Something long and unique.
3261 $key->value = md5($userid.'_'.time().random_string(40));
3262 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3264 $key->value = md5($userid.'_'.time().random_string(40));
3266 $DB->insert_record('user_private_key', $key);
3271 * Delete the user's new private user access keys for a particular script.
3273 * @param string $script unique target identifier
3274 * @param int $userid
3277 function delete_user_key($script, $userid) {
3279 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3283 * Gets a private user access key (and creates one if one doesn't exist).
3285 * @param string $script unique target identifier
3286 * @param int $userid
3287 * @param int $instance optional instance id
3288 * @param string $iprestriction optional ip restricted access
3289 * @param int $validuntil key valid only until given date
3290 * @return string access key value
3292 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3295 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3296 'instance' => $instance, 'iprestriction' => $iprestriction,
3297 'validuntil' => $validuntil))) {
3300 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3306 * Modify the user table by setting the currently logged in user's last login to now.
3308 * @return bool Always returns true
3310 function update_user_login_times() {
3313 if (isguestuser()) {
3314 // Do not update guest access times/ips for performance.
3320 $user = new stdClass();
3321 $user->id = $USER->id;
3323 // Make sure all users that logged in have some firstaccess.
3324 if ($USER->firstaccess == 0) {
3325 $USER->firstaccess = $user->firstaccess = $now;
3328 // Store the previous current as lastlogin.
3329 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3331 $USER->currentlogin = $user->currentlogin = $now;
3333 // Function user_accesstime_log() may not update immediately, better do it here.
3334 $USER->lastaccess = $user->lastaccess = $now;
3335 $USER->lastip = $user->lastip = getremoteaddr();
3337 // Note: do not call user_update_user() here because this is part of the login process,
3338 // the login event means that these fields were updated.
3339 $DB->update_record('user', $user);
3344 * Determines if a user has completed setting up their account.
3346 * The lax mode (with $strict = false) has been introduced for special cases
3347 * only where we want to skip certain checks intentionally. This is valid in
3348 * certain mnet or ajax scenarios when the user cannot / should not be
3349 * redirected to edit their profile. In most cases, you should perform the
3352 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3353 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3356 function user_not_fully_set_up($user, $strict = true) {
3358 require_once($CFG->dirroot.'/user/profile/lib.php');
3360 if (isguestuser($user)) {
3364 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3369 if (empty($user->id)) {
3370 // Strict mode can be used with existing accounts only.
3373 if (!profile_has_required_custom_fields_set($user->id)) {
3382 * Check whether the user has exceeded the bounce threshold
3384 * @param stdClass $user A {@link $USER} object
3385 * @return bool true => User has exceeded bounce threshold
3387 function over_bounce_threshold($user) {
3390 if (empty($CFG->handlebounces)) {
3394 if (empty($user->id)) {
3395 // No real (DB) user, nothing to do here.
3399 // Set sensible defaults.
3400 if (empty($CFG->minbounces)) {
3401 $CFG->minbounces = 10;
3403 if (empty($CFG->bounceratio)) {
3404 $CFG->bounceratio = .20;
3408 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3409 $bouncecount = $bounce->value;
3411 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3412 $sendcount = $send->value;
3414 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3418 * Used to increment or reset email sent count
3420 * @param stdClass $user object containing an id
3421 * @param bool $reset will reset the count to 0
3424 function set_send_count($user, $reset=false) {
3427 if (empty($user->id)) {
3428 // No real (DB) user, nothing to do here.
3432 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3433 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3434 $DB->update_record('user_preferences', $pref);
3435 } else if (!empty($reset)) {
3436 // If it's not there and we're resetting, don't bother. Make a new one.
3437 $pref = new stdClass();
3438 $pref->name = 'email_send_count';
3440 $pref->userid = $user->id;
3441 $DB->insert_record('user_preferences', $pref, false);
3446 * Increment or reset user's email bounce count
3448 * @param stdClass $user object containing an id
3449 * @param bool $reset will reset the count to 0
3451 function set_bounce_count($user, $reset=false) {
3454 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3455 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3456 $DB->update_record('user_preferences', $pref);
3457 } else if (!empty($reset)) {
3458 // If it's not there and we're resetting, don't bother. Make a new one.
3459 $pref = new stdClass();
3460 $pref->name = 'email_bounce_count';
3462 $pref->userid = $user->id;
3463 $DB->insert_record('user_preferences', $pref, false);
3468 * Determines if the logged in user is currently moving an activity
3470 * @param int $courseid The id of the course being tested
3473 function ismoving($courseid) {
3476 if (!empty($USER->activitycopy)) {
3477 return ($USER->activitycopycourse == $courseid);
3483 * Returns a persons full name
3485 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3486 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3489 * @param stdClass $user A {@link $USER} object to get full name of.
3490 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3493 function fullname($user, $override=false) {
3494 global $CFG, $SESSION;
3496 if (!isset($user->firstname) and !isset($user->lastname)) {
3500 // Get all of the name fields.
3501 $allnames = get_all_user_name_fields();
3502 if ($CFG->debugdeveloper) {
3503 foreach ($allnames as $allname) {
3504 if (!property_exists($user, $allname)) {
3505 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3506 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3507 // Message has been sent, no point in sending the message multiple times.
3514 if (!empty($CFG->forcefirstname)) {
3515 $user->firstname = $CFG->forcefirstname;
3517 if (!empty($CFG->forcelastname)) {
3518 $user->lastname = $CFG->forcelastname;
3522 if (!empty($SESSION->fullnamedisplay)) {
3523 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3527 // If the fullnamedisplay setting is available, set the template to that.
3528 if (isset($CFG->fullnamedisplay)) {
3529 $template = $CFG->fullnamedisplay;
3531 // If the template is empty, or set to language, return the language string.
3532 if ((empty($template) || $template == 'language') && !$override) {
3533 return get_string('fullnamedisplay', null, $user);
3536 // Check to see if we are displaying according to the alternative full name format.
3538 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3539 // Default to show just the user names according to the fullnamedisplay string.
3540 return get_string('fullnamedisplay', null, $user);
3542 // If the override is true, then change the template to use the complete name.
3543 $template = $CFG->alternativefullnameformat;
3547 $requirednames = array();
3548 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3549 foreach ($allnames as $allname) {
3550 if (strpos($template, $allname) !== false) {
3551 $requirednames[] = $allname;
3555 $displayname = $template;
3556 // Switch in the actual data into the template.
3557 foreach ($requirednames as $altname) {
3558 if (isset($user->$altname)) {
3559 // Using empty() on the below if statement causes breakages.
3560 if ((string)$user->$altname == '') {
3561 $displayname = str_replace($altname, 'EMPTY', $displayname);
3563 $displayname = str_replace($altname, $user->$altname, $displayname);
3566 $displayname = str_replace($altname, 'EMPTY', $displayname);
3569 // Tidy up any misc. characters (Not perfect, but gets most characters).
3570 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3571 // katakana and parenthesis.
3572 $patterns = array();
3573 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3574 // filled in by a user.
3575 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3576 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3577 // This regular expression is to remove any double spaces in the display name.
3578 $patterns[] = '/\s{2,}/u';
3579 foreach ($patterns as $pattern) {
3580 $displayname = preg_replace($pattern, ' ', $displayname);
3583 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3584 $displayname = trim($displayname);
3585 if (empty($displayname)) {
3586 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3587 // people in general feel is a good setting to fall back on.
3588 $displayname = $user->firstname;
3590 return $displayname;
3594 * A centralised location for the all name fields. Returns an array / sql string snippet.
3596 * @param bool $returnsql True for an sql select field snippet.
3597 * @param string $tableprefix table query prefix to use in front of each field.
3598 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3599 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3600 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3601 * @return array|string All name fields.
3603 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3604 // This array is provided in this order because when called by fullname() (above) if firstname is before
3605 // firstnamephonetic str_replace() will change the wrong placeholder.
3606 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3607 'lastnamephonetic' => 'lastnamephonetic',
3608 'middlename' => 'middlename',
3609 'alternatename' => 'alternatename',
3610 'firstname' => 'firstname',
3611 'lastname' => 'lastname');
3613 // Let's add a prefix to the array of user name fields if provided.
3615 foreach ($alternatenames as $key => $altname) {
3616 $alternatenames[$key] = $prefix . $altname;
3620 // If we want the end result to have firstname and lastname at the front / top of the result.
3622 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3623 for ($i = 0; $i < 2; $i++) {
3624 // Get the last element.
3625 $lastelement = end($alternatenames);
3626 // Remove it from the array.
3627 unset($alternatenames[$lastelement]);
3628 // Put the element back on the top of the array.
3629 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3633 // Create an sql field snippet if requested.
3637 foreach ($alternatenames as $key => $altname) {
3638 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3641 foreach ($alternatenames as $key => $altname) {
3642 $alternatenames[$key] = $tableprefix .