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 * URL of the Moodle sites registration portal.
492 defined('HUB_MOODLEORGHUBURL') || define('HUB_MOODLEORGHUBURL', 'https://stats.moodle.org');
495 * Moodle mobile app service name
497 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
500 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
502 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
505 * Course display settings: display all sections on one page.
507 define('COURSE_DISPLAY_SINGLEPAGE', 0);
509 * Course display settings: split pages into a page per section.
511 define('COURSE_DISPLAY_MULTIPAGE', 1);
514 * Authentication constant: String used in password field when password is not stored.
516 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
519 * Email from header to never include via information.
521 define('EMAIL_VIA_NEVER', 0);
524 * Email from header to always include via information.
526 define('EMAIL_VIA_ALWAYS', 1);
529 * Email from header to only include via information if the address is no-reply.
531 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
533 // PARAMETER HANDLING.
536 * Returns a particular value for the named variable, taken from
537 * POST or GET. If the parameter doesn't exist then an error is
538 * thrown because we require this variable.
540 * This function should be used to initialise all required values
541 * in a script that are based on parameters. Usually it will be
543 * $id = required_param('id', PARAM_INT);
545 * Please note the $type parameter is now required and the value can not be array.
547 * @param string $parname the name of the page parameter we want
548 * @param string $type expected type of parameter
550 * @throws coding_exception
552 function required_param($parname, $type) {
553 if (func_num_args() != 2 or empty($parname) or empty($type)) {
554 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
556 // POST has precedence.
557 if (isset($_POST[$parname])) {
558 $param = $_POST[$parname];
559 } else if (isset($_GET[$parname])) {
560 $param = $_GET[$parname];
562 print_error('missingparam', '', '', $parname);
565 if (is_array($param)) {
566 debugging('Invalid array parameter detected in required_param(): '.$parname);
567 // TODO: switch to fatal error in Moodle 2.3.
568 return required_param_array($parname, $type);
571 return clean_param($param, $type);
575 * Returns a particular array value for the named variable, taken from
576 * POST or GET. If the parameter doesn't exist then an error is
577 * thrown because we require this variable.
579 * This function should be used to initialise all required values
580 * in a script that are based on parameters. Usually it will be
582 * $ids = required_param_array('ids', PARAM_INT);
584 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
586 * @param string $parname the name of the page parameter we want
587 * @param string $type expected type of parameter
589 * @throws coding_exception
591 function required_param_array($parname, $type) {
592 if (func_num_args() != 2 or empty($parname) or empty($type)) {
593 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
595 // POST has precedence.
596 if (isset($_POST[$parname])) {
597 $param = $_POST[$parname];
598 } else if (isset($_GET[$parname])) {
599 $param = $_GET[$parname];
601 print_error('missingparam', '', '', $parname);
603 if (!is_array($param)) {
604 print_error('missingparam', '', '', $parname);
608 foreach ($param as $key => $value) {
609 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
610 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
613 $result[$key] = clean_param($value, $type);
620 * Returns a particular value for the named variable, taken from
621 * POST or GET, otherwise returning a given default.
623 * This function should be used to initialise all optional values
624 * in a script that are based on parameters. Usually it will be
626 * $name = optional_param('name', 'Fred', PARAM_TEXT);
628 * Please note the $type parameter is now required and the value can not be array.
630 * @param string $parname the name of the page parameter we want
631 * @param mixed $default the default value to return if nothing is found
632 * @param string $type expected type of parameter
634 * @throws coding_exception
636 function optional_param($parname, $default, $type) {
637 if (func_num_args() != 3 or empty($parname) or empty($type)) {
638 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
641 // POST has precedence.
642 if (isset($_POST[$parname])) {
643 $param = $_POST[$parname];
644 } else if (isset($_GET[$parname])) {
645 $param = $_GET[$parname];
650 if (is_array($param)) {
651 debugging('Invalid array parameter detected in required_param(): '.$parname);
652 // TODO: switch to $default in Moodle 2.3.
653 return optional_param_array($parname, $default, $type);
656 return clean_param($param, $type);
660 * Returns a particular array value for the named variable, taken from
661 * POST or GET, otherwise returning a given default.
663 * This function should be used to initialise all optional values
664 * in a script that are based on parameters. Usually it will be
666 * $ids = optional_param('id', array(), PARAM_INT);
668 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
670 * @param string $parname the name of the page parameter we want
671 * @param mixed $default the default value to return if nothing is found
672 * @param string $type expected type of parameter
674 * @throws coding_exception
676 function optional_param_array($parname, $default, $type) {
677 if (func_num_args() != 3 or empty($parname) or empty($type)) {
678 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
681 // POST has precedence.
682 if (isset($_POST[$parname])) {
683 $param = $_POST[$parname];
684 } else if (isset($_GET[$parname])) {
685 $param = $_GET[$parname];
689 if (!is_array($param)) {
690 debugging('optional_param_array() expects array parameters only: '.$parname);
695 foreach ($param as $key => $value) {
696 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
697 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
700 $result[$key] = clean_param($value, $type);
707 * Strict validation of parameter values, the values are only converted
708 * to requested PHP type. Internally it is using clean_param, the values
709 * before and after cleaning must be equal - otherwise
710 * an invalid_parameter_exception is thrown.
711 * Objects and classes are not accepted.
713 * @param mixed $param
714 * @param string $type PARAM_ constant
715 * @param bool $allownull are nulls valid value?
716 * @param string $debuginfo optional debug information
717 * @return mixed the $param value converted to PHP type
718 * @throws invalid_parameter_exception if $param is not of given type
720 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
721 if (is_null($param)) {
722 if ($allownull == NULL_ALLOWED) {
725 throw new invalid_parameter_exception($debuginfo);
728 if (is_array($param) or is_object($param)) {
729 throw new invalid_parameter_exception($debuginfo);
732 $cleaned = clean_param($param, $type);
734 if ($type == PARAM_FLOAT) {
735 // Do not detect precision loss here.
736 if (is_float($param) or is_int($param)) {
738 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
739 throw new invalid_parameter_exception($debuginfo);
741 } else if ((string)$param !== (string)$cleaned) {
742 // Conversion to string is usually lossless.
743 throw new invalid_parameter_exception($debuginfo);
750 * Makes sure array contains only the allowed types, this function does not validate array key names!
753 * $options = clean_param($options, PARAM_INT);
756 * @param array $param the variable array we are cleaning
757 * @param string $type expected format of param after cleaning.
758 * @param bool $recursive clean recursive arrays
760 * @throws coding_exception
762 function clean_param_array(array $param = null, $type, $recursive = false) {
763 // Convert null to empty array.
764 $param = (array)$param;
765 foreach ($param as $key => $value) {
766 if (is_array($value)) {
768 $param[$key] = clean_param_array($value, $type, true);
770 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
773 $param[$key] = clean_param($value, $type);
780 * Used by {@link optional_param()} and {@link required_param()} to
781 * clean the variables and/or cast to specific types, based on
784 * $course->format = clean_param($course->format, PARAM_ALPHA);
785 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
788 * @param mixed $param the variable we are cleaning
789 * @param string $type expected format of param after cleaning.
791 * @throws coding_exception
793 function clean_param($param, $type) {
796 if (is_array($param)) {
797 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
798 } else if (is_object($param)) {
799 if (method_exists($param, '__toString')) {
800 $param = $param->__toString();
802 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
808 // No cleaning at all.
809 $param = fix_utf8($param);
812 case PARAM_RAW_TRIMMED:
813 // No cleaning, but strip leading and trailing whitespace.
814 $param = fix_utf8($param);
818 // General HTML cleaning, try to use more specific type if possible this is deprecated!
819 // Please use more specific type instead.
820 if (is_numeric($param)) {
823 $param = fix_utf8($param);
824 // Sweep for scripts, etc.
825 return clean_text($param);
827 case PARAM_CLEANHTML:
828 // Clean html fragment.
829 $param = fix_utf8($param);
830 // Sweep for scripts, etc.
831 $param = clean_text($param, FORMAT_HTML);
835 // Convert to integer.
840 return (float)$param;
842 case PARAM_LOCALISEDFLOAT:
844 return unformat_float($param, true);
847 // Remove everything not `a-z`.
848 return preg_replace('/[^a-zA-Z]/i', '', $param);
851 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
852 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
855 // Remove everything not `a-zA-Z0-9`.
856 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
858 case PARAM_ALPHANUMEXT:
859 // Remove everything not `a-zA-Z0-9_-`.
860 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
863 // Remove everything not `0-9,`.
864 return preg_replace('/[^0-9,]/i', '', $param);
867 // Convert to 1 or 0.
868 $tempstr = strtolower($param);
869 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
871 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
874 $param = empty($param) ? 0 : 1;
880 $param = fix_utf8($param);
881 return strip_tags($param);
884 // Leave only tags needed for multilang.
885 $param = fix_utf8($param);
886 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
887 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
889 if (strpos($param, '</lang>') !== false) {
890 // Old and future mutilang syntax.
891 $param = strip_tags($param, '<lang>');
892 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
896 foreach ($matches[0] as $match) {
897 if ($match === '</lang>') {
905 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
916 } else if (strpos($param, '</span>') !== false) {
917 // Current problematic multilang syntax.
918 $param = strip_tags($param, '<span>');
919 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
923 foreach ($matches[0] as $match) {
924 if ($match === '</span>') {
932 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
944 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
945 return strip_tags($param);
947 case PARAM_COMPONENT:
948 // We do not want any guessing here, either the name is correct or not
949 // please note only normalised component names are accepted.
950 if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
953 if (strpos($param, '__') !== false) {
956 if (strpos($param, 'mod_') === 0) {
957 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
958 if (substr_count($param, '_') != 1) {
966 // We do not want any guessing here, either the name is correct or not.
967 if (!is_valid_plugin_name($param)) {
973 // Remove everything not a-zA-Z0-9_- .
974 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
977 // Remove everything not a-zA-Z0-9/_- .
978 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
981 // Strip all suspicious characters from filename.
982 $param = fix_utf8($param);
983 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
984 if ($param === '.' || $param === '..') {
990 // Strip all suspicious characters from file path.
991 $param = fix_utf8($param);
992 $param = str_replace('\\', '/', $param);
994 // Explode the path and clean each element using the PARAM_FILE rules.
995 $breadcrumb = explode('/', $param);
996 foreach ($breadcrumb as $key => $crumb) {
997 if ($crumb === '.' && $key === 0) {
998 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1000 $crumb = clean_param($crumb, PARAM_FILE);
1002 $breadcrumb[$key] = $crumb;
1004 $param = implode('/', $breadcrumb);
1006 // Remove multiple current path (./././) and multiple slashes (///).
1007 $param = preg_replace('~//+~', '/', $param);
1008 $param = preg_replace('~/(\./)+~', '/', $param);
1012 // Allow FQDN or IPv4 dotted quad.
1013 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1014 // Match ipv4 dotted quad.
1015 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1016 // Confirm values are ok.
1017 if ( $match[0] > 255
1020 || $match[4] > 255 ) {
1021 // Hmmm, what kind of dotted quad is this?
1024 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1025 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1026 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1028 // All is ok - $param is respected.
1037 $param = fix_utf8($param);
1038 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1039 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1040 // All is ok, param is respected.
1047 case PARAM_LOCALURL:
1048 // Allow http absolute, root relative and relative URLs within wwwroot.
1049 $param = clean_param($param, PARAM_URL);
1050 if (!empty($param)) {
1052 if ($param === $CFG->wwwroot) {
1054 } else if (preg_match(':^/:', $param)) {
1055 // Root-relative, ok!
1056 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1057 // Absolute, and matches our wwwroot.
1059 // Relative - let's make sure there are no tricks.
1060 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1070 $param = trim($param);
1071 // PEM formatted strings may contain letters/numbers and the symbols:
1075 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1076 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1077 list($wholething, $body) = $matches;
1078 unset($wholething, $matches);
1079 $b64 = clean_param($body, PARAM_BASE64);
1081 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1089 if (!empty($param)) {
1090 // PEM formatted strings may contain letters/numbers and the symbols
1094 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1097 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1098 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1099 // than (or equal to) 64 characters long.
1100 for ($i=0, $j=count($lines); $i < $j; $i++) {
1102 if (64 < strlen($lines[$i])) {
1108 if (64 != strlen($lines[$i])) {
1112 return implode("\n", $lines);
1118 $param = fix_utf8($param);
1119 // Please note it is not safe to use the tag name directly anywhere,
1120 // it must be processed with s(), urlencode() before embedding anywhere.
1121 // Remove some nasties.
1122 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1123 // Convert many whitespace chars into one.
1124 $param = preg_replace('/\s+/u', ' ', $param);
1125 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1129 $param = fix_utf8($param);
1130 $tags = explode(',', $param);
1132 foreach ($tags as $tag) {
1133 $res = clean_param($tag, PARAM_TAG);
1139 return implode(',', $result);
1144 case PARAM_CAPABILITY:
1145 if (get_capability_info($param)) {
1151 case PARAM_PERMISSION:
1152 $param = (int)$param;
1153 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1160 $param = clean_param($param, PARAM_PLUGIN);
1161 if (empty($param)) {
1163 } else if (exists_auth_plugin($param)) {
1170 $param = clean_param($param, PARAM_SAFEDIR);
1171 if (get_string_manager()->translation_exists($param)) {
1174 // Specified language is not installed or param malformed.
1179 $param = clean_param($param, PARAM_PLUGIN);
1180 if (empty($param)) {
1182 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1184 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1187 // Specified theme is not installed.
1191 case PARAM_USERNAME:
1192 $param = fix_utf8($param);
1193 $param = trim($param);
1194 // Convert uppercase to lowercase MDL-16919.
1195 $param = core_text::strtolower($param);
1196 if (empty($CFG->extendedusernamechars)) {
1197 $param = str_replace(" " , "", $param);
1198 // Regular expression, eliminate all chars EXCEPT:
1199 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1200 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1205 $param = fix_utf8($param);
1206 if (validate_email($param)) {
1212 case PARAM_STRINGID:
1213 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1219 case PARAM_TIMEZONE:
1220 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1221 $param = fix_utf8($param);
1222 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1223 if (preg_match($timezonepattern, $param)) {
1230 // Doh! throw error, switched parameters in optional_param or another serious problem.
1231 print_error("unknownparamtype", '', '', $type);
1236 * Whether the PARAM_* type is compatible in RTL.
1238 * Being compatible with RTL means that the data they contain can flow
1239 * from right-to-left or left-to-right without compromising the user experience.
1241 * Take URLs for example, they are not RTL compatible as they should always
1242 * flow from the left to the right. This also applies to numbers, email addresses,
1243 * configuration snippets, base64 strings, etc...
1245 * This function tries to best guess which parameters can contain localised strings.
1247 * @param string $paramtype Constant PARAM_*.
1250 function is_rtl_compatible($paramtype) {
1251 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1255 * Makes sure the data is using valid utf8, invalid characters are discarded.
1257 * Note: this function is not intended for full objects with methods and private properties.
1259 * @param mixed $value
1260 * @return mixed with proper utf-8 encoding
1262 function fix_utf8($value) {
1263 if (is_null($value) or $value === '') {
1266 } else if (is_string($value)) {
1267 if ((string)(int)$value === $value) {
1271 // No null bytes expected in our data, so let's remove it.
1272 $value = str_replace("\0", '', $value);
1274 // Note: this duplicates min_fix_utf8() intentionally.
1275 static $buggyiconv = null;
1276 if ($buggyiconv === null) {
1277 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1281 if (function_exists('mb_convert_encoding')) {
1282 $subst = mb_substitute_character();
1283 mb_substitute_character('');
1284 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1285 mb_substitute_character($subst);
1288 // Warn admins on admin/index.php page.
1293 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1298 } else if (is_array($value)) {
1299 foreach ($value as $k => $v) {
1300 $value[$k] = fix_utf8($v);
1304 } else if (is_object($value)) {
1305 // Do not modify original.
1306 $value = clone($value);
1307 foreach ($value as $k => $v) {
1308 $value->$k = fix_utf8($v);
1313 // This is some other type, no utf-8 here.
1319 * Return true if given value is integer or string with integer value
1321 * @param mixed $value String or Int
1322 * @return bool true if number, false if not
1324 function is_number($value) {
1325 if (is_int($value)) {
1327 } else if (is_string($value)) {
1328 return ((string)(int)$value) === $value;
1335 * Returns host part from url.
1337 * @param string $url full url
1338 * @return string host, null if not found
1340 function get_host_from_url($url) {
1341 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1349 * Tests whether anything was returned by text editor
1351 * This function is useful for testing whether something you got back from
1352 * the HTML editor actually contains anything. Sometimes the HTML editor
1353 * appear to be empty, but actually you get back a <br> tag or something.
1355 * @param string $string a string containing HTML.
1356 * @return boolean does the string contain any actual content - that is text,
1357 * images, objects, etc.
1359 function html_is_blank($string) {
1360 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1364 * Set a key in global configuration
1366 * Set a key/value pair in both this session's {@link $CFG} global variable
1367 * and in the 'config' database table for future sessions.
1369 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1370 * In that case it doesn't affect $CFG.
1372 * A NULL value will delete the entry.
1374 * NOTE: this function is called from lib/db/upgrade.php
1376 * @param string $name the key to set
1377 * @param string $value the value to set (without magic quotes)
1378 * @param string $plugin (optional) the plugin scope, default null
1379 * @return bool true or exception
1381 function set_config($name, $value, $plugin=null) {
1384 if (empty($plugin)) {
1385 if (!array_key_exists($name, $CFG->config_php_settings)) {
1386 // So it's defined for this invocation at least.
1387 if (is_null($value)) {
1390 // Settings from db are always strings.
1391 $CFG->$name = (string)$value;
1395 if ($DB->get_field('config', 'name', array('name' => $name))) {
1396 if ($value === null) {
1397 $DB->delete_records('config', array('name' => $name));
1399 $DB->set_field('config', 'value', $value, array('name' => $name));
1402 if ($value !== null) {
1403 $config = new stdClass();
1404 $config->name = $name;
1405 $config->value = $value;
1406 $DB->insert_record('config', $config, false);
1408 // When setting config during a Behat test (in the CLI script, not in the web browser
1409 // requests), remember which ones are set so that we can clear them later.
1410 if (defined('BEHAT_TEST')) {
1411 if (!property_exists($CFG, 'behat_cli_added_config')) {
1412 $CFG->behat_cli_added_config = [];
1414 $CFG->behat_cli_added_config[$name] = true;
1417 if ($name === 'siteidentifier') {
1418 cache_helper::update_site_identifier($value);
1420 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1423 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1424 if ($value===null) {
1425 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1427 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1430 if ($value !== null) {
1431 $config = new stdClass();
1432 $config->plugin = $plugin;
1433 $config->name = $name;
1434 $config->value = $value;
1435 $DB->insert_record('config_plugins', $config, false);
1438 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1445 * Get configuration values from the global config table
1446 * or the config_plugins table.
1448 * If called with one parameter, it will load all the config
1449 * variables for one plugin, and return them as an object.
1451 * If called with 2 parameters it will return a string single
1452 * value or false if the value is not found.
1454 * NOTE: this function is called from lib/db/upgrade.php
1456 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1457 * that we need only fetch it once per request.
1458 * @param string $plugin full component name
1459 * @param string $name default null
1460 * @return mixed hash-like object or single value, return false no config found
1461 * @throws dml_exception
1463 function get_config($plugin, $name = null) {
1466 static $siteidentifier = null;
1468 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1469 $forced =& $CFG->config_php_settings;
1473 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1474 $forced =& $CFG->forced_plugin_settings[$plugin];
1481 if ($siteidentifier === null) {
1483 // This may fail during installation.
1484 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1485 // install the database.
1486 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1487 } catch (dml_exception $ex) {
1488 // Set siteidentifier to false. We don't want to trip this continually.
1489 $siteidentifier = false;
1494 if (!empty($name)) {
1495 if (array_key_exists($name, $forced)) {
1496 return (string)$forced[$name];
1497 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1498 return $siteidentifier;
1502 $cache = cache::make('core', 'config');
1503 $result = $cache->get($plugin);
1504 if ($result === false) {
1505 // The user is after a recordset.
1507 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1509 // This part is not really used any more, but anyway...
1510 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1512 $cache->set($plugin, $result);
1515 if (!empty($name)) {
1516 if (array_key_exists($name, $result)) {
1517 return $result[$name];
1522 if ($plugin === 'core') {
1523 $result['siteidentifier'] = $siteidentifier;
1526 foreach ($forced as $key => $value) {
1527 if (is_null($value) or is_array($value) or is_object($value)) {
1528 // We do not want any extra mess here, just real settings that could be saved in db.
1529 unset($result[$key]);
1531 // Convert to string as if it went through the DB.
1532 $result[$key] = (string)$value;
1536 return (object)$result;
1540 * Removes a key from global configuration.
1542 * NOTE: this function is called from lib/db/upgrade.php
1544 * @param string $name the key to set
1545 * @param string $plugin (optional) the plugin scope
1546 * @return boolean whether the operation succeeded.
1548 function unset_config($name, $plugin=null) {
1551 if (empty($plugin)) {
1553 $DB->delete_records('config', array('name' => $name));
1554 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1556 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1557 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1564 * Remove all the config variables for a given plugin.
1566 * NOTE: this function is called from lib/db/upgrade.php
1568 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1569 * @return boolean whether the operation succeeded.
1571 function unset_all_config_for_plugin($plugin) {
1573 // Delete from the obvious config_plugins first.
1574 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1575 // Next delete any suspect settings from config.
1576 $like = $DB->sql_like('name', '?', true, true, false, '|');
1577 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1578 $DB->delete_records_select('config', $like, $params);
1579 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1580 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1586 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1588 * All users are verified if they still have the necessary capability.
1590 * @param string $value the value of the config setting.
1591 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1592 * @param bool $includeadmins include administrators.
1593 * @return array of user objects.
1595 function get_users_from_config($value, $capability, $includeadmins = true) {
1596 if (empty($value) or $value === '$@NONE@$') {
1600 // We have to make sure that users still have the necessary capability,
1601 // it should be faster to fetch them all first and then test if they are present
1602 // instead of validating them one-by-one.
1603 $users = get_users_by_capability(context_system::instance(), $capability);
1604 if ($includeadmins) {
1605 $admins = get_admins();
1606 foreach ($admins as $admin) {
1607 $users[$admin->id] = $admin;
1611 if ($value === '$@ALL@$') {
1615 $result = array(); // Result in correct order.
1616 $allowed = explode(',', $value);
1617 foreach ($allowed as $uid) {
1618 if (isset($users[$uid])) {
1619 $user = $users[$uid];
1620 $result[$user->id] = $user;
1629 * Invalidates browser caches and cached data in temp.
1633 function purge_all_caches() {
1638 * Selectively invalidate different types of cache.
1640 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1641 * areas alone or in combination.
1643 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1644 * 'muc' Purge MUC caches?
1645 * 'theme' Purge theme cache?
1646 * 'lang' Purge language string cache?
1647 * 'js' Purge javascript cache?
1648 * 'filter' Purge text filter cache?
1649 * 'other' Purge all other caches?
1651 function purge_caches($options = []) {
1652 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1653 if (empty(array_filter($options))) {
1654 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1656 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1658 if ($options['muc']) {
1659 cache_helper::purge_all();
1661 if ($options['theme']) {
1662 theme_reset_all_caches();
1664 if ($options['lang']) {
1665 get_string_manager()->reset_caches();
1667 if ($options['js']) {
1668 js_reset_all_caches();
1670 if ($options['template']) {
1671 template_reset_all_caches();
1673 if ($options['filter']) {
1674 reset_text_filters_cache();
1676 if ($options['other']) {
1677 purge_other_caches();
1682 * Purge all non-MUC caches not otherwise purged in purge_caches.
1684 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1685 * {@link phpunit_util::reset_dataroot()}
1687 function purge_other_caches() {
1689 core_text::reset_caches();
1690 if (class_exists('core_plugin_manager')) {
1691 core_plugin_manager::reset_caches();
1694 // Bump up cacherev field for all courses.
1696 increment_revision_number('course', 'cacherev', '');
1697 } catch (moodle_exception $e) {
1698 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1701 $DB->reset_caches();
1703 // Purge all other caches: rss, simplepie, etc.
1705 remove_dir($CFG->cachedir.'', true);
1707 // Make sure cache dir is writable, throws exception if not.
1708 make_cache_directory('');
1710 // This is the only place where we purge local caches, we are only adding files there.
1711 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1712 remove_dir($CFG->localcachedir, true);
1713 set_config('localcachedirpurged', time());
1714 make_localcache_directory('', true);
1715 \core\task\manager::clear_static_caches();
1719 * Get volatile flags
1721 * @param string $type
1722 * @param int $changedsince default null
1723 * @return array records array
1725 function get_cache_flags($type, $changedsince = null) {
1728 $params = array('type' => $type, 'expiry' => time());
1729 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1730 if ($changedsince !== null) {
1731 $params['changedsince'] = $changedsince;
1732 $sqlwhere .= " AND timemodified > :changedsince";
1735 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1736 foreach ($flags as $flag) {
1737 $cf[$flag->name] = $flag->value;
1744 * Get volatile flags
1746 * @param string $type
1747 * @param string $name
1748 * @param int $changedsince default null
1749 * @return string|false The cache flag value or false
1751 function get_cache_flag($type, $name, $changedsince=null) {
1754 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1756 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1757 if ($changedsince !== null) {
1758 $params['changedsince'] = $changedsince;
1759 $sqlwhere .= " AND timemodified > :changedsince";
1762 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1766 * Set a volatile flag
1768 * @param string $type the "type" namespace for the key
1769 * @param string $name the key to set
1770 * @param string $value the value to set (without magic quotes) - null will remove the flag
1771 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1772 * @return bool Always returns true
1774 function set_cache_flag($type, $name, $value, $expiry = null) {
1777 $timemodified = time();
1778 if ($expiry === null || $expiry < $timemodified) {
1779 $expiry = $timemodified + 24 * 60 * 60;
1781 $expiry = (int)$expiry;
1784 if ($value === null) {
1785 unset_cache_flag($type, $name);
1789 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1790 // This is a potential problem in DEBUG_DEVELOPER.
1791 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1792 return true; // No need to update.
1795 $f->expiry = $expiry;
1796 $f->timemodified = $timemodified;
1797 $DB->update_record('cache_flags', $f);
1799 $f = new stdClass();
1800 $f->flagtype = $type;
1803 $f->expiry = $expiry;
1804 $f->timemodified = $timemodified;
1805 $DB->insert_record('cache_flags', $f);
1811 * Removes a single volatile flag
1813 * @param string $type the "type" namespace for the key
1814 * @param string $name the key to set
1817 function unset_cache_flag($type, $name) {
1819 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1824 * Garbage-collect volatile flags
1826 * @return bool Always returns true
1828 function gc_cache_flags() {
1830 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1834 // USER PREFERENCE API.
1837 * Refresh user preference cache. This is used most often for $USER
1838 * object that is stored in session, but it also helps with performance in cron script.
1840 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1843 * @category preference
1845 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1846 * @param int $cachelifetime Cache life time on the current page (in seconds)
1847 * @throws coding_exception
1850 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1852 // Static cache, we need to check on each page load, not only every 2 minutes.
1853 static $loadedusers = array();
1855 if (!isset($user->id)) {
1856 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1859 if (empty($user->id) or isguestuser($user->id)) {
1860 // No permanent storage for not-logged-in users and guest.
1861 if (!isset($user->preference)) {
1862 $user->preference = array();
1869 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1870 // Already loaded at least once on this page. Are we up to date?
1871 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1872 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1875 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1876 // No change since the lastcheck on this page.
1877 $user->preference['_lastloaded'] = $timenow;
1882 // OK, so we have to reload all preferences.
1883 $loadedusers[$user->id] = true;
1884 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1885 $user->preference['_lastloaded'] = $timenow;
1889 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1891 * NOTE: internal function, do not call from other code.
1895 * @param integer $userid the user whose prefs were changed.
1897 function mark_user_preferences_changed($userid) {
1900 if (empty($userid) or isguestuser($userid)) {
1901 // No cache flags for guest and not-logged-in users.
1905 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1909 * Sets a preference for the specified user.
1911 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1913 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1916 * @category preference
1918 * @param string $name The key to set as preference for the specified user
1919 * @param string $value The value to set for the $name key in the specified user's
1920 * record, null means delete current value.
1921 * @param stdClass|int|null $user A moodle user object or id, null means current user
1922 * @throws coding_exception
1923 * @return bool Always true or exception
1925 function set_user_preference($name, $value, $user = null) {
1928 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1929 throw new coding_exception('Invalid preference name in set_user_preference() call');
1932 if (is_null($value)) {
1933 // Null means delete current.
1934 return unset_user_preference($name, $user);
1935 } else if (is_object($value)) {
1936 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1937 } else if (is_array($value)) {
1938 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1940 // Value column maximum length is 1333 characters.
1941 $value = (string)$value;
1942 if (core_text::strlen($value) > 1333) {
1943 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1946 if (is_null($user)) {
1948 } else if (isset($user->id)) {
1949 // It is a valid object.
1950 } else if (is_numeric($user)) {
1951 $user = (object)array('id' => (int)$user);
1953 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1956 check_user_preferences_loaded($user);
1958 if (empty($user->id) or isguestuser($user->id)) {
1959 // No permanent storage for not-logged-in users and guest.
1960 $user->preference[$name] = $value;
1964 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1965 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1966 // Preference already set to this value.
1969 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1972 $preference = new stdClass();
1973 $preference->userid = $user->id;
1974 $preference->name = $name;
1975 $preference->value = $value;
1976 $DB->insert_record('user_preferences', $preference);
1979 // Update value in cache.
1980 $user->preference[$name] = $value;
1981 // Update the $USER in case where we've not a direct reference to $USER.
1982 if ($user !== $USER && $user->id == $USER->id) {
1983 $USER->preference[$name] = $value;
1986 // Set reload flag for other sessions.
1987 mark_user_preferences_changed($user->id);
1993 * Sets a whole array of preferences for the current user
1995 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1998 * @category preference
2000 * @param array $prefarray An array of key/value pairs to be set
2001 * @param stdClass|int|null $user A moodle user object or id, null means current user
2002 * @return bool Always true or exception
2004 function set_user_preferences(array $prefarray, $user = null) {
2005 foreach ($prefarray as $name => $value) {
2006 set_user_preference($name, $value, $user);
2012 * Unsets a preference completely by deleting it from the database
2014 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2017 * @category preference
2019 * @param string $name The key to unset as preference for the specified user
2020 * @param stdClass|int|null $user A moodle user object or id, null means current user
2021 * @throws coding_exception
2022 * @return bool Always true or exception
2024 function unset_user_preference($name, $user = null) {
2027 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2028 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2031 if (is_null($user)) {
2033 } else if (isset($user->id)) {
2034 // It is a valid object.
2035 } else if (is_numeric($user)) {
2036 $user = (object)array('id' => (int)$user);
2038 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2041 check_user_preferences_loaded($user);
2043 if (empty($user->id) or isguestuser($user->id)) {
2044 // No permanent storage for not-logged-in user and guest.
2045 unset($user->preference[$name]);
2050 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2052 // Delete the preference from cache.
2053 unset($user->preference[$name]);
2054 // Update the $USER in case where we've not a direct reference to $USER.
2055 if ($user !== $USER && $user->id == $USER->id) {
2056 unset($USER->preference[$name]);
2059 // Set reload flag for other sessions.
2060 mark_user_preferences_changed($user->id);
2066 * Used to fetch user preference(s)
2068 * If no arguments are supplied this function will return
2069 * all of the current user preferences as an array.
2071 * If a name is specified then this function
2072 * attempts to return that particular preference value. If
2073 * none is found, then the optional value $default is returned,
2076 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2079 * @category preference
2081 * @param string $name Name of the key to use in finding a preference value
2082 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2083 * @param stdClass|int|null $user A moodle user object or id, null means current user
2084 * @throws coding_exception
2085 * @return string|mixed|null A string containing the value of a single preference. An
2086 * array with all of the preferences or null
2088 function get_user_preferences($name = null, $default = null, $user = null) {
2091 if (is_null($name)) {
2093 } else if (is_numeric($name) or $name === '_lastloaded') {
2094 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2097 if (is_null($user)) {
2099 } else if (isset($user->id)) {
2100 // Is a valid object.
2101 } else if (is_numeric($user)) {
2102 if ($USER->id == $user) {
2105 $user = (object)array('id' => (int)$user);
2108 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2111 check_user_preferences_loaded($user);
2115 return $user->preference;
2116 } else if (isset($user->preference[$name])) {
2117 // The single string value.
2118 return $user->preference[$name];
2120 // Default value (null if not specified).
2125 // FUNCTIONS FOR HANDLING TIME.
2128 * Given Gregorian date parts in user time produce a GMT timestamp.
2132 * @param int $year The year part to create timestamp of
2133 * @param int $month The month part to create timestamp of
2134 * @param int $day The day part to create timestamp of
2135 * @param int $hour The hour part to create timestamp of
2136 * @param int $minute The minute part to create timestamp of
2137 * @param int $second The second part to create timestamp of
2138 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2139 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2140 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2141 * applied only if timezone is 99 or string.
2142 * @return int GMT timestamp
2144 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2145 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2146 $date->setDate((int)$year, (int)$month, (int)$day);
2147 $date->setTime((int)$hour, (int)$minute, (int)$second);
2149 $time = $date->getTimestamp();
2151 if ($time === false) {
2152 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2153 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2156 // Moodle BC DST stuff.
2158 $time += dst_offset_on($time, $timezone);
2166 * Format a date/time (seconds) as weeks, days, hours etc as needed
2168 * Given an amount of time in seconds, returns string
2169 * formatted nicely as years, days, hours etc as needed
2177 * @param int $totalsecs Time in seconds
2178 * @param stdClass $str Should be a time object
2179 * @return string A nicely formatted date/time string
2181 function format_time($totalsecs, $str = null) {
2183 $totalsecs = abs($totalsecs);
2186 // Create the str structure the slow way.
2187 $str = new stdClass();
2188 $str->day = get_string('day');
2189 $str->days = get_string('days');
2190 $str->hour = get_string('hour');
2191 $str->hours = get_string('hours');
2192 $str->min = get_string('min');
2193 $str->mins = get_string('mins');
2194 $str->sec = get_string('sec');
2195 $str->secs = get_string('secs');
2196 $str->year = get_string('year');
2197 $str->years = get_string('years');
2200 $years = floor($totalsecs/YEARSECS);
2201 $remainder = $totalsecs - ($years*YEARSECS);
2202 $days = floor($remainder/DAYSECS);
2203 $remainder = $totalsecs - ($days*DAYSECS);
2204 $hours = floor($remainder/HOURSECS);
2205 $remainder = $remainder - ($hours*HOURSECS);
2206 $mins = floor($remainder/MINSECS);
2207 $secs = $remainder - ($mins*MINSECS);
2209 $ss = ($secs == 1) ? $str->sec : $str->secs;
2210 $sm = ($mins == 1) ? $str->min : $str->mins;
2211 $sh = ($hours == 1) ? $str->hour : $str->hours;
2212 $sd = ($days == 1) ? $str->day : $str->days;
2213 $sy = ($years == 1) ? $str->year : $str->years;
2222 $oyears = $years .' '. $sy;
2225 $odays = $days .' '. $sd;
2228 $ohours = $hours .' '. $sh;
2231 $omins = $mins .' '. $sm;
2234 $osecs = $secs .' '. $ss;
2238 return trim($oyears .' '. $odays);
2241 return trim($odays .' '. $ohours);
2244 return trim($ohours .' '. $omins);
2247 return trim($omins .' '. $osecs);
2252 return get_string('now');
2256 * Returns a formatted string that represents a date in user time.
2260 * @param int $date the timestamp in UTC, as obtained from the database.
2261 * @param string $format strftime format. You should probably get this using
2262 * get_string('strftime...', 'langconfig');
2263 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2264 * not 99 then daylight saving will not be added.
2265 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2266 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2267 * If false then the leading zero is maintained.
2268 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2269 * @return string the formatted date/time.
2271 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2272 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2273 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2277 * Returns a html "time" tag with both the exact user date with timezone information
2278 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2282 * @param int $date the timestamp in UTC, as obtained from the database.
2283 * @param string $format strftime format. You should probably get this using
2284 * get_string('strftime...', 'langconfig');
2285 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2286 * not 99 then daylight saving will not be added.
2287 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2288 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2289 * If false then the leading zero is maintained.
2290 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2291 * @return string the formatted date/time.
2293 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2294 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2295 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2296 return $userdatestr;
2298 $machinedate = new DateTime();
2299 $machinedate->setTimestamp(intval($date));
2300 $machinedate->setTimezone(core_date::get_user_timezone_object());
2302 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2306 * Returns a formatted date ensuring it is UTF-8.
2308 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2309 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2311 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2312 * @param string $format strftime format.
2313 * @param int|float|string $tz the user timezone
2314 * @return string the formatted date/time.
2315 * @since Moodle 2.3.3
2317 function date_format_string($date, $format, $tz = 99) {
2320 $localewincharset = null;
2321 // Get the calendar type user is using.
2322 if ($CFG->ostype == 'WINDOWS') {
2323 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2324 $localewincharset = $calendartype->locale_win_charset();
2327 if ($localewincharset) {
2328 $format = core_text::convert($format, 'utf-8', $localewincharset);
2331 date_default_timezone_set(core_date::get_user_timezone($tz));
2332 $datestring = strftime($format, $date);
2333 core_date::set_default_server_timezone();
2335 if ($localewincharset) {
2336 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2343 * Given a $time timestamp in GMT (seconds since epoch),
2344 * returns an array that represents the Gregorian date in user time
2348 * @param int $time Timestamp in GMT
2349 * @param float|int|string $timezone user timezone
2350 * @return array An array that represents the date in user time
2352 function usergetdate($time, $timezone=99) {
2353 date_default_timezone_set(core_date::get_user_timezone($timezone));
2354 $result = getdate($time);
2355 core_date::set_default_server_timezone();
2361 * Given a GMT timestamp (seconds since epoch), offsets it by
2362 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2364 * NOTE: this function does not include DST properly,
2365 * you should use the PHP date stuff instead!
2369 * @param int $date Timestamp in GMT
2370 * @param float|int|string $timezone user timezone
2373 function usertime($date, $timezone=99) {
2374 $userdate = new DateTime('@' . $date);
2375 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2376 $dst = dst_offset_on($date, $timezone);
2378 return $date - $userdate->getOffset() + $dst;
2382 * Get a formatted string representation of an interval between two unix timestamps.
2385 * $intervalstring = get_time_interval_string(12345600, 12345660);
2386 * Will produce the string:
2389 * @param int $time1 unix timestamp
2390 * @param int $time2 unix timestamp
2391 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2392 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2394 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2395 $dtdate = new DateTime();
2396 $dtdate->setTimeStamp($time1);
2397 $dtdate2 = new DateTime();
2398 $dtdate2->setTimeStamp($time2);
2399 $interval = $dtdate2->diff($dtdate);
2400 $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2401 return $interval->format($format);
2405 * Given a time, return the GMT timestamp of the most recent midnight
2406 * for the current user.
2410 * @param int $date Timestamp in GMT
2411 * @param float|int|string $timezone user timezone
2412 * @return int Returns a GMT timestamp
2414 function usergetmidnight($date, $timezone=99) {
2416 $userdate = usergetdate($date, $timezone);
2418 // Time of midnight of this user's day, in GMT.
2419 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2424 * Returns a string that prints the user's timezone
2428 * @param float|int|string $timezone user timezone
2431 function usertimezone($timezone=99) {
2432 $tz = core_date::get_user_timezone($timezone);
2433 return core_date::get_localised_timezone($tz);
2437 * Returns a float or a string which denotes the user's timezone
2438 * 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)
2439 * means that for this timezone there are also DST rules to be taken into account
2440 * Checks various settings and picks the most dominant of those which have a value
2444 * @param float|int|string $tz timezone to calculate GMT time offset before
2445 * calculating user timezone, 99 is default user timezone
2446 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2447 * @return float|string
2449 function get_user_timezone($tz = 99) {
2454 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2455 isset($USER->timezone) ? $USER->timezone : 99,
2456 isset($CFG->timezone) ? $CFG->timezone : 99,
2461 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2462 foreach ($timezones as $nextvalue) {
2463 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2467 return is_numeric($tz) ? (float) $tz : $tz;
2471 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2472 * - Note: Daylight saving only works for string timezones and not for float.
2476 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2477 * @param int|float|string $strtimezone user timezone
2480 function dst_offset_on($time, $strtimezone = null) {
2481 $tz = core_date::get_user_timezone($strtimezone);
2482 $date = new DateTime('@' . $time);
2483 $date->setTimezone(new DateTimeZone($tz));
2484 if ($date->format('I') == '1') {
2485 if ($tz === 'Australia/Lord_Howe') {
2494 * Calculates when the day appears in specific month
2498 * @param int $startday starting day of the month
2499 * @param int $weekday The day when week starts (normally taken from user preferences)
2500 * @param int $month The month whose day is sought
2501 * @param int $year The year of the month whose day is sought
2504 function find_day_in_month($startday, $weekday, $month, $year) {
2505 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2507 $daysinmonth = days_in_month($month, $year);
2508 $daysinweek = count($calendartype->get_weekdays());
2510 if ($weekday == -1) {
2511 // Don't care about weekday, so return:
2512 // abs($startday) if $startday != -1
2513 // $daysinmonth otherwise.
2514 return ($startday == -1) ? $daysinmonth : abs($startday);
2517 // From now on we 're looking for a specific weekday.
2518 // Give "end of month" its actual value, since we know it.
2519 if ($startday == -1) {
2520 $startday = -1 * $daysinmonth;
2523 // Starting from day $startday, the sign is the direction.
2524 if ($startday < 1) {
2525 $startday = abs($startday);
2526 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2528 // This is the last such weekday of the month.
2529 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2530 if ($lastinmonth > $daysinmonth) {
2531 $lastinmonth -= $daysinweek;
2534 // Find the first such weekday <= $startday.
2535 while ($lastinmonth > $startday) {
2536 $lastinmonth -= $daysinweek;
2539 return $lastinmonth;
2541 $indexweekday = dayofweek($startday, $month, $year);
2543 $diff = $weekday - $indexweekday;
2545 $diff += $daysinweek;
2548 // This is the first such weekday of the month equal to or after $startday.
2549 $firstfromindex = $startday + $diff;
2551 return $firstfromindex;
2556 * Calculate the number of days in a given month
2560 * @param int $month The month whose day count is sought
2561 * @param int $year The year of the month whose day count is sought
2564 function days_in_month($month, $year) {
2565 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2566 return $calendartype->get_num_days_in_month($year, $month);
2570 * Calculate the position in the week of a specific calendar day
2574 * @param int $day The day of the date whose position in the week is sought
2575 * @param int $month The month of the date whose position in the week is sought
2576 * @param int $year The year of the date whose position in the week is sought
2579 function dayofweek($day, $month, $year) {
2580 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2581 return $calendartype->get_weekday($year, $month, $day);
2584 // USER AUTHENTICATION AND LOGIN.
2587 * Returns full login url.
2589 * Any form submissions for authentication to this URL must include username,
2590 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2592 * @return string login url
2594 function get_login_url() {
2597 return "$CFG->wwwroot/login/index.php";
2601 * This function checks that the current user is logged in and has the
2602 * required privileges
2604 * This function checks that the current user is logged in, and optionally
2605 * whether they are allowed to be in a particular course and view a particular
2607 * If they are not logged in, then it redirects them to the site login unless
2608 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2609 * case they are automatically logged in as guests.
2610 * If $courseid is given and the user is not enrolled in that course then the
2611 * user is redirected to the course enrolment page.
2612 * If $cm is given and the course module is hidden and the user is not a teacher
2613 * in the course then the user is redirected to the course home page.
2615 * When $cm parameter specified, this function sets page layout to 'module'.
2616 * You need to change it manually later if some other layout needed.
2618 * @package core_access
2621 * @param mixed $courseorid id of the course or course object
2622 * @param bool $autologinguest default true
2623 * @param object $cm course module object
2624 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2625 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2626 * in order to keep redirects working properly. MDL-14495
2627 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2628 * @return mixed Void, exit, and die depending on path
2629 * @throws coding_exception
2630 * @throws require_login_exception
2631 * @throws moodle_exception
2633 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2634 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2636 // Must not redirect when byteserving already started.
2637 if (!empty($_SERVER['HTTP_RANGE'])) {
2638 $preventredirect = true;
2642 // We cannot redirect for AJAX scripts either.
2643 $preventredirect = true;
2646 // Setup global $COURSE, themes, language and locale.
2647 if (!empty($courseorid)) {
2648 if (is_object($courseorid)) {
2649 $course = $courseorid;
2650 } else if ($courseorid == SITEID) {
2651 $course = clone($SITE);
2653 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2656 if ($cm->course != $course->id) {
2657 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2659 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2660 if (!($cm instanceof cm_info)) {
2661 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2662 // db queries so this is not really a performance concern, however it is obviously
2663 // better if you use get_fast_modinfo to get the cm before calling this.
2664 $modinfo = get_fast_modinfo($course);
2665 $cm = $modinfo->get_cm($cm->id);
2669 // Do not touch global $COURSE via $PAGE->set_course(),
2670 // the reasons is we need to be able to call require_login() at any time!!
2673 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2677 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2678 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2679 // risk leading the user back to the AJAX request URL.
2680 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2681 $setwantsurltome = false;
2684 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2685 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2686 if ($preventredirect) {
2687 throw new require_login_session_timeout_exception();
2689 if ($setwantsurltome) {
2690 $SESSION->wantsurl = qualified_me();
2692 redirect(get_login_url());
2696 // If the user is not even logged in yet then make sure they are.
2697 if (!isloggedin()) {
2698 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2699 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2700 // Misconfigured site guest, just redirect to login page.
2701 redirect(get_login_url());
2702 exit; // Never reached.
2704 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2705 complete_user_login($guest);
2706 $USER->autologinguest = true;
2707 $SESSION->lang = $lang;
2709 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2710 if ($preventredirect) {
2711 throw new require_login_exception('You are not logged in');
2714 if ($setwantsurltome) {
2715 $SESSION->wantsurl = qualified_me();
2718 $referer = get_local_referer(false);
2719 if (!empty($referer)) {
2720 $SESSION->fromurl = $referer;
2723 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2724 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2725 foreach($authsequence as $authname) {
2726 $authplugin = get_auth_plugin($authname);
2727 $authplugin->pre_loginpage_hook();
2730 $modinfo = get_fast_modinfo($course);
2731 $cm = $modinfo->get_cm($cm->id);
2733 set_access_log_user();
2738 // If we're still not logged in then go to the login page
2739 if (!isloggedin()) {
2740 redirect(get_login_url());
2741 exit; // Never reached.
2746 // Loginas as redirection if needed.
2747 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2748 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2749 if ($USER->loginascontext->instanceid != $course->id) {
2750 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2755 // Check whether the user should be changing password (but only if it is REALLY them).
2756 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2757 $userauth = get_auth_plugin($USER->auth);
2758 if ($userauth->can_change_password() and !$preventredirect) {
2759 if ($setwantsurltome) {
2760 $SESSION->wantsurl = qualified_me();
2762 if ($changeurl = $userauth->change_password_url()) {
2763 // Use plugin custom url.
2764 redirect($changeurl);
2766 // Use moodle internal method.
2767 redirect($CFG->wwwroot .'/login/change_password.php');
2769 } else if ($userauth->can_change_password()) {
2770 throw new moodle_exception('forcepasswordchangenotice');
2772 throw new moodle_exception('nopasswordchangeforced', 'auth');
2776 // Check that the user account is properly set up. If we can't redirect to
2777 // edit their profile and this is not a WS request, perform just the lax check.
2778 // It will allow them to use filepicker on the profile edit page.
2780 if ($preventredirect && !WS_SERVER) {
2781 $usernotfullysetup = user_not_fully_set_up($USER, false);
2783 $usernotfullysetup = user_not_fully_set_up($USER, true);
2786 if ($usernotfullysetup) {
2787 if ($preventredirect) {
2788 throw new moodle_exception('usernotfullysetup');
2790 if ($setwantsurltome) {
2791 $SESSION->wantsurl = qualified_me();
2793 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2796 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2799 if (\core\session\manager::is_loggedinas()) {
2800 // During a "logged in as" session we should force all content to be cleaned because the
2801 // logged in user will be viewing potentially malicious user generated content.
2802 // See MDL-63786 for more details.
2803 $CFG->forceclean = true;
2806 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2808 // Do not bother admins with any formalities, except for activities pending deletion.
2809 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2810 // Set the global $COURSE.
2812 $PAGE->set_cm($cm, $course);
2813 $PAGE->set_pagelayout('incourse');
2814 } else if (!empty($courseorid)) {
2815 $PAGE->set_course($course);
2817 // Set accesstime or the user will appear offline which messes up messaging.
2818 // Do not update access time for webservice or ajax requests.
2819 if (!WS_SERVER && !AJAX_SCRIPT) {
2820 user_accesstime_log($course->id);
2823 foreach ($afterlogins as $plugintype => $plugins) {
2824 foreach ($plugins as $pluginfunction) {
2825 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2831 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2832 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2833 if (!defined('NO_SITEPOLICY_CHECK')) {
2834 define('NO_SITEPOLICY_CHECK', false);
2837 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2838 // Do not test if the script explicitly asked for skipping the site policies check.
2839 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2840 $manager = new \core_privacy\local\sitepolicy\manager();
2841 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2842 if ($preventredirect) {
2843 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2845 if ($setwantsurltome) {
2846 $SESSION->wantsurl = qualified_me();
2848 redirect($policyurl);
2852 // Fetch the system context, the course context, and prefetch its child contexts.
2853 $sysctx = context_system::instance();
2854 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2856 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2861 // If the site is currently under maintenance, then print a message.
2862 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2863 if ($preventredirect) {
2864 throw new require_login_exception('Maintenance in progress');
2866 $PAGE->set_context(null);
2867 print_maintenance_message();
2870 // Make sure the course itself is not hidden.
2871 if ($course->id == SITEID) {
2872 // Frontpage can not be hidden.
2874 if (is_role_switched($course->id)) {
2875 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2877 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2878 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2879 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2880 if ($preventredirect) {
2881 throw new require_login_exception('Course is hidden');
2883 $PAGE->set_context(null);
2884 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2885 // the navigation will mess up when trying to find it.
2886 navigation_node::override_active_url(new moodle_url('/'));
2887 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2892 // Is the user enrolled?
2893 if ($course->id == SITEID) {
2894 // Everybody is enrolled on the frontpage.
2896 if (\core\session\manager::is_loggedinas()) {
2897 // Make sure the REAL person can access this course first.
2898 $realuser = \core\session\manager::get_realuser();
2899 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2900 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2901 if ($preventredirect) {
2902 throw new require_login_exception('Invalid course login-as access');
2904 $PAGE->set_context(null);
2905 echo $OUTPUT->header();
2906 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2912 if (is_role_switched($course->id)) {
2913 // Ok, user had to be inside this course before the switch.
2916 } else if (is_viewing($coursecontext, $USER)) {
2917 // Ok, no need to mess with enrol.
2921 if (isset($USER->enrol['enrolled'][$course->id])) {
2922 if ($USER->enrol['enrolled'][$course->id] > time()) {
2924 if (isset($USER->enrol['tempguest'][$course->id])) {
2925 unset($USER->enrol['tempguest'][$course->id]);
2926 remove_temp_course_roles($coursecontext);
2930 unset($USER->enrol['enrolled'][$course->id]);
2933 if (isset($USER->enrol['tempguest'][$course->id])) {
2934 if ($USER->enrol['tempguest'][$course->id] == 0) {
2936 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2940 unset($USER->enrol['tempguest'][$course->id]);
2941 remove_temp_course_roles($coursecontext);
2947 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2948 if ($until !== false) {
2949 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2951 $until = ENROL_MAX_TIMESTAMP;
2953 $USER->enrol['enrolled'][$course->id] = $until;
2956 } else if (core_course_category::can_view_course_info($course)) {
2957 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2958 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2959 $enrols = enrol_get_plugins(true);
2960 // First ask all enabled enrol instances in course if they want to auto enrol user.
2961 foreach ($instances as $instance) {
2962 if (!isset($enrols[$instance->enrol])) {
2965 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2966 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2967 if ($until !== false) {
2969 $until = ENROL_MAX_TIMESTAMP;
2971 $USER->enrol['enrolled'][$course->id] = $until;
2976 // If not enrolled yet try to gain temporary guest access.
2978 foreach ($instances as $instance) {
2979 if (!isset($enrols[$instance->enrol])) {
2982 // Get a duration for the guest access, a timestamp in the future or false.
2983 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2984 if ($until !== false and $until > time()) {
2985 $USER->enrol['tempguest'][$course->id] = $until;
2992 // User is not enrolled and is not allowed to browse courses here.
2993 if ($preventredirect) {
2994 throw new require_login_exception('Course is not available');
2996 $PAGE->set_context(null);
2997 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2998 // the navigation will mess up when trying to find it.
2999 navigation_node::override_active_url(new moodle_url('/'));
3000 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3006 if ($preventredirect) {
3007 throw new require_login_exception('Not enrolled');
3009 if ($setwantsurltome) {
3010 $SESSION->wantsurl = qualified_me();
3012 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3016 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3017 if ($cm && $cm->deletioninprogress) {
3018 if ($preventredirect) {
3019 throw new moodle_exception('activityisscheduledfordeletion');
3021 require_once($CFG->dirroot . '/course/lib.php');
3022 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3025 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3026 if ($cm && !$cm->uservisible) {
3027 if ($preventredirect) {
3028 throw new require_login_exception('Activity is hidden');
3030 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3031 $PAGE->set_course($course);
3032 $renderer = $PAGE->get_renderer('course');
3033 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3034 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3037 // Set the global $COURSE.
3039 $PAGE->set_cm($cm, $course);
3040 $PAGE->set_pagelayout('incourse');
3041 } else if (!empty($courseorid)) {
3042 $PAGE->set_course($course);
3045 foreach ($afterlogins as $plugintype => $plugins) {
3046 foreach ($plugins as $pluginfunction) {
3047 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3051 // Finally access granted, update lastaccess times.
3052 // Do not update access time for webservice or ajax requests.
3053 if (!WS_SERVER && !AJAX_SCRIPT) {
3054 user_accesstime_log($course->id);
3059 * A convenience function for where we must be logged in as admin
3062 function require_admin() {
3063 require_login(null, false);
3064 require_capability('moodle/site:config', context_system::instance());
3068 * This function just makes sure a user is logged out.
3070 * @package core_access
3073 function require_logout() {
3076 if (!isloggedin()) {
3077 // This should not happen often, no need for hooks or events here.
3078 \core\session\manager::terminate_current();
3082 // Execute hooks before action.
3083 $authplugins = array();
3084 $authsequence = get_enabled_auth_plugins();
3085 foreach ($authsequence as $authname) {
3086 $authplugins[$authname] = get_auth_plugin($authname);
3087 $authplugins[$authname]->prelogout_hook();
3090 // Store info that gets removed during logout.
3091 $sid = session_id();
3092 $event = \core\event\user_loggedout::create(
3094 'userid' => $USER->id,
3095 'objectid' => $USER->id,
3096 'other' => array('sessionid' => $sid),
3099 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3100 $event->add_record_snapshot('sessions', $session);
3103 // Clone of $USER object to be used by auth plugins.
3104 $user = fullclone($USER);
3106 // Delete session record and drop $_SESSION content.
3107 \core\session\manager::terminate_current();
3109 // Trigger event AFTER action.
3112 // Hook to execute auth plugins redirection after event trigger.
3113 foreach ($authplugins as $authplugin) {
3114 $authplugin->postlogout_hook($user);
3119 * Weaker version of require_login()
3121 * This is a weaker version of {@link require_login()} which only requires login
3122 * when called from within a course rather than the site page, unless
3123 * the forcelogin option is turned on.
3124 * @see require_login()
3126 * @package core_access
3129 * @param mixed $courseorid The course object or id in question
3130 * @param bool $autologinguest Allow autologin guests if that is wanted
3131 * @param object $cm Course activity module if known
3132 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3133 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3134 * in order to keep redirects working properly. MDL-14495
3135 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3137 * @throws coding_exception
3139 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3140 global $CFG, $PAGE, $SITE;
3141 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3142 or (!is_object($courseorid) and $courseorid == SITEID));
3143 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3144 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3145 // db queries so this is not really a performance concern, however it is obviously
3146 // better if you use get_fast_modinfo to get the cm before calling this.
3147 if (is_object($courseorid)) {
3148 $course = $courseorid;
3150 $course = clone($SITE);
3152 $modinfo = get_fast_modinfo($course);
3153 $cm = $modinfo->get_cm($cm->id);
3155 if (!empty($CFG->forcelogin)) {
3156 // Login required for both SITE and courses.
3157 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3159 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3160 // Always login for hidden activities.
3161 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3163 } else if (isloggedin() && !isguestuser()) {
3164 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3165 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3167 } else if ($issite) {
3168 // Login for SITE not required.
3169 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3170 if (!empty($courseorid)) {
3171 if (is_object($courseorid)) {
3172 $course = $courseorid;
3174 $course = clone $SITE;
3177 if ($cm->course != $course->id) {
3178 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3180 $PAGE->set_cm($cm, $course);
3181 $PAGE->set_pagelayout('incourse');
3183 $PAGE->set_course($course);
3186 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3187 $PAGE->set_course($PAGE->course);
3189 // Do not update access time for webservice or ajax requests.
3190 if (!WS_SERVER && !AJAX_SCRIPT) {
3191 user_accesstime_log(SITEID);
3196 // Course login always required.
3197 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3202 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3204 * @param string $keyvalue the key value
3205 * @param string $script unique script identifier
3206 * @param int $instance instance id
3207 * @return stdClass the key entry in the user_private_key table
3209 * @throws moodle_exception
3211 function validate_user_key($keyvalue, $script, $instance) {
3214 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3215 print_error('invalidkey');
3218 if (!empty($key->validuntil) and $key->validuntil < time()) {
3219 print_error('expiredkey');
3222 if ($key->iprestriction) {
3223 $remoteaddr = getremoteaddr(null);
3224 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3225 print_error('ipmismatch');
3232 * Require key login. Function terminates with error if key not found or incorrect.
3234 * @uses NO_MOODLE_COOKIES
3235 * @uses PARAM_ALPHANUM
3236 * @param string $script unique script identifier
3237 * @param int $instance optional instance id
3238 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3239 * @return int Instance ID
3241 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3244 if (!NO_MOODLE_COOKIES) {
3245 print_error('sessioncookiesdisable');
3249 \core\session\manager::write_close();
3251 if (null === $keyvalue) {
3252 $keyvalue = required_param('key', PARAM_ALPHANUM);
3255 $key = validate_user_key($keyvalue, $script, $instance);
3257 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3258 print_error('invaliduserid');
3261 core_user::require_active_user($user, true, true);
3263 // Emulate normal session.
3264 enrol_check_plugins($user);
3265 \core\session\manager::set_user($user);
3267 // Note we are not using normal login.
3268 if (!defined('USER_KEY_LOGIN')) {
3269 define('USER_KEY_LOGIN', true);
3272 // Return instance id - it might be empty.
3273 return $key->instance;
3277 * Creates a new private user access key.
3279 * @param string $script unique target identifier
3280 * @param int $userid
3281 * @param int $instance optional instance id
3282 * @param string $iprestriction optional ip restricted access
3283 * @param int $validuntil key valid only until given data
3284 * @return string access key value
3286 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3289 $key = new stdClass();
3290 $key->script = $script;
3291 $key->userid = $userid;
3292 $key->instance = $instance;
3293 $key->iprestriction = $iprestriction;
3294 $key->validuntil = $validuntil;
3295 $key->timecreated = time();
3297 // Something long and unique.
3298 $key->value = md5($userid.'_'.time().random_string(40));
3299 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3301 $key->value = md5($userid.'_'.time().random_string(40));
3303 $DB->insert_record('user_private_key', $key);
3308 * Delete the user's new private user access keys for a particular script.
3310 * @param string $script unique target identifier
3311 * @param int $userid
3314 function delete_user_key($script, $userid) {
3316 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3320 * Gets a private user access key (and creates one if one doesn't exist).
3322 * @param string $script unique target identifier
3323 * @param int $userid
3324 * @param int $instance optional instance id
3325 * @param string $iprestriction optional ip restricted access
3326 * @param int $validuntil key valid only until given date
3327 * @return string access key value
3329 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3332 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3333 'instance' => $instance, 'iprestriction' => $iprestriction,
3334 'validuntil' => $validuntil))) {
3337 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3343 * Modify the user table by setting the currently logged in user's last login to now.
3345 * @return bool Always returns true
3347 function update_user_login_times() {
3350 if (isguestuser()) {
3351 // Do not update guest access times/ips for performance.
3357 $user = new stdClass();
3358 $user->id = $USER->id;
3360 // Make sure all users that logged in have some firstaccess.
3361 if ($USER->firstaccess == 0) {
3362 $USER->firstaccess = $user->firstaccess = $now;
3365 // Store the previous current as lastlogin.
3366 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3368 $USER->currentlogin = $user->currentlogin = $now;
3370 // Function user_accesstime_log() may not update immediately, better do it here.
3371 $USER->lastaccess = $user->lastaccess = $now;
3372 $USER->lastip = $user->lastip = getremoteaddr();
3374 // Note: do not call user_update_user() here because this is part of the login process,
3375 // the login event means that these fields were updated.
3376 $DB->update_record('user', $user);
3381 * Determines if a user has completed setting up their account.
3383 * The lax mode (with $strict = false) has been introduced for special cases
3384 * only where we want to skip certain checks intentionally. This is valid in
3385 * certain mnet or ajax scenarios when the user cannot / should not be
3386 * redirected to edit their profile. In most cases, you should perform the
3389 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3390 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3393 function user_not_fully_set_up($user, $strict = true) {
3395 require_once($CFG->dirroot.'/user/profile/lib.php');
3397 if (isguestuser($user)) {
3401 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3406 if (empty($user->id)) {
3407 // Strict mode can be used with existing accounts only.
3410 if (!profile_has_required_custom_fields_set($user->id)) {
3419 * Check whether the user has exceeded the bounce threshold
3421 * @param stdClass $user A {@link $USER} object
3422 * @return bool true => User has exceeded bounce threshold
3424 function over_bounce_threshold($user) {
3427 if (empty($CFG->handlebounces)) {
3431 if (empty($user->id)) {
3432 // No real (DB) user, nothing to do here.
3436 // Set sensible defaults.
3437 if (empty($CFG->minbounces)) {
3438 $CFG->minbounces = 10;
3440 if (empty($CFG->bounceratio)) {
3441 $CFG->bounceratio = .20;
3445 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3446 $bouncecount = $bounce->value;
3448 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3449 $sendcount = $send->value;
3451 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3455 * Used to increment or reset email sent count
3457 * @param stdClass $user object containing an id
3458 * @param bool $reset will reset the count to 0
3461 function set_send_count($user, $reset=false) {
3464 if (empty($user->id)) {
3465 // No real (DB) user, nothing to do here.
3469 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3470 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3471 $DB->update_record('user_preferences', $pref);
3472 } else if (!empty($reset)) {
3473 // If it's not there and we're resetting, don't bother. Make a new one.
3474 $pref = new stdClass();
3475 $pref->name = 'email_send_count';
3477 $pref->userid = $user->id;
3478 $DB->insert_record('user_preferences', $pref, false);
3483 * Increment or reset user's email bounce count
3485 * @param stdClass $user object containing an id
3486 * @param bool $reset will reset the count to 0
3488 function set_bounce_count($user, $reset=false) {
3491 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3492 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3493 $DB->update_record('user_preferences', $pref);
3494 } else if (!empty($reset)) {
3495 // If it's not there and we're resetting, don't bother. Make a new one.
3496 $pref = new stdClass();
3497 $pref->name = 'email_bounce_count';
3499 $pref->userid = $user->id;
3500 $DB->insert_record('user_preferences', $pref, false);
3505 * Determines if the logged in user is currently moving an activity
3507 * @param int $courseid The id of the course being tested
3510 function ismoving($courseid) {
3513 if (!empty($USER->activitycopy)) {
3514 return ($USER->activitycopycourse == $courseid);
3520 * Returns a persons full name
3522 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3523 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3526 * @param stdClass $user A {@link $USER} object to get full name of.
3527 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3530 function fullname($user, $override=false) {
3531 global $CFG, $SESSION;
3533 if (!isset($user->firstname) and !isset($user->lastname)) {
3537 // Get all of the name fields.
3538 $allnames = get_all_user_name_fields();
3539 if ($CFG->debugdeveloper) {
3540 foreach ($allnames as $allname) {
3541 if (!property_exists($user, $allname)) {
3542 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3543 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3544 // Message has been sent, no point in sending the message multiple times.
3551 if (!empty($CFG->forcefirstname)) {
3552 $user->firstname = $CFG->forcefirstname;
3554 if (!empty($CFG->forcelastname)) {
3555 $user->lastname = $CFG->forcelastname;
3559 if (!empty($SESSION->fullnamedisplay)) {
3560 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3564 // If the fullnamedisplay setting is available, set the template to that.
3565 if (isset($CFG->fullnamedisplay)) {
3566 $template = $CFG->fullnamedisplay;
3568 // If the template is empty, or set to language, return the language string.
3569 if ((empty($template) || $template == 'language') && !$override) {
3570 return get_string('fullnamedisplay', null, $user);
3573 // Check to see if we are displaying according to the alternative full name format.
3575 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3576 // Default to show just the user names according to the fullnamedisplay string.
3577 return get_string('fullnamedisplay', null, $user);
3579 // If the override is true, then change the template to use the complete name.
3580 $template = $CFG->alternativefullnameformat;
3584 $requirednames = array();
3585 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3586 foreach ($allnames as $allname) {
3587 if (strpos($template, $allname) !== false) {
3588 $requirednames[] = $allname;
3592 $displayname = $template;
3593 // Switch in the actual data into the template.
3594 foreach ($requirednames as $altname) {
3595 if (isset($user->$altname)) {
3596 // Using empty() on the below if statement causes breakages.
3597 if ((string)$user->$altname == '') {
3598 $displayname = str_replace($altname, 'EMPTY', $displayname);
3600 $displayname = str_replace($altname, $user->$altname, $displayname);
3603 $displayname = str_replace($altname, 'EMPTY', $displayname);
3606 // Tidy up any misc. characters (Not perfect, but gets most characters).
3607 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3608 // katakana and parenthesis.
3609 $patterns = array();
3610 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3611 // filled in by a user.
3612 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3613 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3614 // This regular expression is to remove any double spaces in the display name.
3615 $patterns[] = '/\s{2,}/u';
3616 foreach ($patterns as $pattern) {
3617 $displayname = preg_replace($pattern, ' ', $displayname);
3620 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3621 $displayname = trim($displayname);
3622 if (empty($displayname)) {
3623 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3624 // people in general feel is a good setting to fall back on.
3625 $displayname = $user->firstname;
3627 return $displayname;
3631 * A centralised location for the all name fields. Returns an array / sql string snippet.
3633 * @param bool $returnsql True for an sql select field snippet.
3634 * @param string $tableprefix table query prefix to use in front of each field.
3635 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3636 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3637 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3638 * @return array|string All name fields.
3640 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3641 // This array is provided in this order because when called by fullname() (above) if firstname is before
3642 // firstnamephonetic str_replace() will change the wrong placeholder.
3643 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3644 'lastnamephonetic' => 'lastnamephonetic',
3645 'middlename' => 'middlename',