2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
83 define('PARAM_ALPHAEXT', 'alphaext');
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
98 define('PARAM_AUTH', 'auth');
101 * PARAM_BASE64 - Base 64 encoded format
103 define('PARAM_BASE64', 'base64');
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
108 define('PARAM_BOOL', 'bool');
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
114 define('PARAM_CAPABILITY', 'capability');
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119 * the input (required/optional_param or formslib) and then sanitse the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
123 define('PARAM_CLEANHTML', 'cleanhtml');
126 * PARAM_EMAIL - an email address following the RFC
128 define('PARAM_EMAIL', 'email');
131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
133 define('PARAM_FILE', 'file');
136 * PARAM_FLOAT - a real/floating point number.
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
146 define('PARAM_FLOAT', 'float');
149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
151 define('PARAM_HOST', 'host');
154 * PARAM_INT - integers only, use when expecting only numbers.
156 define('PARAM_INT', 'int');
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
161 define('PARAM_LANG', 'lang');
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
167 define('PARAM_LOCALURL', 'localurl');
170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
172 define('PARAM_NOTAGS', 'notags');
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
178 define('PARAM_PATH', 'path');
181 * PARAM_PEM - Privacy Enhanced Mail format
183 define('PARAM_PEM', 'pem');
186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
188 define('PARAM_PERMISSION', 'permission');
191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
193 define('PARAM_RAW', 'raw');
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
203 define('PARAM_SAFEDIR', 'safedir');
206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
208 define('PARAM_SAFEPATH', 'safepath');
211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
213 define('PARAM_SEQUENCE', 'sequence');
216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
218 define('PARAM_TAG', 'tag');
221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
223 define('PARAM_TAGLIST', 'taglist');
226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
228 define('PARAM_TEXT', 'text');
231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
233 define('PARAM_THEME', 'theme');
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
245 define('PARAM_USERNAME', 'username');
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
250 define('PARAM_STRINGID', 'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
256 * @deprecated since 2.0
258 define('PARAM_CLEAN', 'clean');
261 * PARAM_INTEGER - deprecated alias for PARAM_INT
262 * @deprecated since 2.0
264 define('PARAM_INTEGER', 'int');
267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268 * @deprecated since 2.0
270 define('PARAM_NUMBER', 'float');
273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274 * NOTE: originally alias for PARAM_APLHA
275 * @deprecated since 2.0
277 define('PARAM_ACTION', 'alphanumext');
280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
282 * @deprecated since 2.0
284 define('PARAM_FORMAT', 'alphanumext');
287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288 * @deprecated since 2.0
290 define('PARAM_MULTILANG', 'text');
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295 * America/Port-au-Prince)
297 define('PARAM_TIMEZONE', 'timezone');
300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
302 define('PARAM_CLEANFILE', 'file');
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
310 define('PARAM_COMPONENT', 'component');
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
317 define('PARAM_AREA', 'area');
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
324 define('PARAM_PLUGIN', 'plugin');
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
332 define('VALUE_REQUIRED', 1);
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
337 define('VALUE_OPTIONAL', 2);
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
342 define('VALUE_DEFAULT', 0);
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
347 define('NULL_NOT_ALLOWED', false);
350 * NULL_ALLOWED - the parameter can be set to null in the database
352 define('NULL_ALLOWED', true);
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
442 /** Unspecified module archetype */
443 define('MOD_ARCHETYPE_OTHER', 0);
444 /** Resource-like type module */
445 define('MOD_ARCHETYPE_RESOURCE', 1);
446 /** Assignment module archetype */
447 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448 /** System (not user-addable) module archetype */
449 define('MOD_ARCHETYPE_SYSTEM', 3);
452 * Return this from modname_get_types callback to use default display in activity chooser.
453 * Deprecated, will be removed in 3.5, TODO MDL-53697.
454 * @deprecated since Moodle 3.1
456 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
459 * Security token used for allowing access
460 * from external application such as web services.
461 * Scripts do not use any session, performance is relatively
462 * low because we need to load access info in each request.
463 * Scripts are executed in parallel.
465 define('EXTERNAL_TOKEN_PERMANENT', 0);
468 * Security token used for allowing access
469 * of embedded applications, the code is executed in the
470 * active user session. Token is invalidated after user logs out.
471 * Scripts are executed serially - normal session locking is used.
473 define('EXTERNAL_TOKEN_EMBEDDED', 1);
476 * The home page should be the site home
478 define('HOMEPAGE_SITE', 0);
480 * The home page should be the users my page
482 define('HOMEPAGE_MY', 1);
484 * The home page can be chosen by the user
486 define('HOMEPAGE_USER', 2);
489 * Hub directory url (should be moodle.org)
491 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
495 * Moodle.org url (should be moodle.org)
497 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
500 * Moodle mobile app service name
502 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
505 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
507 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
510 * Course display settings: display all sections on one page.
512 define('COURSE_DISPLAY_SINGLEPAGE', 0);
514 * Course display settings: split pages into a page per section.
516 define('COURSE_DISPLAY_MULTIPAGE', 1);
519 * Authentication constant: String used in password field when password is not stored.
521 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
523 // PARAMETER HANDLING.
526 * Returns a particular value for the named variable, taken from
527 * POST or GET. If the parameter doesn't exist then an error is
528 * thrown because we require this variable.
530 * This function should be used to initialise all required values
531 * in a script that are based on parameters. Usually it will be
533 * $id = required_param('id', PARAM_INT);
535 * Please note the $type parameter is now required and the value can not be array.
537 * @param string $parname the name of the page parameter we want
538 * @param string $type expected type of parameter
540 * @throws coding_exception
542 function required_param($parname, $type) {
543 if (func_num_args() != 2 or empty($parname) or empty($type)) {
544 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
546 // POST has precedence.
547 if (isset($_POST[$parname])) {
548 $param = $_POST[$parname];
549 } else if (isset($_GET[$parname])) {
550 $param = $_GET[$parname];
552 print_error('missingparam', '', '', $parname);
555 if (is_array($param)) {
556 debugging('Invalid array parameter detected in required_param(): '.$parname);
557 // TODO: switch to fatal error in Moodle 2.3.
558 return required_param_array($parname, $type);
561 return clean_param($param, $type);
565 * Returns a particular array value for the named variable, taken from
566 * POST or GET. If the parameter doesn't exist then an error is
567 * thrown because we require this variable.
569 * This function should be used to initialise all required values
570 * in a script that are based on parameters. Usually it will be
572 * $ids = required_param_array('ids', PARAM_INT);
574 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
576 * @param string $parname the name of the page parameter we want
577 * @param string $type expected type of parameter
579 * @throws coding_exception
581 function required_param_array($parname, $type) {
582 if (func_num_args() != 2 or empty($parname) or empty($type)) {
583 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
585 // POST has precedence.
586 if (isset($_POST[$parname])) {
587 $param = $_POST[$parname];
588 } else if (isset($_GET[$parname])) {
589 $param = $_GET[$parname];
591 print_error('missingparam', '', '', $parname);
593 if (!is_array($param)) {
594 print_error('missingparam', '', '', $parname);
598 foreach ($param as $key => $value) {
599 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
600 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
603 $result[$key] = clean_param($value, $type);
610 * Returns a particular value for the named variable, taken from
611 * POST or GET, otherwise returning a given default.
613 * This function should be used to initialise all optional values
614 * in a script that are based on parameters. Usually it will be
616 * $name = optional_param('name', 'Fred', PARAM_TEXT);
618 * Please note the $type parameter is now required and the value can not be array.
620 * @param string $parname the name of the page parameter we want
621 * @param mixed $default the default value to return if nothing is found
622 * @param string $type expected type of parameter
624 * @throws coding_exception
626 function optional_param($parname, $default, $type) {
627 if (func_num_args() != 3 or empty($parname) or empty($type)) {
628 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
631 // POST has precedence.
632 if (isset($_POST[$parname])) {
633 $param = $_POST[$parname];
634 } else if (isset($_GET[$parname])) {
635 $param = $_GET[$parname];
640 if (is_array($param)) {
641 debugging('Invalid array parameter detected in required_param(): '.$parname);
642 // TODO: switch to $default in Moodle 2.3.
643 return optional_param_array($parname, $default, $type);
646 return clean_param($param, $type);
650 * Returns a particular array value for the named variable, taken from
651 * POST or GET, otherwise returning a given default.
653 * This function should be used to initialise all optional values
654 * in a script that are based on parameters. Usually it will be
656 * $ids = optional_param('id', array(), PARAM_INT);
658 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
660 * @param string $parname the name of the page parameter we want
661 * @param mixed $default the default value to return if nothing is found
662 * @param string $type expected type of parameter
664 * @throws coding_exception
666 function optional_param_array($parname, $default, $type) {
667 if (func_num_args() != 3 or empty($parname) or empty($type)) {
668 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
671 // POST has precedence.
672 if (isset($_POST[$parname])) {
673 $param = $_POST[$parname];
674 } else if (isset($_GET[$parname])) {
675 $param = $_GET[$parname];
679 if (!is_array($param)) {
680 debugging('optional_param_array() expects array parameters only: '.$parname);
685 foreach ($param as $key => $value) {
686 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
687 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
690 $result[$key] = clean_param($value, $type);
697 * Strict validation of parameter values, the values are only converted
698 * to requested PHP type. Internally it is using clean_param, the values
699 * before and after cleaning must be equal - otherwise
700 * an invalid_parameter_exception is thrown.
701 * Objects and classes are not accepted.
703 * @param mixed $param
704 * @param string $type PARAM_ constant
705 * @param bool $allownull are nulls valid value?
706 * @param string $debuginfo optional debug information
707 * @return mixed the $param value converted to PHP type
708 * @throws invalid_parameter_exception if $param is not of given type
710 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
711 if (is_null($param)) {
712 if ($allownull == NULL_ALLOWED) {
715 throw new invalid_parameter_exception($debuginfo);
718 if (is_array($param) or is_object($param)) {
719 throw new invalid_parameter_exception($debuginfo);
722 $cleaned = clean_param($param, $type);
724 if ($type == PARAM_FLOAT) {
725 // Do not detect precision loss here.
726 if (is_float($param) or is_int($param)) {
728 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
729 throw new invalid_parameter_exception($debuginfo);
731 } else if ((string)$param !== (string)$cleaned) {
732 // Conversion to string is usually lossless.
733 throw new invalid_parameter_exception($debuginfo);
740 * Makes sure array contains only the allowed types, this function does not validate array key names!
743 * $options = clean_param($options, PARAM_INT);
746 * @param array $param the variable array we are cleaning
747 * @param string $type expected format of param after cleaning.
748 * @param bool $recursive clean recursive arrays
750 * @throws coding_exception
752 function clean_param_array(array $param = null, $type, $recursive = false) {
753 // Convert null to empty array.
754 $param = (array)$param;
755 foreach ($param as $key => $value) {
756 if (is_array($value)) {
758 $param[$key] = clean_param_array($value, $type, true);
760 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
763 $param[$key] = clean_param($value, $type);
770 * Used by {@link optional_param()} and {@link required_param()} to
771 * clean the variables and/or cast to specific types, based on
774 * $course->format = clean_param($course->format, PARAM_ALPHA);
775 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
778 * @param mixed $param the variable we are cleaning
779 * @param string $type expected format of param after cleaning.
781 * @throws coding_exception
783 function clean_param($param, $type) {
786 if (is_array($param)) {
787 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
788 } else if (is_object($param)) {
789 if (method_exists($param, '__toString')) {
790 $param = $param->__toString();
792 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
798 // No cleaning at all.
799 $param = fix_utf8($param);
802 case PARAM_RAW_TRIMMED:
803 // No cleaning, but strip leading and trailing whitespace.
804 $param = fix_utf8($param);
808 // General HTML cleaning, try to use more specific type if possible this is deprecated!
809 // Please use more specific type instead.
810 if (is_numeric($param)) {
813 $param = fix_utf8($param);
814 // Sweep for scripts, etc.
815 return clean_text($param);
817 case PARAM_CLEANHTML:
818 // Clean html fragment.
819 $param = fix_utf8($param);
820 // Sweep for scripts, etc.
821 $param = clean_text($param, FORMAT_HTML);
825 // Convert to integer.
830 return (float)$param;
833 // Remove everything not `a-z`.
834 return preg_replace('/[^a-zA-Z]/i', '', $param);
837 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
838 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
841 // Remove everything not `a-zA-Z0-9`.
842 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
844 case PARAM_ALPHANUMEXT:
845 // Remove everything not `a-zA-Z0-9_-`.
846 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
849 // Remove everything not `0-9,`.
850 return preg_replace('/[^0-9,]/i', '', $param);
853 // Convert to 1 or 0.
854 $tempstr = strtolower($param);
855 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
857 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
860 $param = empty($param) ? 0 : 1;
866 $param = fix_utf8($param);
867 return strip_tags($param);
870 // Leave only tags needed for multilang.
871 $param = fix_utf8($param);
872 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
873 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
875 if (strpos($param, '</lang>') !== false) {
876 // Old and future mutilang syntax.
877 $param = strip_tags($param, '<lang>');
878 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
882 foreach ($matches[0] as $match) {
883 if ($match === '</lang>') {
891 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
902 } else if (strpos($param, '</span>') !== false) {
903 // Current problematic multilang syntax.
904 $param = strip_tags($param, '<span>');
905 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
909 foreach ($matches[0] as $match) {
910 if ($match === '</span>') {
918 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
930 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
931 return strip_tags($param);
933 case PARAM_COMPONENT:
934 // We do not want any guessing here, either the name is correct or not
935 // please note only normalised component names are accepted.
936 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
939 if (strpos($param, '__') !== false) {
942 if (strpos($param, 'mod_') === 0) {
943 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
944 if (substr_count($param, '_') != 1) {
952 // We do not want any guessing here, either the name is correct or not.
953 if (!is_valid_plugin_name($param)) {
959 // Remove everything not a-zA-Z0-9_- .
960 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
963 // Remove everything not a-zA-Z0-9/_- .
964 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
967 // Strip all suspicious characters from filename.
968 $param = fix_utf8($param);
969 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
970 if ($param === '.' || $param === '..') {
976 // Strip all suspicious characters from file path.
977 $param = fix_utf8($param);
978 $param = str_replace('\\', '/', $param);
980 // Explode the path and clean each element using the PARAM_FILE rules.
981 $breadcrumb = explode('/', $param);
982 foreach ($breadcrumb as $key => $crumb) {
983 if ($crumb === '.' && $key === 0) {
984 // Special condition to allow for relative current path such as ./currentdirfile.txt.
986 $crumb = clean_param($crumb, PARAM_FILE);
988 $breadcrumb[$key] = $crumb;
990 $param = implode('/', $breadcrumb);
992 // Remove multiple current path (./././) and multiple slashes (///).
993 $param = preg_replace('~//+~', '/', $param);
994 $param = preg_replace('~/(\./)+~', '/', $param);
998 // Allow FQDN or IPv4 dotted quad.
999 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1000 // Match ipv4 dotted quad.
1001 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1002 // Confirm values are ok.
1003 if ( $match[0] > 255
1006 || $match[4] > 255 ) {
1007 // Hmmm, what kind of dotted quad is this?
1010 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1011 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1012 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1014 // All is ok - $param is respected.
1021 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1022 $param = fix_utf8($param);
1023 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1024 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1025 // All is ok, param is respected.
1032 case PARAM_LOCALURL:
1033 // Allow http absolute, root relative and relative URLs within wwwroot.
1034 $param = clean_param($param, PARAM_URL);
1035 if (!empty($param)) {
1037 // Simulate the HTTPS version of the site.
1038 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1040 if ($param === $CFG->wwwroot) {
1042 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1044 } else if (preg_match(':^/:', $param)) {
1045 // Root-relative, ok!
1046 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1047 // Absolute, and matches our wwwroot.
1048 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1049 // Absolute, and matches our httpswwwroot.
1051 // Relative - let's make sure there are no tricks.
1052 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1062 $param = trim($param);
1063 // PEM formatted strings may contain letters/numbers and the symbols:
1067 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1068 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1069 list($wholething, $body) = $matches;
1070 unset($wholething, $matches);
1071 $b64 = clean_param($body, PARAM_BASE64);
1073 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1081 if (!empty($param)) {
1082 // PEM formatted strings may contain letters/numbers and the symbols
1086 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1089 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1090 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1091 // than (or equal to) 64 characters long.
1092 for ($i=0, $j=count($lines); $i < $j; $i++) {
1094 if (64 < strlen($lines[$i])) {
1100 if (64 != strlen($lines[$i])) {
1104 return implode("\n", $lines);
1110 $param = fix_utf8($param);
1111 // Please note it is not safe to use the tag name directly anywhere,
1112 // it must be processed with s(), urlencode() before embedding anywhere.
1113 // Remove some nasties.
1114 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1115 // Convert many whitespace chars into one.
1116 $param = preg_replace('/\s+/u', ' ', $param);
1117 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1121 $param = fix_utf8($param);
1122 $tags = explode(',', $param);
1124 foreach ($tags as $tag) {
1125 $res = clean_param($tag, PARAM_TAG);
1131 return implode(',', $result);
1136 case PARAM_CAPABILITY:
1137 if (get_capability_info($param)) {
1143 case PARAM_PERMISSION:
1144 $param = (int)$param;
1145 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1152 $param = clean_param($param, PARAM_PLUGIN);
1153 if (empty($param)) {
1155 } else if (exists_auth_plugin($param)) {
1162 $param = clean_param($param, PARAM_SAFEDIR);
1163 if (get_string_manager()->translation_exists($param)) {
1166 // Specified language is not installed or param malformed.
1171 $param = clean_param($param, PARAM_PLUGIN);
1172 if (empty($param)) {
1174 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1176 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1179 // Specified theme is not installed.
1183 case PARAM_USERNAME:
1184 $param = fix_utf8($param);
1185 $param = trim($param);
1186 // Convert uppercase to lowercase MDL-16919.
1187 $param = core_text::strtolower($param);
1188 if (empty($CFG->extendedusernamechars)) {
1189 $param = str_replace(" " , "", $param);
1190 // Regular expression, eliminate all chars EXCEPT:
1191 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1192 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1197 $param = fix_utf8($param);
1198 if (validate_email($param)) {
1204 case PARAM_STRINGID:
1205 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1211 case PARAM_TIMEZONE:
1212 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1213 $param = fix_utf8($param);
1214 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1215 if (preg_match($timezonepattern, $param)) {
1222 // Doh! throw error, switched parameters in optional_param or another serious problem.
1223 print_error("unknownparamtype", '', '', $type);
1228 * Makes sure the data is using valid utf8, invalid characters are discarded.
1230 * Note: this function is not intended for full objects with methods and private properties.
1232 * @param mixed $value
1233 * @return mixed with proper utf-8 encoding
1235 function fix_utf8($value) {
1236 if (is_null($value) or $value === '') {
1239 } else if (is_string($value)) {
1240 if ((string)(int)$value === $value) {
1244 // No null bytes expected in our data, so let's remove it.
1245 $value = str_replace("\0", '', $value);
1247 // Note: this duplicates min_fix_utf8() intentionally.
1248 static $buggyiconv = null;
1249 if ($buggyiconv === null) {
1250 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1254 if (function_exists('mb_convert_encoding')) {
1255 $subst = mb_substitute_character();
1256 mb_substitute_character('');
1257 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1258 mb_substitute_character($subst);
1261 // Warn admins on admin/index.php page.
1266 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1271 } else if (is_array($value)) {
1272 foreach ($value as $k => $v) {
1273 $value[$k] = fix_utf8($v);
1277 } else if (is_object($value)) {
1278 // Do not modify original.
1279 $value = clone($value);
1280 foreach ($value as $k => $v) {
1281 $value->$k = fix_utf8($v);
1286 // This is some other type, no utf-8 here.
1292 * Return true if given value is integer or string with integer value
1294 * @param mixed $value String or Int
1295 * @return bool true if number, false if not
1297 function is_number($value) {
1298 if (is_int($value)) {
1300 } else if (is_string($value)) {
1301 return ((string)(int)$value) === $value;
1308 * Returns host part from url.
1310 * @param string $url full url
1311 * @return string host, null if not found
1313 function get_host_from_url($url) {
1314 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1322 * Tests whether anything was returned by text editor
1324 * This function is useful for testing whether something you got back from
1325 * the HTML editor actually contains anything. Sometimes the HTML editor
1326 * appear to be empty, but actually you get back a <br> tag or something.
1328 * @param string $string a string containing HTML.
1329 * @return boolean does the string contain any actual content - that is text,
1330 * images, objects, etc.
1332 function html_is_blank($string) {
1333 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1337 * Set a key in global configuration
1339 * Set a key/value pair in both this session's {@link $CFG} global variable
1340 * and in the 'config' database table for future sessions.
1342 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1343 * In that case it doesn't affect $CFG.
1345 * A NULL value will delete the entry.
1347 * NOTE: this function is called from lib/db/upgrade.php
1349 * @param string $name the key to set
1350 * @param string $value the value to set (without magic quotes)
1351 * @param string $plugin (optional) the plugin scope, default null
1352 * @return bool true or exception
1354 function set_config($name, $value, $plugin=null) {
1357 if (empty($plugin)) {
1358 if (!array_key_exists($name, $CFG->config_php_settings)) {
1359 // So it's defined for this invocation at least.
1360 if (is_null($value)) {
1363 // Settings from db are always strings.
1364 $CFG->$name = (string)$value;
1368 if ($DB->get_field('config', 'name', array('name' => $name))) {
1369 if ($value === null) {
1370 $DB->delete_records('config', array('name' => $name));
1372 $DB->set_field('config', 'value', $value, array('name' => $name));
1375 if ($value !== null) {
1376 $config = new stdClass();
1377 $config->name = $name;
1378 $config->value = $value;
1379 $DB->insert_record('config', $config, false);
1382 if ($name === 'siteidentifier') {
1383 cache_helper::update_site_identifier($value);
1385 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1388 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1389 if ($value===null) {
1390 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1392 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1395 if ($value !== null) {
1396 $config = new stdClass();
1397 $config->plugin = $plugin;
1398 $config->name = $name;
1399 $config->value = $value;
1400 $DB->insert_record('config_plugins', $config, false);
1403 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1410 * Get configuration values from the global config table
1411 * or the config_plugins table.
1413 * If called with one parameter, it will load all the config
1414 * variables for one plugin, and return them as an object.
1416 * If called with 2 parameters it will return a string single
1417 * value or false if the value is not found.
1419 * NOTE: this function is called from lib/db/upgrade.php
1421 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1422 * that we need only fetch it once per request.
1423 * @param string $plugin full component name
1424 * @param string $name default null
1425 * @return mixed hash-like object or single value, return false no config found
1426 * @throws dml_exception
1428 function get_config($plugin, $name = null) {
1431 static $siteidentifier = null;
1433 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1434 $forced =& $CFG->config_php_settings;
1438 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1439 $forced =& $CFG->forced_plugin_settings[$plugin];
1446 if ($siteidentifier === null) {
1448 // This may fail during installation.
1449 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1450 // install the database.
1451 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1452 } catch (dml_exception $ex) {
1453 // Set siteidentifier to false. We don't want to trip this continually.
1454 $siteidentifier = false;
1459 if (!empty($name)) {
1460 if (array_key_exists($name, $forced)) {
1461 return (string)$forced[$name];
1462 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1463 return $siteidentifier;
1467 $cache = cache::make('core', 'config');
1468 $result = $cache->get($plugin);
1469 if ($result === false) {
1470 // The user is after a recordset.
1472 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1474 // This part is not really used any more, but anyway...
1475 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1477 $cache->set($plugin, $result);
1480 if (!empty($name)) {
1481 if (array_key_exists($name, $result)) {
1482 return $result[$name];
1487 if ($plugin === 'core') {
1488 $result['siteidentifier'] = $siteidentifier;
1491 foreach ($forced as $key => $value) {
1492 if (is_null($value) or is_array($value) or is_object($value)) {
1493 // We do not want any extra mess here, just real settings that could be saved in db.
1494 unset($result[$key]);
1496 // Convert to string as if it went through the DB.
1497 $result[$key] = (string)$value;
1501 return (object)$result;
1505 * Removes a key from global configuration.
1507 * NOTE: this function is called from lib/db/upgrade.php
1509 * @param string $name the key to set
1510 * @param string $plugin (optional) the plugin scope
1511 * @return boolean whether the operation succeeded.
1513 function unset_config($name, $plugin=null) {
1516 if (empty($plugin)) {
1518 $DB->delete_records('config', array('name' => $name));
1519 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1521 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1522 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1529 * Remove all the config variables for a given plugin.
1531 * NOTE: this function is called from lib/db/upgrade.php
1533 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1534 * @return boolean whether the operation succeeded.
1536 function unset_all_config_for_plugin($plugin) {
1538 // Delete from the obvious config_plugins first.
1539 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1540 // Next delete any suspect settings from config.
1541 $like = $DB->sql_like('name', '?', true, true, false, '|');
1542 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1543 $DB->delete_records_select('config', $like, $params);
1544 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1545 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1551 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1553 * All users are verified if they still have the necessary capability.
1555 * @param string $value the value of the config setting.
1556 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1557 * @param bool $includeadmins include administrators.
1558 * @return array of user objects.
1560 function get_users_from_config($value, $capability, $includeadmins = true) {
1561 if (empty($value) or $value === '$@NONE@$') {
1565 // We have to make sure that users still have the necessary capability,
1566 // it should be faster to fetch them all first and then test if they are present
1567 // instead of validating them one-by-one.
1568 $users = get_users_by_capability(context_system::instance(), $capability);
1569 if ($includeadmins) {
1570 $admins = get_admins();
1571 foreach ($admins as $admin) {
1572 $users[$admin->id] = $admin;
1576 if ($value === '$@ALL@$') {
1580 $result = array(); // Result in correct order.
1581 $allowed = explode(',', $value);
1582 foreach ($allowed as $uid) {
1583 if (isset($users[$uid])) {
1584 $user = $users[$uid];
1585 $result[$user->id] = $user;
1594 * Invalidates browser caches and cached data in temp.
1596 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1597 * {@link phpunit_util::reset_dataroot()}
1601 function purge_all_caches() {
1604 reset_text_filters_cache();
1605 js_reset_all_caches();
1606 theme_reset_all_caches();
1607 get_string_manager()->reset_caches();
1608 core_text::reset_caches();
1609 if (class_exists('core_plugin_manager')) {
1610 core_plugin_manager::reset_caches();
1613 // Bump up cacherev field for all courses.
1615 increment_revision_number('course', 'cacherev', '');
1616 } catch (moodle_exception $e) {
1617 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1620 $DB->reset_caches();
1621 cache_helper::purge_all();
1623 // Purge all other caches: rss, simplepie, etc.
1624 remove_dir($CFG->cachedir.'', true);
1626 // Make sure cache dir is writable, throws exception if not.
1627 make_cache_directory('');
1629 // This is the only place where we purge local caches, we are only adding files there.
1630 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1631 remove_dir($CFG->localcachedir, true);
1632 set_config('localcachedirpurged', time());
1633 make_localcache_directory('', true);
1634 \core\task\manager::clear_static_caches();
1638 * Get volatile flags
1640 * @param string $type
1641 * @param int $changedsince default null
1642 * @return array records array
1644 function get_cache_flags($type, $changedsince = null) {
1647 $params = array('type' => $type, 'expiry' => time());
1648 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1649 if ($changedsince !== null) {
1650 $params['changedsince'] = $changedsince;
1651 $sqlwhere .= " AND timemodified > :changedsince";
1654 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1655 foreach ($flags as $flag) {
1656 $cf[$flag->name] = $flag->value;
1663 * Get volatile flags
1665 * @param string $type
1666 * @param string $name
1667 * @param int $changedsince default null
1668 * @return string|false The cache flag value or false
1670 function get_cache_flag($type, $name, $changedsince=null) {
1673 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1675 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1676 if ($changedsince !== null) {
1677 $params['changedsince'] = $changedsince;
1678 $sqlwhere .= " AND timemodified > :changedsince";
1681 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1685 * Set a volatile flag
1687 * @param string $type the "type" namespace for the key
1688 * @param string $name the key to set
1689 * @param string $value the value to set (without magic quotes) - null will remove the flag
1690 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1691 * @return bool Always returns true
1693 function set_cache_flag($type, $name, $value, $expiry = null) {
1696 $timemodified = time();
1697 if ($expiry === null || $expiry < $timemodified) {
1698 $expiry = $timemodified + 24 * 60 * 60;
1700 $expiry = (int)$expiry;
1703 if ($value === null) {
1704 unset_cache_flag($type, $name);
1708 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1709 // This is a potential problem in DEBUG_DEVELOPER.
1710 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1711 return true; // No need to update.
1714 $f->expiry = $expiry;
1715 $f->timemodified = $timemodified;
1716 $DB->update_record('cache_flags', $f);
1718 $f = new stdClass();
1719 $f->flagtype = $type;
1722 $f->expiry = $expiry;
1723 $f->timemodified = $timemodified;
1724 $DB->insert_record('cache_flags', $f);
1730 * Removes a single volatile flag
1732 * @param string $type the "type" namespace for the key
1733 * @param string $name the key to set
1736 function unset_cache_flag($type, $name) {
1738 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1743 * Garbage-collect volatile flags
1745 * @return bool Always returns true
1747 function gc_cache_flags() {
1749 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1753 // USER PREFERENCE API.
1756 * Refresh user preference cache. This is used most often for $USER
1757 * object that is stored in session, but it also helps with performance in cron script.
1759 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1762 * @category preference
1764 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1765 * @param int $cachelifetime Cache life time on the current page (in seconds)
1766 * @throws coding_exception
1769 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1771 // Static cache, we need to check on each page load, not only every 2 minutes.
1772 static $loadedusers = array();
1774 if (!isset($user->id)) {
1775 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1778 if (empty($user->id) or isguestuser($user->id)) {
1779 // No permanent storage for not-logged-in users and guest.
1780 if (!isset($user->preference)) {
1781 $user->preference = array();
1788 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1789 // Already loaded at least once on this page. Are we up to date?
1790 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1791 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1794 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1795 // No change since the lastcheck on this page.
1796 $user->preference['_lastloaded'] = $timenow;
1801 // OK, so we have to reload all preferences.
1802 $loadedusers[$user->id] = true;
1803 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1804 $user->preference['_lastloaded'] = $timenow;
1808 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1810 * NOTE: internal function, do not call from other code.
1814 * @param integer $userid the user whose prefs were changed.
1816 function mark_user_preferences_changed($userid) {
1819 if (empty($userid) or isguestuser($userid)) {
1820 // No cache flags for guest and not-logged-in users.
1824 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1828 * Sets a preference for the specified user.
1830 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1833 * @category preference
1835 * @param string $name The key to set as preference for the specified user
1836 * @param string $value The value to set for the $name key in the specified user's
1837 * record, null means delete current value.
1838 * @param stdClass|int|null $user A moodle user object or id, null means current user
1839 * @throws coding_exception
1840 * @return bool Always true or exception
1842 function set_user_preference($name, $value, $user = null) {
1845 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1846 throw new coding_exception('Invalid preference name in set_user_preference() call');
1849 if (is_null($value)) {
1850 // Null means delete current.
1851 return unset_user_preference($name, $user);
1852 } else if (is_object($value)) {
1853 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1854 } else if (is_array($value)) {
1855 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1857 // Value column maximum length is 1333 characters.
1858 $value = (string)$value;
1859 if (core_text::strlen($value) > 1333) {
1860 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1863 if (is_null($user)) {
1865 } else if (isset($user->id)) {
1866 // It is a valid object.
1867 } else if (is_numeric($user)) {
1868 $user = (object)array('id' => (int)$user);
1870 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1873 check_user_preferences_loaded($user);
1875 if (empty($user->id) or isguestuser($user->id)) {
1876 // No permanent storage for not-logged-in users and guest.
1877 $user->preference[$name] = $value;
1881 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1882 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1883 // Preference already set to this value.
1886 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1889 $preference = new stdClass();
1890 $preference->userid = $user->id;
1891 $preference->name = $name;
1892 $preference->value = $value;
1893 $DB->insert_record('user_preferences', $preference);
1896 // Update value in cache.
1897 $user->preference[$name] = $value;
1899 // Set reload flag for other sessions.
1900 mark_user_preferences_changed($user->id);
1906 * Sets a whole array of preferences for the current user
1908 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1911 * @category preference
1913 * @param array $prefarray An array of key/value pairs to be set
1914 * @param stdClass|int|null $user A moodle user object or id, null means current user
1915 * @return bool Always true or exception
1917 function set_user_preferences(array $prefarray, $user = null) {
1918 foreach ($prefarray as $name => $value) {
1919 set_user_preference($name, $value, $user);
1925 * Unsets a preference completely by deleting it from the database
1927 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1930 * @category preference
1932 * @param string $name The key to unset as preference for the specified user
1933 * @param stdClass|int|null $user A moodle user object or id, null means current user
1934 * @throws coding_exception
1935 * @return bool Always true or exception
1937 function unset_user_preference($name, $user = null) {
1940 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1941 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1944 if (is_null($user)) {
1946 } else if (isset($user->id)) {
1947 // It is a valid object.
1948 } else if (is_numeric($user)) {
1949 $user = (object)array('id' => (int)$user);
1951 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1954 check_user_preferences_loaded($user);
1956 if (empty($user->id) or isguestuser($user->id)) {
1957 // No permanent storage for not-logged-in user and guest.
1958 unset($user->preference[$name]);
1963 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1965 // Delete the preference from cache.
1966 unset($user->preference[$name]);
1968 // Set reload flag for other sessions.
1969 mark_user_preferences_changed($user->id);
1975 * Used to fetch user preference(s)
1977 * If no arguments are supplied this function will return
1978 * all of the current user preferences as an array.
1980 * If a name is specified then this function
1981 * attempts to return that particular preference value. If
1982 * none is found, then the optional value $default is returned,
1985 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1988 * @category preference
1990 * @param string $name Name of the key to use in finding a preference value
1991 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1992 * @param stdClass|int|null $user A moodle user object or id, null means current user
1993 * @throws coding_exception
1994 * @return string|mixed|null A string containing the value of a single preference. An
1995 * array with all of the preferences or null
1997 function get_user_preferences($name = null, $default = null, $user = null) {
2000 if (is_null($name)) {
2002 } else if (is_numeric($name) or $name === '_lastloaded') {
2003 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2006 if (is_null($user)) {
2008 } else if (isset($user->id)) {
2009 // Is a valid object.
2010 } else if (is_numeric($user)) {
2011 $user = (object)array('id' => (int)$user);
2013 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2016 check_user_preferences_loaded($user);
2020 return $user->preference;
2021 } else if (isset($user->preference[$name])) {
2022 // The single string value.
2023 return $user->preference[$name];
2025 // Default value (null if not specified).
2030 // FUNCTIONS FOR HANDLING TIME.
2033 * Given Gregorian date parts in user time produce a GMT timestamp.
2037 * @param int $year The year part to create timestamp of
2038 * @param int $month The month part to create timestamp of
2039 * @param int $day The day part to create timestamp of
2040 * @param int $hour The hour part to create timestamp of
2041 * @param int $minute The minute part to create timestamp of
2042 * @param int $second The second part to create timestamp of
2043 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2044 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2045 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2046 * applied only if timezone is 99 or string.
2047 * @return int GMT timestamp
2049 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2050 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2051 $date->setDate((int)$year, (int)$month, (int)$day);
2052 $date->setTime((int)$hour, (int)$minute, (int)$second);
2054 $time = $date->getTimestamp();
2056 if ($time === false) {
2057 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2058 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2061 // Moodle BC DST stuff.
2063 $time += dst_offset_on($time, $timezone);
2071 * Format a date/time (seconds) as weeks, days, hours etc as needed
2073 * Given an amount of time in seconds, returns string
2074 * formatted nicely as weeks, days, hours etc as needed
2082 * @param int $totalsecs Time in seconds
2083 * @param stdClass $str Should be a time object
2084 * @return string A nicely formatted date/time string
2086 function format_time($totalsecs, $str = null) {
2088 $totalsecs = abs($totalsecs);
2091 // Create the str structure the slow way.
2092 $str = new stdClass();
2093 $str->day = get_string('day');
2094 $str->days = get_string('days');
2095 $str->hour = get_string('hour');
2096 $str->hours = get_string('hours');
2097 $str->min = get_string('min');
2098 $str->mins = get_string('mins');
2099 $str->sec = get_string('sec');
2100 $str->secs = get_string('secs');
2101 $str->year = get_string('year');
2102 $str->years = get_string('years');
2105 $years = floor($totalsecs/YEARSECS);
2106 $remainder = $totalsecs - ($years*YEARSECS);
2107 $days = floor($remainder/DAYSECS);
2108 $remainder = $totalsecs - ($days*DAYSECS);
2109 $hours = floor($remainder/HOURSECS);
2110 $remainder = $remainder - ($hours*HOURSECS);
2111 $mins = floor($remainder/MINSECS);
2112 $secs = $remainder - ($mins*MINSECS);
2114 $ss = ($secs == 1) ? $str->sec : $str->secs;
2115 $sm = ($mins == 1) ? $str->min : $str->mins;
2116 $sh = ($hours == 1) ? $str->hour : $str->hours;
2117 $sd = ($days == 1) ? $str->day : $str->days;
2118 $sy = ($years == 1) ? $str->year : $str->years;
2127 $oyears = $years .' '. $sy;
2130 $odays = $days .' '. $sd;
2133 $ohours = $hours .' '. $sh;
2136 $omins = $mins .' '. $sm;
2139 $osecs = $secs .' '. $ss;
2143 return trim($oyears .' '. $odays);
2146 return trim($odays .' '. $ohours);
2149 return trim($ohours .' '. $omins);
2152 return trim($omins .' '. $osecs);
2157 return get_string('now');
2161 * Returns a formatted string that represents a date in user time.
2165 * @param int $date the timestamp in UTC, as obtained from the database.
2166 * @param string $format strftime format. You should probably get this using
2167 * get_string('strftime...', 'langconfig');
2168 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2169 * not 99 then daylight saving will not be added.
2170 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2171 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2172 * If false then the leading zero is maintained.
2173 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2174 * @return string the formatted date/time.
2176 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2177 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2178 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2182 * Returns a formatted date ensuring it is UTF-8.
2184 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2185 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2187 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2188 * @param string $format strftime format.
2189 * @param int|float|string $tz the user timezone
2190 * @return string the formatted date/time.
2191 * @since Moodle 2.3.3
2193 function date_format_string($date, $format, $tz = 99) {
2196 $localewincharset = null;
2197 // Get the calendar type user is using.
2198 if ($CFG->ostype == 'WINDOWS') {
2199 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2200 $localewincharset = $calendartype->locale_win_charset();
2203 if ($localewincharset) {
2204 $format = core_text::convert($format, 'utf-8', $localewincharset);
2207 date_default_timezone_set(core_date::get_user_timezone($tz));
2208 $datestring = strftime($format, $date);
2209 core_date::set_default_server_timezone();
2211 if ($localewincharset) {
2212 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2219 * Given a $time timestamp in GMT (seconds since epoch),
2220 * returns an array that represents the Gregorian date in user time
2224 * @param int $time Timestamp in GMT
2225 * @param float|int|string $timezone user timezone
2226 * @return array An array that represents the date in user time
2228 function usergetdate($time, $timezone=99) {
2229 date_default_timezone_set(core_date::get_user_timezone($timezone));
2230 $result = getdate($time);
2231 core_date::set_default_server_timezone();
2237 * Given a GMT timestamp (seconds since epoch), offsets it by
2238 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2240 * NOTE: this function does not include DST properly,
2241 * you should use the PHP date stuff instead!
2245 * @param int $date Timestamp in GMT
2246 * @param float|int|string $timezone user timezone
2249 function usertime($date, $timezone=99) {
2250 $userdate = new DateTime('@' . $date);
2251 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2252 $dst = dst_offset_on($date, $timezone);
2254 return $date - $userdate->getOffset() + $dst;
2258 * Given a time, return the GMT timestamp of the most recent midnight
2259 * for the current user.
2263 * @param int $date Timestamp in GMT
2264 * @param float|int|string $timezone user timezone
2265 * @return int Returns a GMT timestamp
2267 function usergetmidnight($date, $timezone=99) {
2269 $userdate = usergetdate($date, $timezone);
2271 // Time of midnight of this user's day, in GMT.
2272 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2277 * Returns a string that prints the user's timezone
2281 * @param float|int|string $timezone user timezone
2284 function usertimezone($timezone=99) {
2285 $tz = core_date::get_user_timezone($timezone);
2286 return core_date::get_localised_timezone($tz);
2290 * Returns a float or a string which denotes the user's timezone
2291 * 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)
2292 * means that for this timezone there are also DST rules to be taken into account
2293 * Checks various settings and picks the most dominant of those which have a value
2297 * @param float|int|string $tz timezone to calculate GMT time offset before
2298 * calculating user timezone, 99 is default user timezone
2299 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2300 * @return float|string
2302 function get_user_timezone($tz = 99) {
2307 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2308 isset($USER->timezone) ? $USER->timezone : 99,
2309 isset($CFG->timezone) ? $CFG->timezone : 99,
2314 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2315 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2316 $tz = $next['value'];
2318 return is_numeric($tz) ? (float) $tz : $tz;
2322 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2323 * - Note: Daylight saving only works for string timezones and not for float.
2327 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2328 * @param int|float|string $strtimezone user timezone
2331 function dst_offset_on($time, $strtimezone = null) {
2332 $tz = core_date::get_user_timezone($strtimezone);
2333 $date = new DateTime('@' . $time);
2334 $date->setTimezone(new DateTimeZone($tz));
2335 if ($date->format('I') == '1') {
2336 if ($tz === 'Australia/Lord_Howe') {
2345 * Calculates when the day appears in specific month
2349 * @param int $startday starting day of the month
2350 * @param int $weekday The day when week starts (normally taken from user preferences)
2351 * @param int $month The month whose day is sought
2352 * @param int $year The year of the month whose day is sought
2355 function find_day_in_month($startday, $weekday, $month, $year) {
2356 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2358 $daysinmonth = days_in_month($month, $year);
2359 $daysinweek = count($calendartype->get_weekdays());
2361 if ($weekday == -1) {
2362 // Don't care about weekday, so return:
2363 // abs($startday) if $startday != -1
2364 // $daysinmonth otherwise.
2365 return ($startday == -1) ? $daysinmonth : abs($startday);
2368 // From now on we 're looking for a specific weekday.
2369 // Give "end of month" its actual value, since we know it.
2370 if ($startday == -1) {
2371 $startday = -1 * $daysinmonth;
2374 // Starting from day $startday, the sign is the direction.
2375 if ($startday < 1) {
2376 $startday = abs($startday);
2377 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2379 // This is the last such weekday of the month.
2380 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2381 if ($lastinmonth > $daysinmonth) {
2382 $lastinmonth -= $daysinweek;
2385 // Find the first such weekday <= $startday.
2386 while ($lastinmonth > $startday) {
2387 $lastinmonth -= $daysinweek;
2390 return $lastinmonth;
2392 $indexweekday = dayofweek($startday, $month, $year);
2394 $diff = $weekday - $indexweekday;
2396 $diff += $daysinweek;
2399 // This is the first such weekday of the month equal to or after $startday.
2400 $firstfromindex = $startday + $diff;
2402 return $firstfromindex;
2407 * Calculate the number of days in a given month
2411 * @param int $month The month whose day count is sought
2412 * @param int $year The year of the month whose day count is sought
2415 function days_in_month($month, $year) {
2416 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2417 return $calendartype->get_num_days_in_month($year, $month);
2421 * Calculate the position in the week of a specific calendar day
2425 * @param int $day The day of the date whose position in the week is sought
2426 * @param int $month The month of the date whose position in the week is sought
2427 * @param int $year The year of the date whose position in the week is sought
2430 function dayofweek($day, $month, $year) {
2431 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2432 return $calendartype->get_weekday($year, $month, $day);
2435 // USER AUTHENTICATION AND LOGIN.
2438 * Returns full login url.
2440 * @return string login url
2442 function get_login_url() {
2445 $url = "$CFG->wwwroot/login/index.php";
2447 if (!empty($CFG->loginhttps)) {
2448 $url = str_replace('http:', 'https:', $url);
2455 * This function checks that the current user is logged in and has the
2456 * required privileges
2458 * This function checks that the current user is logged in, and optionally
2459 * whether they are allowed to be in a particular course and view a particular
2461 * If they are not logged in, then it redirects them to the site login unless
2462 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2463 * case they are automatically logged in as guests.
2464 * If $courseid is given and the user is not enrolled in that course then the
2465 * user is redirected to the course enrolment page.
2466 * If $cm is given and the course module is hidden and the user is not a teacher
2467 * in the course then the user is redirected to the course home page.
2469 * When $cm parameter specified, this function sets page layout to 'module'.
2470 * You need to change it manually later if some other layout needed.
2472 * @package core_access
2475 * @param mixed $courseorid id of the course or course object
2476 * @param bool $autologinguest default true
2477 * @param object $cm course module object
2478 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2479 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2480 * in order to keep redirects working properly. MDL-14495
2481 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2482 * @return mixed Void, exit, and die depending on path
2483 * @throws coding_exception
2484 * @throws require_login_exception
2486 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2487 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2489 // Must not redirect when byteserving already started.
2490 if (!empty($_SERVER['HTTP_RANGE'])) {
2491 $preventredirect = true;
2495 // We cannot redirect for AJAX scripts either.
2496 $preventredirect = true;
2499 // Setup global $COURSE, themes, language and locale.
2500 if (!empty($courseorid)) {
2501 if (is_object($courseorid)) {
2502 $course = $courseorid;
2503 } else if ($courseorid == SITEID) {
2504 $course = clone($SITE);
2506 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2509 if ($cm->course != $course->id) {
2510 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2512 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2513 if (!($cm instanceof cm_info)) {
2514 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2515 // db queries so this is not really a performance concern, however it is obviously
2516 // better if you use get_fast_modinfo to get the cm before calling this.
2517 $modinfo = get_fast_modinfo($course);
2518 $cm = $modinfo->get_cm($cm->id);
2522 // Do not touch global $COURSE via $PAGE->set_course(),
2523 // the reasons is we need to be able to call require_login() at any time!!
2526 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2530 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2531 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2532 // risk leading the user back to the AJAX request URL.
2533 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2534 $setwantsurltome = false;
2537 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2538 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2539 if ($preventredirect) {
2540 throw new require_login_session_timeout_exception();
2542 if ($setwantsurltome) {
2543 $SESSION->wantsurl = qualified_me();
2545 redirect(get_login_url());
2549 // If the user is not even logged in yet then make sure they are.
2550 if (!isloggedin()) {
2551 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2552 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2553 // Misconfigured site guest, just redirect to login page.
2554 redirect(get_login_url());
2555 exit; // Never reached.
2557 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2558 complete_user_login($guest);
2559 $USER->autologinguest = true;
2560 $SESSION->lang = $lang;
2562 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2563 if ($preventredirect) {
2564 throw new require_login_exception('You are not logged in');
2567 if ($setwantsurltome) {
2568 $SESSION->wantsurl = qualified_me();
2571 $referer = get_local_referer(false);
2572 if (!empty($referer)) {
2573 $SESSION->fromurl = $referer;
2576 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2577 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2578 foreach($authsequence as $authname) {
2579 $authplugin = get_auth_plugin($authname);
2580 $authplugin->pre_loginpage_hook();
2586 // If we're still not logged in then go to the login page
2587 if (!isloggedin()) {
2588 redirect(get_login_url());
2589 exit; // Never reached.
2594 // Loginas as redirection if needed.
2595 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2596 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2597 if ($USER->loginascontext->instanceid != $course->id) {
2598 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2603 // Check whether the user should be changing password (but only if it is REALLY them).
2604 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2605 $userauth = get_auth_plugin($USER->auth);
2606 if ($userauth->can_change_password() and !$preventredirect) {
2607 if ($setwantsurltome) {
2608 $SESSION->wantsurl = qualified_me();
2610 if ($changeurl = $userauth->change_password_url()) {
2611 // Use plugin custom url.
2612 redirect($changeurl);
2614 // Use moodle internal method.
2615 if (empty($CFG->loginhttps)) {
2616 redirect($CFG->wwwroot .'/login/change_password.php');
2618 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2619 redirect($wwwroot .'/login/change_password.php');
2623 print_error('nopasswordchangeforced', 'auth');
2627 // Check that the user account is properly set up.
2628 if (user_not_fully_set_up($USER)) {
2629 if ($preventredirect) {
2630 throw new require_login_exception('User not fully set-up');
2632 if ($setwantsurltome) {
2633 $SESSION->wantsurl = qualified_me();
2635 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2638 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2641 // Do not bother admins with any formalities.
2642 if (is_siteadmin()) {
2643 // Set the global $COURSE.
2645 $PAGE->set_cm($cm, $course);
2646 $PAGE->set_pagelayout('incourse');
2647 } else if (!empty($courseorid)) {
2648 $PAGE->set_course($course);
2650 // Set accesstime or the user will appear offline which messes up messaging.
2651 user_accesstime_log($course->id);
2655 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2656 if (!$USER->policyagreed and !is_siteadmin()) {
2657 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2658 if ($preventredirect) {
2659 throw new require_login_exception('Policy not agreed');
2661 if ($setwantsurltome) {
2662 $SESSION->wantsurl = qualified_me();
2664 redirect($CFG->wwwroot .'/user/policy.php');
2665 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2666 if ($preventredirect) {
2667 throw new require_login_exception('Policy not agreed');
2669 if ($setwantsurltome) {
2670 $SESSION->wantsurl = qualified_me();
2672 redirect($CFG->wwwroot .'/user/policy.php');
2676 // Fetch the system context, the course context, and prefetch its child contexts.
2677 $sysctx = context_system::instance();
2678 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2680 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2685 // If the site is currently under maintenance, then print a message.
2686 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2687 if ($preventredirect) {
2688 throw new require_login_exception('Maintenance in progress');
2691 print_maintenance_message();
2694 // Make sure the course itself is not hidden.
2695 if ($course->id == SITEID) {
2696 // Frontpage can not be hidden.
2698 if (is_role_switched($course->id)) {
2699 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2701 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2702 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2703 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2704 if ($preventredirect) {
2705 throw new require_login_exception('Course is hidden');
2707 $PAGE->set_context(null);
2708 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2709 // the navigation will mess up when trying to find it.
2710 navigation_node::override_active_url(new moodle_url('/'));
2711 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2716 // Is the user enrolled?
2717 if ($course->id == SITEID) {
2718 // Everybody is enrolled on the frontpage.
2720 if (\core\session\manager::is_loggedinas()) {
2721 // Make sure the REAL person can access this course first.
2722 $realuser = \core\session\manager::get_realuser();
2723 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2724 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2725 if ($preventredirect) {
2726 throw new require_login_exception('Invalid course login-as access');
2728 $PAGE->set_context(null);
2729 echo $OUTPUT->header();
2730 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2736 if (is_role_switched($course->id)) {
2737 // Ok, user had to be inside this course before the switch.
2740 } else if (is_viewing($coursecontext, $USER)) {
2741 // Ok, no need to mess with enrol.
2745 if (isset($USER->enrol['enrolled'][$course->id])) {
2746 if ($USER->enrol['enrolled'][$course->id] > time()) {
2748 if (isset($USER->enrol['tempguest'][$course->id])) {
2749 unset($USER->enrol['tempguest'][$course->id]);
2750 remove_temp_course_roles($coursecontext);
2754 unset($USER->enrol['enrolled'][$course->id]);
2757 if (isset($USER->enrol['tempguest'][$course->id])) {
2758 if ($USER->enrol['tempguest'][$course->id] == 0) {
2760 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2764 unset($USER->enrol['tempguest'][$course->id]);
2765 remove_temp_course_roles($coursecontext);
2771 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2772 if ($until !== false) {
2773 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2775 $until = ENROL_MAX_TIMESTAMP;
2777 $USER->enrol['enrolled'][$course->id] = $until;
2781 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2782 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2783 $enrols = enrol_get_plugins(true);
2784 // First ask all enabled enrol instances in course if they want to auto enrol user.
2785 foreach ($instances as $instance) {
2786 if (!isset($enrols[$instance->enrol])) {
2789 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2790 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2791 if ($until !== false) {
2793 $until = ENROL_MAX_TIMESTAMP;
2795 $USER->enrol['enrolled'][$course->id] = $until;
2800 // If not enrolled yet try to gain temporary guest access.
2802 foreach ($instances as $instance) {
2803 if (!isset($enrols[$instance->enrol])) {
2806 // Get a duration for the guest access, a timestamp in the future or false.
2807 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2808 if ($until !== false and $until > time()) {
2809 $USER->enrol['tempguest'][$course->id] = $until;
2820 if ($preventredirect) {
2821 throw new require_login_exception('Not enrolled');
2823 if ($setwantsurltome) {
2824 $SESSION->wantsurl = qualified_me();
2826 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2830 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2831 if ($cm && !$cm->uservisible) {
2832 if ($preventredirect) {
2833 throw new require_login_exception('Activity is hidden');
2835 if ($course->id != SITEID) {
2836 $url = new moodle_url('/course/view.php', array('id' => $course->id));
2838 $url = new moodle_url('/');
2840 redirect($url, get_string('activityiscurrentlyhidden'));
2843 // Set the global $COURSE.
2845 $PAGE->set_cm($cm, $course);
2846 $PAGE->set_pagelayout('incourse');
2847 } else if (!empty($courseorid)) {
2848 $PAGE->set_course($course);
2851 // Finally access granted, update lastaccess times.
2852 user_accesstime_log($course->id);
2857 * This function just makes sure a user is logged out.
2859 * @package core_access
2862 function require_logout() {
2865 if (!isloggedin()) {
2866 // This should not happen often, no need for hooks or events here.
2867 \core\session\manager::terminate_current();
2871 // Execute hooks before action.
2872 $authplugins = array();
2873 $authsequence = get_enabled_auth_plugins();
2874 foreach ($authsequence as $authname) {
2875 $authplugins[$authname] = get_auth_plugin($authname);
2876 $authplugins[$authname]->prelogout_hook();
2879 // Store info that gets removed during logout.
2880 $sid = session_id();
2881 $event = \core\event\user_loggedout::create(
2883 'userid' => $USER->id,
2884 'objectid' => $USER->id,
2885 'other' => array('sessionid' => $sid),
2888 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2889 $event->add_record_snapshot('sessions', $session);
2892 // Clone of $USER object to be used by auth plugins.
2893 $user = fullclone($USER);
2895 // Delete session record and drop $_SESSION content.
2896 \core\session\manager::terminate_current();
2898 // Trigger event AFTER action.
2901 // Hook to execute auth plugins redirection after event trigger.
2902 foreach ($authplugins as $authplugin) {
2903 $authplugin->postlogout_hook($user);
2908 * Weaker version of require_login()
2910 * This is a weaker version of {@link require_login()} which only requires login
2911 * when called from within a course rather than the site page, unless
2912 * the forcelogin option is turned on.
2913 * @see require_login()
2915 * @package core_access
2918 * @param mixed $courseorid The course object or id in question
2919 * @param bool $autologinguest Allow autologin guests if that is wanted
2920 * @param object $cm Course activity module if known
2921 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2922 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2923 * in order to keep redirects working properly. MDL-14495
2924 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2926 * @throws coding_exception
2928 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2929 global $CFG, $PAGE, $SITE;
2930 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2931 or (!is_object($courseorid) and $courseorid == SITEID));
2932 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2933 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2934 // db queries so this is not really a performance concern, however it is obviously
2935 // better if you use get_fast_modinfo to get the cm before calling this.
2936 if (is_object($courseorid)) {
2937 $course = $courseorid;
2939 $course = clone($SITE);
2941 $modinfo = get_fast_modinfo($course);
2942 $cm = $modinfo->get_cm($cm->id);
2944 if (!empty($CFG->forcelogin)) {
2945 // Login required for both SITE and courses.
2946 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2948 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2949 // Always login for hidden activities.
2950 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2952 } else if ($issite) {
2953 // Login for SITE not required.
2954 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
2955 if (!empty($courseorid)) {
2956 if (is_object($courseorid)) {
2957 $course = $courseorid;
2959 $course = clone $SITE;
2962 if ($cm->course != $course->id) {
2963 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2965 $PAGE->set_cm($cm, $course);
2966 $PAGE->set_pagelayout('incourse');
2968 $PAGE->set_course($course);
2971 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
2972 $PAGE->set_course($PAGE->course);
2974 user_accesstime_log(SITEID);
2978 // Course login always required.
2979 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2984 * Require key login. Function terminates with error if key not found or incorrect.
2986 * @uses NO_MOODLE_COOKIES
2987 * @uses PARAM_ALPHANUM
2988 * @param string $script unique script identifier
2989 * @param int $instance optional instance id
2990 * @return int Instance ID
2992 function require_user_key_login($script, $instance=null) {
2995 if (!NO_MOODLE_COOKIES) {
2996 print_error('sessioncookiesdisable');
3000 \core\session\manager::write_close();
3002 $keyvalue = required_param('key', PARAM_ALPHANUM);
3004 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3005 print_error('invalidkey');
3008 if (!empty($key->validuntil) and $key->validuntil < time()) {
3009 print_error('expiredkey');
3012 if ($key->iprestriction) {
3013 $remoteaddr = getremoteaddr(null);
3014 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3015 print_error('ipmismatch');
3019 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3020 print_error('invaliduserid');
3023 // Emulate normal session.
3024 enrol_check_plugins($user);
3025 \core\session\manager::set_user($user);
3027 // Note we are not using normal login.
3028 if (!defined('USER_KEY_LOGIN')) {
3029 define('USER_KEY_LOGIN', true);
3032 // Return instance id - it might be empty.
3033 return $key->instance;
3037 * Creates a new private user access key.
3039 * @param string $script unique target identifier
3040 * @param int $userid
3041 * @param int $instance optional instance id
3042 * @param string $iprestriction optional ip restricted access
3043 * @param int $validuntil key valid only until given data
3044 * @return string access key value
3046 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3049 $key = new stdClass();
3050 $key->script = $script;
3051 $key->userid = $userid;
3052 $key->instance = $instance;
3053 $key->iprestriction = $iprestriction;
3054 $key->validuntil = $validuntil;
3055 $key->timecreated = time();
3057 // Something long and unique.
3058 $key->value = md5($userid.'_'.time().random_string(40));
3059 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3061 $key->value = md5($userid.'_'.time().random_string(40));
3063 $DB->insert_record('user_private_key', $key);
3068 * Delete the user's new private user access keys for a particular script.
3070 * @param string $script unique target identifier
3071 * @param int $userid
3074 function delete_user_key($script, $userid) {
3076 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3080 * Gets a private user access key (and creates one if one doesn't exist).
3082 * @param string $script unique target identifier
3083 * @param int $userid
3084 * @param int $instance optional instance id
3085 * @param string $iprestriction optional ip restricted access
3086 * @param int $validuntil key valid only until given date
3087 * @return string access key value
3089 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3092 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3093 'instance' => $instance, 'iprestriction' => $iprestriction,
3094 'validuntil' => $validuntil))) {
3097 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3103 * Modify the user table by setting the currently logged in user's last login to now.
3105 * @return bool Always returns true
3107 function update_user_login_times() {
3110 if (isguestuser()) {
3111 // Do not update guest access times/ips for performance.
3117 $user = new stdClass();
3118 $user->id = $USER->id;
3120 // Make sure all users that logged in have some firstaccess.
3121 if ($USER->firstaccess == 0) {
3122 $USER->firstaccess = $user->firstaccess = $now;
3125 // Store the previous current as lastlogin.
3126 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3128 $USER->currentlogin = $user->currentlogin = $now;
3130 // Function user_accesstime_log() may not update immediately, better do it here.
3131 $USER->lastaccess = $user->lastaccess = $now;
3132 $USER->lastip = $user->lastip = getremoteaddr();
3134 // Note: do not call user_update_user() here because this is part of the login process,
3135 // the login event means that these fields were updated.
3136 $DB->update_record('user', $user);
3141 * Determines if a user has completed setting up their account.
3143 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3146 function user_not_fully_set_up($user) {
3147 if (isguestuser($user)) {
3150 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3154 * Check whether the user has exceeded the bounce threshold
3156 * @param stdClass $user A {@link $USER} object
3157 * @return bool true => User has exceeded bounce threshold
3159 function over_bounce_threshold($user) {
3162 if (empty($CFG->handlebounces)) {
3166 if (empty($user->id)) {
3167 // No real (DB) user, nothing to do here.
3171 // Set sensible defaults.
3172 if (empty($CFG->minbounces)) {
3173 $CFG->minbounces = 10;
3175 if (empty($CFG->bounceratio)) {
3176 $CFG->bounceratio = .20;
3180 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3181 $bouncecount = $bounce->value;
3183 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3184 $sendcount = $send->value;
3186 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3190 * Used to increment or reset email sent count
3192 * @param stdClass $user object containing an id
3193 * @param bool $reset will reset the count to 0
3196 function set_send_count($user, $reset=false) {
3199 if (empty($user->id)) {
3200 // No real (DB) user, nothing to do here.
3204 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3205 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3206 $DB->update_record('user_preferences', $pref);
3207 } else if (!empty($reset)) {
3208 // If it's not there and we're resetting, don't bother. Make a new one.
3209 $pref = new stdClass();
3210 $pref->name = 'email_send_count';
3212 $pref->userid = $user->id;
3213 $DB->insert_record('user_preferences', $pref, false);
3218 * Increment or reset user's email bounce count
3220 * @param stdClass $user object containing an id
3221 * @param bool $reset will reset the count to 0
3223 function set_bounce_count($user, $reset=false) {
3226 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3227 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3228 $DB->update_record('user_preferences', $pref);
3229 } else if (!empty($reset)) {
3230 // If it's not there and we're resetting, don't bother. Make a new one.
3231 $pref = new stdClass();
3232 $pref->name = 'email_bounce_count';
3234 $pref->userid = $user->id;
3235 $DB->insert_record('user_preferences', $pref, false);
3240 * Determines if the logged in user is currently moving an activity
3242 * @param int $courseid The id of the course being tested
3245 function ismoving($courseid) {
3248 if (!empty($USER->activitycopy)) {
3249 return ($USER->activitycopycourse == $courseid);
3255 * Returns a persons full name
3257 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3258 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3261 * @param stdClass $user A {@link $USER} object to get full name of.
3262 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3265 function fullname($user, $override=false) {
3266 global $CFG, $SESSION;
3268 if (!isset($user->firstname) and !isset($user->lastname)) {
3272 // Get all of the name fields.
3273 $allnames = get_all_user_name_fields();
3274 if ($CFG->debugdeveloper) {
3275 foreach ($allnames as $allname) {
3276 if (!property_exists($user, $allname)) {
3277 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3278 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3279 // Message has been sent, no point in sending the message multiple times.
3286 if (!empty($CFG->forcefirstname)) {
3287 $user->firstname = $CFG->forcefirstname;
3289 if (!empty($CFG->forcelastname)) {
3290 $user->lastname = $CFG->forcelastname;
3294 if (!empty($SESSION->fullnamedisplay)) {
3295 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3299 // If the fullnamedisplay setting is available, set the template to that.
3300 if (isset($CFG->fullnamedisplay)) {
3301 $template = $CFG->fullnamedisplay;
3303 // If the template is empty, or set to language, return the language string.
3304 if ((empty($template) || $template == 'language') && !$override) {
3305 return get_string('fullnamedisplay', null, $user);
3308 // Check to see if we are displaying according to the alternative full name format.
3310 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3311 // Default to show just the user names according to the fullnamedisplay string.
3312 return get_string('fullnamedisplay', null, $user);
3314 // If the override is true, then change the template to use the complete name.
3315 $template = $CFG->alternativefullnameformat;
3319 $requirednames = array();
3320 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3321 foreach ($allnames as $allname) {
3322 if (strpos($template, $allname) !== false) {
3323 $requirednames[] = $allname;
3327 $displayname = $template;
3328 // Switch in the actual data into the template.
3329 foreach ($requirednames as $altname) {
3330 if (isset($user->$altname)) {
3331 // Using empty() on the below if statement causes breakages.
3332 if ((string)$user->$altname == '') {
3333 $displayname = str_replace($altname, 'EMPTY', $displayname);
3335 $displayname = str_replace($altname, $user->$altname, $displayname);
3338 $displayname = str_replace($altname, 'EMPTY', $displayname);
3341 // Tidy up any misc. characters (Not perfect, but gets most characters).
3342 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3343 // katakana and parenthesis.
3344 $patterns = array();
3345 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3346 // filled in by a user.
3347 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3348 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3349 // This regular expression is to remove any double spaces in the display name.
3350 $patterns[] = '/\s{2,}/u';
3351 foreach ($patterns as $pattern) {
3352 $displayname = preg_replace($pattern, ' ', $displayname);
3355 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3356 $displayname = trim($displayname);
3357 if (empty($displayname)) {
3358 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3359 // people in general feel is a good setting to fall back on.
3360 $displayname = $user->firstname;
3362 return $displayname;
3366 * A centralised location for the all name fields. Returns an array / sql string snippet.
3368 * @param bool $returnsql True for an sql select field snippet.
3369 * @param string $tableprefix table query prefix to use in front of each field.
3370 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3371 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3372 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3373 * @return array|string All name fields.
3375 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3376 // This array is provided in this order because when called by fullname() (above) if firstname is before
3377 // firstnamephonetic str_replace() will change the wrong placeholder.
3378 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3379 'lastnamephonetic' => 'lastnamephonetic',
3380 'middlename' => 'middlename',
3381 'alternatename' => 'alternatename',
3382 'firstname' => 'firstname',
3383 'lastname' => 'lastname');
3385 // Let's add a prefix to the array of user name fields if provided.
3387 foreach ($alternatenames as $key => $altname) {
3388 $alternatenames[$key] = $prefix . $altname;
3392 // If we want the end result to have firstname and lastname at the front / top of the result.
3394 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3395 for ($i = 0; $i < 2; $i++) {
3396 // Get the last element.
3397 $lastelement = end($alternatenames);
3398 // Remove it from the array.
3399 unset($alternatenames[$lastelement]);
3400 // Put the element back on the top of the array.
3401 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3405 // Create an sql field snippet if requested.
3409 foreach ($alternatenames as $key => $altname) {
3410 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3413 foreach ($alternatenames as $key => $altname) {
3414 $alternatenames[$key] = $tableprefix . '.' . $altname;
3418 $alternatenames = implode(',', $alternatenames);
3420 return $alternatenames;
3424 * Reduces lines of duplicated code for getting user name fields.
3426 * See also {@link user_picture::unalias()}
3428 * @param object $addtoobject Object to add user name fields to.
3429 * @param object $secondobject Object that contains user name field information.
3430 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3431 * @param array $additionalfields Additional fields to be matched with data in the second object.
3432 * The key can be set to the user table field name.
3433 * @return object User name fields.
3435 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3436 $fields = get_all_user_name_fields(false, null, $prefix);
3437 if ($additionalfields) {
3438 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3439 // the key is a number and then sets the key to the array value.
3440 foreach ($additionalfields as $key => $value) {
3441 if (is_numeric($key)) {
3442 $additionalfields[$value] = $prefix . $value;
3443 unset($additionalfields[$key]);
3445 $additionalfields[$key] = $prefix . $value;
3448 $fields = array_merge($fields, $additionalfields);
3450 foreach ($fields as $key => $field) {
3451 // Important that we have all of the user name fields present in the object that we are sending back.
3452 $addtoobject->$key = '';
3453 if (isset($secondobject->$field)) {
3454 $addtoobject->$key = $secondobject->$field;
3457 return $addtoobject;
3461 * Returns an array of values in order of occurance in a provided string.
3462 * The key in the result is the character postion in the string.
3464 * @param array $values Values to be found in the string format
3465 * @param string $stringformat The string which may contain values being searched for.
3466 * @return array An array of values in order according to placement in the string format.
3468 function order_in_string($values, $stringformat) {
3469 $valuearray = array();
3470 foreach ($values as $value) {
3471 $pattern = "/$value\b/";
3472 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3473 if (preg_match($pattern, $stringformat)) {
3474 $replacement = "thing";
3475 // Replace the value with something more unique to ensure we get the right position when using strpos().
3476 $newformat = preg_replace($pattern, $replacement, $stringformat);
3477 $position = strpos($newformat, $replacement);
3478 $valuearray[$position] = $value;
3486 * Checks if current user is shown any extra fields when listing users.
3488 * @param object $context Context
3489 * @param array $already Array of fields that we're going to show anyway
3490 * so don't bother listing them
3491 * @return array Array of field names from user table, not including anything
3492 * listed in $already
3494 function get_extra_user_fields($context, $already = array()) {
3497 // Only users with permission get the extra fields.
3498 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3502 // Split showuseridentity on comma.
3503 if (empty($CFG->showuseridentity)) {
3504 // Explode gives wrong result with empty string.
3507 $extra = explode(',', $CFG->showuseridentity);
3510 foreach ($extra as $key => $field) {
3511 if (in_array($field, $already)) {
3512 unset($extra[$key]);
3517 // For consistency, if entries are removed from array, renumber it
3518 // so they are numbered as you would expect.
3519 $extra = array_merge($extra);
3525 * If the current user is to be shown extra user fields when listing or
3526 * selecting users, returns a string suitable for including in an SQL select
3527 * clause to retrieve those fields.
3529 * @param context $context Context
3530 * @param string $alias Alias of user table, e.g. 'u' (default none)
3531 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3532 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3533 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3535 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3536 $fields = get_extra_user_fields($context, $already);
3538 // Add punctuation for alias.
3539 if ($alias !== '') {
3542 foreach ($fields as $field) {
3543 $result .= ', ' . $alias . $field;
3545 $result .= ' AS ' . $prefix . $field;
3552 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3553 * @param string $field Field name, e.g. 'phone1'
3554 * @return string Text description taken from language file, e.g. 'Phone number'
3556 function get_user_field_name($field) {
3557 // Some fields have language strings which are not the same as field name.
3560 return get_string('webpage');
3563 return get_string('icqnumber');
3566 return get_string('skypeid');
3569 return get_string('aimid');
3572 return get_string('yahooid');
3575 return get_string('msnid');
3578 // Otherwise just use the same lang string.
3579 return get_string($field);
3583 * Returns whether a given authentication plugin exists.
3585 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3586 * @return boolean Whether the plugin is available.
3588 function exists_auth_plugin($auth) {
3591 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3592 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3598 * Checks if a given plugin is in the list of enabled authentication plugins.
3600 * @param string $auth Authentication plugin.
3601 * @return boolean Whether the plugin is enabled.
3603 function is_enabled_auth($auth) {
3608 $enabled = get_enabled_auth_plugins();
3610 return in_array($auth, $enabled);
3614 * Returns an authentication plugin instance.
3616 * @param string $auth name of authentication plugin
3617 * @return auth_plugin_base An instance of the required authentication plugin.
3619 function get_auth_plugin($auth) {
3622 // Check the plugin exists first.
3623 if (! exists_auth_plugin($auth)) {
3624 print_error('authpluginnotfound', 'debug', '', $auth);
3627 // Return auth plugin instance.
3628 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3629 $class = "auth_plugin_$auth";
3634 * Returns array of active auth plugins.
3636 * @param bool $fix fix $CFG->auth if needed
3639 function get_enabled_auth_plugins($fix=false) {
3642 $default = array('manual', 'nologin');
3644 if (empty($CFG->auth)) {
3647 $auths = explode(',', $CFG->auth);
3651 $auths = array_unique($auths);
3652 foreach ($auths as $k => $authname) {
3653 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {