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. //////////////
77 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
79 define('PARAM_ALPHA', 'alpha');
82 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
83 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
85 define('PARAM_ALPHAEXT', 'alphaext');
88 * PARAM_ALPHANUM - expected numbers and letters only.
90 define('PARAM_ALPHANUM', 'alphanum');
93 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
95 define('PARAM_ALPHANUMEXT', 'alphanumext');
98 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
100 define('PARAM_AUTH', 'auth');
103 * PARAM_BASE64 - Base 64 encoded format
105 define('PARAM_BASE64', 'base64');
108 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
110 define('PARAM_BOOL', 'bool');
113 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
114 * checked against the list of capabilities in the database.
116 define('PARAM_CAPABILITY', 'capability');
119 * PARAM_CLEANHTML - cleans submitted HTML code. use only for text in HTML format. This cleaning may fix xhtml strictness too.
121 define('PARAM_CLEANHTML', 'cleanhtml');
124 * PARAM_EMAIL - an email address following the RFC
126 define('PARAM_EMAIL', 'email');
129 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
131 define('PARAM_FILE', 'file');
134 * PARAM_FLOAT - a real/floating point number.
136 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
137 * It does not work for languages that use , as a decimal separator.
138 * Instead, do something like
139 * $rawvalue = required_param('name', PARAM_RAW);
140 * // ... other code including require_login, which sets current lang ...
141 * $realvalue = unformat_float($rawvalue);
142 * // ... then use $realvalue
144 define('PARAM_FLOAT', 'float');
147 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
149 define('PARAM_HOST', 'host');
152 * PARAM_INT - integers only, use when expecting only numbers.
154 define('PARAM_INT', 'int');
157 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
159 define('PARAM_LANG', 'lang');
162 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
164 define('PARAM_LOCALURL', 'localurl');
167 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
169 define('PARAM_NOTAGS', 'notags');
172 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
173 * note: the leading slash is not removed, window drive letter is not allowed
175 define('PARAM_PATH', 'path');
178 * PARAM_PEM - Privacy Enhanced Mail format
180 define('PARAM_PEM', 'pem');
183 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
185 define('PARAM_PERMISSION', 'permission');
188 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
190 define('PARAM_RAW', 'raw');
193 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
195 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
198 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
200 define('PARAM_SAFEDIR', 'safedir');
203 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
205 define('PARAM_SAFEPATH', 'safepath');
208 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
210 define('PARAM_SEQUENCE', 'sequence');
213 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
215 define('PARAM_TAG', 'tag');
218 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
220 define('PARAM_TAGLIST', 'taglist');
223 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
225 define('PARAM_TEXT', 'text');
228 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
230 define('PARAM_THEME', 'theme');
233 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
235 define('PARAM_URL', 'url');
238 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user accounts, do NOT use when syncing with external systems!!
240 define('PARAM_USERNAME', 'username');
243 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
245 define('PARAM_STRINGID', 'stringid');
247 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
249 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
250 * It was one of the first types, that is why it is abused so much ;-)
251 * @deprecated since 2.0
253 define('PARAM_CLEAN', 'clean');
256 * PARAM_INTEGER - deprecated alias for PARAM_INT
257 * @deprecated since 2.0
259 define('PARAM_INTEGER', 'int');
262 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
263 * @deprecated since 2.0
265 define('PARAM_NUMBER', 'float');
268 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
269 * NOTE: originally alias for PARAM_APLHA
270 * @deprecated since 2.0
272 define('PARAM_ACTION', 'alphanumext');
275 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
276 * NOTE: originally alias for PARAM_APLHA
277 * @deprecated since 2.0
279 define('PARAM_FORMAT', 'alphanumext');
282 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
283 * @deprecated since 2.0
285 define('PARAM_MULTILANG', 'text');
288 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
289 * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
290 * America/Port-au-Prince)
292 define('PARAM_TIMEZONE', 'timezone');
295 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
297 define('PARAM_CLEANFILE', 'file');
300 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
301 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
302 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
303 * NOTE: numbers and underscores are strongly discouraged in plugin names!
305 define('PARAM_COMPONENT', 'component');
308 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
309 * It is usually used together with context id and component.
310 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
312 define('PARAM_AREA', 'area');
315 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
316 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
317 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
319 define('PARAM_PLUGIN', 'plugin');
325 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
327 define('VALUE_REQUIRED', 1);
330 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
332 define('VALUE_OPTIONAL', 2);
335 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
337 define('VALUE_DEFAULT', 0);
340 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
342 define('NULL_NOT_ALLOWED', false);
345 * NULL_ALLOWED - the parameter can be set to null in the database
347 define('NULL_ALLOWED', true);
351 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
353 define('PAGE_COURSE_VIEW', 'course-view');
355 /** Get remote addr constant */
356 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
357 /** Get remote addr constant */
358 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
360 /// Blog access level constant declaration ///
361 define ('BLOG_USER_LEVEL', 1);
362 define ('BLOG_GROUP_LEVEL', 2);
363 define ('BLOG_COURSE_LEVEL', 3);
364 define ('BLOG_SITE_LEVEL', 4);
365 define ('BLOG_GLOBAL_LEVEL', 5);
370 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
371 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
372 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
374 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
376 define('TAG_MAX_LENGTH', 50);
378 /// Password policy constants ///
379 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
380 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
381 define ('PASSWORD_DIGITS', '0123456789');
382 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
384 /// Feature constants ///
385 // Used for plugin_supports() to report features that are, or are not, supported by a module.
387 /** True if module can provide a grade */
388 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
389 /** True if module supports outcomes */
390 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
391 /** True if module supports advanced grading methods */
392 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
393 /** True if module controls the grade visibility over the gradebook */
394 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
395 /** True if module supports plagiarism plugins */
396 define('FEATURE_PLAGIARISM', 'plagiarism');
398 /** True if module has code to track whether somebody viewed it */
399 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
400 /** True if module has custom completion rules */
401 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
403 /** True if module has no 'view' page (like label) */
404 define('FEATURE_NO_VIEW_LINK', 'viewlink');
405 /** True if module supports outcomes */
406 define('FEATURE_IDNUMBER', 'idnumber');
407 /** True if module supports groups */
408 define('FEATURE_GROUPS', 'groups');
409 /** True if module supports groupings */
410 define('FEATURE_GROUPINGS', 'groupings');
411 /** True if module supports groupmembersonly */
412 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
414 /** Type of module */
415 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
416 /** True if module supports intro editor */
417 define('FEATURE_MOD_INTRO', 'mod_intro');
418 /** True if module has default completion */
419 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
421 define('FEATURE_COMMENT', 'comment');
423 define('FEATURE_RATE', 'rate');
424 /** True if module supports backup/restore of moodle2 format */
425 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
427 /** True if module can show description on course main page */
428 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
430 /** Unspecified module archetype */
431 define('MOD_ARCHETYPE_OTHER', 0);
432 /** Resource-like type module */
433 define('MOD_ARCHETYPE_RESOURCE', 1);
434 /** Assignment module archetype */
435 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
436 /** System (not user-addable) module archetype */
437 define('MOD_ARCHETYPE_SYSTEM', 3);
440 * Security token used for allowing access
441 * from external application such as web services.
442 * Scripts do not use any session, performance is relatively
443 * low because we need to load access info in each request.
444 * Scripts are executed in parallel.
446 define('EXTERNAL_TOKEN_PERMANENT', 0);
449 * Security token used for allowing access
450 * of embedded applications, the code is executed in the
451 * active user session. Token is invalidated after user logs out.
452 * Scripts are executed serially - normal session locking is used.
454 define('EXTERNAL_TOKEN_EMBEDDED', 1);
457 * The home page should be the site home
459 define('HOMEPAGE_SITE', 0);
461 * The home page should be the users my page
463 define('HOMEPAGE_MY', 1);
465 * The home page can be chosen by the user
467 define('HOMEPAGE_USER', 2);
470 * Hub directory url (should be moodle.org)
472 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
476 * Moodle.org url (should be moodle.org)
478 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
481 * Moodle mobile app service name
483 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
486 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
488 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
491 * Course display settings
493 define('COURSE_DISPLAY_SINGLEPAGE', 0); // display all sections on one page
494 define('COURSE_DISPLAY_MULTIPAGE', 1); // split pages into a page per section
496 /// PARAMETER HANDLING ////////////////////////////////////////////////////
499 * Returns a particular value for the named variable, taken from
500 * POST or GET. If the parameter doesn't exist then an error is
501 * thrown because we require this variable.
503 * This function should be used to initialise all required values
504 * in a script that are based on parameters. Usually it will be
506 * $id = required_param('id', PARAM_INT);
508 * Please note the $type parameter is now required and the value can not be array.
510 * @param string $parname the name of the page parameter we want
511 * @param string $type expected type of parameter
514 function required_param($parname, $type) {
515 if (func_num_args() != 2 or empty($parname) or empty($type)) {
516 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
518 if (isset($_POST[$parname])) { // POST has precedence
519 $param = $_POST[$parname];
520 } else if (isset($_GET[$parname])) {
521 $param = $_GET[$parname];
523 print_error('missingparam', '', '', $parname);
526 if (is_array($param)) {
527 debugging('Invalid array parameter detected in required_param(): '.$parname);
528 // TODO: switch to fatal error in Moodle 2.3
529 //print_error('missingparam', '', '', $parname);
530 return required_param_array($parname, $type);
533 return clean_param($param, $type);
537 * Returns a particular array value for the named variable, taken from
538 * POST or GET. If the parameter doesn't exist then an error is
539 * thrown because we require this variable.
541 * This function should be used to initialise all required values
542 * in a script that are based on parameters. Usually it will be
544 * $ids = required_param_array('ids', PARAM_INT);
546 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
548 * @param string $parname the name of the page parameter we want
549 * @param string $type expected type of parameter
552 function required_param_array($parname, $type) {
553 if (func_num_args() != 2 or empty($parname) or empty($type)) {
554 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
556 if (isset($_POST[$parname])) { // POST has precedence
557 $param = $_POST[$parname];
558 } else if (isset($_GET[$parname])) {
559 $param = $_GET[$parname];
561 print_error('missingparam', '', '', $parname);
563 if (!is_array($param)) {
564 print_error('missingparam', '', '', $parname);
568 foreach($param as $key=>$value) {
569 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
570 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
573 $result[$key] = clean_param($value, $type);
580 * Returns a particular value for the named variable, taken from
581 * POST or GET, otherwise returning a given default.
583 * This function should be used to initialise all optional values
584 * in a script that are based on parameters. Usually it will be
586 * $name = optional_param('name', 'Fred', PARAM_TEXT);
588 * Please note the $type parameter is now required and the value can not be array.
590 * @param string $parname the name of the page parameter we want
591 * @param mixed $default the default value to return if nothing is found
592 * @param string $type expected type of parameter
595 function optional_param($parname, $default, $type) {
596 if (func_num_args() != 3 or empty($parname) or empty($type)) {
597 throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
599 if (!isset($default)) {
603 if (isset($_POST[$parname])) { // POST has precedence
604 $param = $_POST[$parname];
605 } else if (isset($_GET[$parname])) {
606 $param = $_GET[$parname];
611 if (is_array($param)) {
612 debugging('Invalid array parameter detected in required_param(): '.$parname);
613 // TODO: switch to $default in Moodle 2.3
615 return optional_param_array($parname, $default, $type);
618 return clean_param($param, $type);
622 * Returns a particular array value for the named variable, taken from
623 * POST or GET, otherwise returning a given default.
625 * This function should be used to initialise all optional values
626 * in a script that are based on parameters. Usually it will be
628 * $ids = optional_param('id', array(), PARAM_INT);
630 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
632 * @param string $parname the name of the page parameter we want
633 * @param mixed $default the default value to return if nothing is found
634 * @param string $type expected type of parameter
637 function optional_param_array($parname, $default, $type) {
638 if (func_num_args() != 3 or empty($parname) or empty($type)) {
639 throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
642 if (isset($_POST[$parname])) { // POST has precedence
643 $param = $_POST[$parname];
644 } else if (isset($_GET[$parname])) {
645 $param = $_GET[$parname];
649 if (!is_array($param)) {
650 debugging('optional_param_array() expects array parameters only: '.$parname);
655 foreach($param as $key=>$value) {
656 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
657 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
660 $result[$key] = clean_param($value, $type);
667 * Strict validation of parameter values, the values are only converted
668 * to requested PHP type. Internally it is using clean_param, the values
669 * before and after cleaning must be equal - otherwise
670 * an invalid_parameter_exception is thrown.
671 * Objects and classes are not accepted.
673 * @param mixed $param
674 * @param string $type PARAM_ constant
675 * @param bool $allownull are nulls valid value?
676 * @param string $debuginfo optional debug information
677 * @return mixed the $param value converted to PHP type
678 * @throws invalid_parameter_exception if $param is not of given type
680 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
681 if (is_null($param)) {
682 if ($allownull == NULL_ALLOWED) {
685 throw new invalid_parameter_exception($debuginfo);
688 if (is_array($param) or is_object($param)) {
689 throw new invalid_parameter_exception($debuginfo);
692 $cleaned = clean_param($param, $type);
694 if ($type == PARAM_FLOAT) {
695 // Do not detect precision loss here.
696 if (is_float($param) or is_int($param)) {
698 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
699 throw new invalid_parameter_exception($debuginfo);
701 } else if ((string)$param !== (string)$cleaned) {
702 // conversion to string is usually lossless
703 throw new invalid_parameter_exception($debuginfo);
710 * Makes sure array contains only the allowed types,
711 * this function does not validate array key names!
713 * $options = clean_param($options, PARAM_INT);
716 * @param array $param the variable array we are cleaning
717 * @param string $type expected format of param after cleaning.
718 * @param bool $recursive clean recursive arrays
721 function clean_param_array(array $param = null, $type, $recursive = false) {
722 $param = (array)$param; // convert null to empty array
723 foreach ($param as $key => $value) {
724 if (is_array($value)) {
726 $param[$key] = clean_param_array($value, $type, true);
728 throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
731 $param[$key] = clean_param($value, $type);
738 * Used by {@link optional_param()} and {@link required_param()} to
739 * clean the variables and/or cast to specific types, based on
742 * $course->format = clean_param($course->format, PARAM_ALPHA);
743 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
746 * @param mixed $param the variable we are cleaning
747 * @param string $type expected format of param after cleaning.
750 function clean_param($param, $type) {
754 if (is_array($param)) {
755 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
756 } else if (is_object($param)) {
757 if (method_exists($param, '__toString')) {
758 $param = $param->__toString();
760 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
765 case PARAM_RAW: // no cleaning at all
766 $param = fix_utf8($param);
769 case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
770 $param = fix_utf8($param);
773 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
774 // this is deprecated!, please use more specific type instead
775 if (is_numeric($param)) {
778 $param = fix_utf8($param);
779 return clean_text($param); // Sweep for scripts, etc
781 case PARAM_CLEANHTML: // clean html fragment
782 $param = fix_utf8($param);
783 $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
787 return (int)$param; // Convert to integer
790 return (float)$param; // Convert to float
792 case PARAM_ALPHA: // Remove everything not a-z
793 return preg_replace('/[^a-zA-Z]/i', '', $param);
795 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
796 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
798 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
799 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
801 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
802 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
804 case PARAM_SEQUENCE: // Remove everything not 0-9,
805 return preg_replace('/[^0-9,]/i', '', $param);
807 case PARAM_BOOL: // Convert to 1 or 0
808 $tempstr = strtolower($param);
809 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
811 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
814 $param = empty($param) ? 0 : 1;
818 case PARAM_NOTAGS: // Strip all tags
819 $param = fix_utf8($param);
820 return strip_tags($param);
822 case PARAM_TEXT: // leave only tags needed for multilang
823 $param = fix_utf8($param);
824 // if the multilang syntax is not correct we strip all tags
825 // because it would break xhtml strict which is required for accessibility standards
826 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
828 if (strpos($param, '</lang>') !== false) {
829 // old and future mutilang syntax
830 $param = strip_tags($param, '<lang>');
831 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
835 foreach ($matches[0] as $match) {
836 if ($match === '</lang>') {
844 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
855 } else if (strpos($param, '</span>') !== false) {
856 // current problematic multilang syntax
857 $param = strip_tags($param, '<span>');
858 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
862 foreach ($matches[0] as $match) {
863 if ($match === '</span>') {
871 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
883 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
884 return strip_tags($param);
886 case PARAM_COMPONENT:
887 // we do not want any guessing here, either the name is correct or not
888 // please note only normalised component names are accepted
889 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
892 if (strpos($param, '__') !== false) {
895 if (strpos($param, 'mod_') === 0) {
896 // module names must not contain underscores because we need to differentiate them from invalid plugin types
897 if (substr_count($param, '_') != 1) {
905 // we do not want any guessing here, either the name is correct or not
906 if (!preg_match('/^[a-z][a-z0-9_]*[a-z0-9]$/', $param)) {
909 if (strpos($param, '__') !== false) {
914 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
915 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
917 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
918 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
920 case PARAM_FILE: // Strip all suspicious characters from filename
921 $param = fix_utf8($param);
922 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
923 $param = preg_replace('~\.\.+~', '', $param);
924 if ($param === '.') {
929 case PARAM_PATH: // Strip all suspicious characters from file path
930 $param = fix_utf8($param);
931 $param = str_replace('\\', '/', $param);
932 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
933 $param = preg_replace('~\.\.+~', '', $param);
934 $param = preg_replace('~//+~', '/', $param);
935 return preg_replace('~/(\./)+~', '/', $param);
937 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
938 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
939 // match ipv4 dotted quad
940 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
941 // confirm values are ok
945 || $match[4] > 255 ) {
946 // hmmm, what kind of dotted quad is this?
949 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
950 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
951 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
953 // all is ok - $param is respected
960 case PARAM_URL: // allow safe ftp, http, mailto urls
961 $param = fix_utf8($param);
962 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
963 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
964 // all is ok, param is respected
966 $param =''; // not really ok
970 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
971 $param = clean_param($param, PARAM_URL);
972 if (!empty($param)) {
973 if (preg_match(':^/:', $param)) {
974 // root-relative, ok!
975 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
976 // absolute, and matches our wwwroot
978 // relative - let's make sure there are no tricks
979 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
989 $param = trim($param);
990 // PEM formatted strings may contain letters/numbers and the symbols
994 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
995 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
996 list($wholething, $body) = $matches;
997 unset($wholething, $matches);
998 $b64 = clean_param($body, PARAM_BASE64);
1000 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1008 if (!empty($param)) {
1009 // PEM formatted strings may contain letters/numbers and the symbols
1013 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1016 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1017 // Each line of base64 encoded data must be 64 characters in
1018 // length, except for the last line which may be less than (or
1019 // equal to) 64 characters long.
1020 for ($i=0, $j=count($lines); $i < $j; $i++) {
1022 if (64 < strlen($lines[$i])) {
1028 if (64 != strlen($lines[$i])) {
1032 return implode("\n",$lines);
1038 $param = fix_utf8($param);
1039 // Please note it is not safe to use the tag name directly anywhere,
1040 // it must be processed with s(), urlencode() before embedding anywhere.
1041 // remove some nasties
1042 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1043 //convert many whitespace chars into one
1044 $param = preg_replace('/\s+/', ' ', $param);
1045 $param = textlib::substr(trim($param), 0, TAG_MAX_LENGTH);
1049 $param = fix_utf8($param);
1050 $tags = explode(',', $param);
1052 foreach ($tags as $tag) {
1053 $res = clean_param($tag, PARAM_TAG);
1059 return implode(',', $result);
1064 case PARAM_CAPABILITY:
1065 if (get_capability_info($param)) {
1071 case PARAM_PERMISSION:
1072 $param = (int)$param;
1073 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1080 $param = clean_param($param, PARAM_PLUGIN);
1081 if (empty($param)) {
1083 } else if (exists_auth_plugin($param)) {
1090 $param = clean_param($param, PARAM_SAFEDIR);
1091 if (get_string_manager()->translation_exists($param)) {
1094 return ''; // Specified language is not installed or param malformed
1098 $param = clean_param($param, PARAM_PLUGIN);
1099 if (empty($param)) {
1101 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1103 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1106 return ''; // Specified theme is not installed
1109 case PARAM_USERNAME:
1110 $param = fix_utf8($param);
1111 $param = str_replace(" " , "", $param);
1112 $param = textlib::strtolower($param); // Convert uppercase to lowercase MDL-16919
1113 if (empty($CFG->extendedusernamechars)) {
1114 // regular expression, eliminate all chars EXCEPT:
1115 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1116 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1121 $param = fix_utf8($param);
1122 if (validate_email($param)) {
1128 case PARAM_STRINGID:
1129 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1135 case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1136 $param = fix_utf8($param);
1137 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1138 if (preg_match($timezonepattern, $param)) {
1144 default: // throw error, switched parameters in optional_param or another serious problem
1145 print_error("unknownparamtype", '', '', $type);
1150 * Makes sure the data is using valid utf8, invalid characters are discarded.
1152 * Note: this function is not intended for full objects with methods and private properties.
1154 * @param mixed $value
1155 * @return mixed with proper utf-8 encoding
1157 function fix_utf8($value) {
1158 if (is_null($value) or $value === '') {
1161 } else if (is_string($value)) {
1162 if ((string)(int)$value === $value) {
1167 // Lower error reporting because glibc throws bogus notices.
1168 $olderror = error_reporting();
1169 if ($olderror & E_NOTICE) {
1170 error_reporting($olderror ^ E_NOTICE);
1173 // Note: this duplicates min_fix_utf8() intentionally.
1174 static $buggyiconv = null;
1175 if ($buggyiconv === null) {
1176 $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1180 if (function_exists('mb_convert_encoding')) {
1181 $subst = mb_substitute_character();
1182 mb_substitute_character('');
1183 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1184 mb_substitute_character($subst);
1187 // Warn admins on admin/index.php page.
1192 $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1195 if ($olderror & E_NOTICE) {
1196 error_reporting($olderror);
1201 } else if (is_array($value)) {
1202 foreach ($value as $k=>$v) {
1203 $value[$k] = fix_utf8($v);
1207 } else if (is_object($value)) {
1208 $value = clone($value); // do not modify original
1209 foreach ($value as $k=>$v) {
1210 $value->$k = fix_utf8($v);
1215 // this is some other type, no utf-8 here
1221 * Return true if given value is integer or string with integer value
1223 * @param mixed $value String or Int
1224 * @return bool true if number, false if not
1226 function is_number($value) {
1227 if (is_int($value)) {
1229 } else if (is_string($value)) {
1230 return ((string)(int)$value) === $value;
1237 * Returns host part from url
1238 * @param string $url full url
1239 * @return string host, null if not found
1241 function get_host_from_url($url) {
1242 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1250 * Tests whether anything was returned by text editor
1252 * This function is useful for testing whether something you got back from
1253 * the HTML editor actually contains anything. Sometimes the HTML editor
1254 * appear to be empty, but actually you get back a <br> tag or something.
1256 * @param string $string a string containing HTML.
1257 * @return boolean does the string contain any actual content - that is text,
1258 * images, objects, etc.
1260 function html_is_blank($string) {
1261 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1265 * Set a key in global configuration
1267 * Set a key/value pair in both this session's {@link $CFG} global variable
1268 * and in the 'config' database table for future sessions.
1270 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1271 * In that case it doesn't affect $CFG.
1273 * A NULL value will delete the entry.
1277 * @param string $name the key to set
1278 * @param string $value the value to set (without magic quotes)
1279 * @param string $plugin (optional) the plugin scope, default NULL
1280 * @return bool true or exception
1282 function set_config($name, $value, $plugin=NULL) {
1285 if (empty($plugin)) {
1286 if (!array_key_exists($name, $CFG->config_php_settings)) {
1287 // So it's defined for this invocation at least
1288 if (is_null($value)) {
1291 $CFG->$name = (string)$value; // settings from db are always strings
1295 if ($DB->get_field('config', 'name', array('name'=>$name))) {
1296 if ($value === null) {
1297 $DB->delete_records('config', array('name'=>$name));
1299 $DB->set_field('config', 'value', $value, array('name'=>$name));
1302 if ($value !== null) {
1303 $config = new stdClass();
1304 $config->name = $name;
1305 $config->value = $value;
1306 $DB->insert_record('config', $config, false);
1310 } else { // plugin scope
1311 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1312 if ($value===null) {
1313 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1315 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1318 if ($value !== null) {
1319 $config = new stdClass();
1320 $config->plugin = $plugin;
1321 $config->name = $name;
1322 $config->value = $value;
1323 $DB->insert_record('config_plugins', $config, false);
1332 * Get configuration values from the global config table
1333 * or the config_plugins table.
1335 * If called with one parameter, it will load all the config
1336 * variables for one plugin, and return them as an object.
1338 * If called with 2 parameters it will return a string single
1339 * value or false if the value is not found.
1341 * @param string $plugin full component name
1342 * @param string $name default NULL
1343 * @return mixed hash-like object or single value, return false no config found
1345 function get_config($plugin, $name = NULL) {
1348 // normalise component name
1349 if ($plugin === 'moodle' or $plugin === 'core') {
1353 if (!empty($name)) { // the user is asking for a specific value
1354 if (!empty($plugin)) {
1355 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1356 // setting forced in config file
1357 return $CFG->forced_plugin_settings[$plugin][$name];
1359 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1362 if (array_key_exists($name, $CFG->config_php_settings)) {
1363 // setting force in config file
1364 return $CFG->config_php_settings[$name];
1366 return $DB->get_field('config', 'value', array('name'=>$name));
1371 // the user is after a recordset
1373 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1374 if (isset($CFG->forced_plugin_settings[$plugin])) {
1375 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1376 if (is_null($v) or is_array($v) or is_object($v)) {
1377 // we do not want any extra mess here, just real settings that could be saved in db
1378 unset($localcfg[$n]);
1380 //convert to string as if it went through the DB
1381 $localcfg[$n] = (string)$v;
1386 return (object)$localcfg;
1388 return new stdClass();
1392 // this part is not really used any more, but anyway...
1393 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1394 foreach($CFG->config_php_settings as $n=>$v) {
1395 if (is_null($v) or is_array($v) or is_object($v)) {
1396 // we do not want any extra mess here, just real settings that could be saved in db
1397 unset($localcfg[$n]);
1399 //convert to string as if it went through the DB
1400 $localcfg[$n] = (string)$v;
1403 return (object)$localcfg;
1408 * Removes a key from global configuration
1410 * @param string $name the key to set
1411 * @param string $plugin (optional) the plugin scope
1413 * @return boolean whether the operation succeeded.
1415 function unset_config($name, $plugin=NULL) {
1418 if (empty($plugin)) {
1420 $DB->delete_records('config', array('name'=>$name));
1422 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1429 * Remove all the config variables for a given plugin.
1431 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1432 * @return boolean whether the operation succeeded.
1434 function unset_all_config_for_plugin($plugin) {
1436 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1437 $like = $DB->sql_like('name', '?', true, true, false, '|');
1438 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1439 $DB->delete_records_select('config', $like, $params);
1444 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1446 * All users are verified if they still have the necessary capability.
1448 * @param string $value the value of the config setting.
1449 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1450 * @param bool $include admins, include administrators
1451 * @return array of user objects.
1453 function get_users_from_config($value, $capability, $includeadmins = true) {
1456 if (empty($value) or $value === '$@NONE@$') {
1460 // we have to make sure that users still have the necessary capability,
1461 // it should be faster to fetch them all first and then test if they are present
1462 // instead of validating them one-by-one
1463 $users = get_users_by_capability(context_system::instance(), $capability);
1464 if ($includeadmins) {
1465 $admins = get_admins();
1466 foreach ($admins as $admin) {
1467 $users[$admin->id] = $admin;
1471 if ($value === '$@ALL@$') {
1475 $result = array(); // result in correct order
1476 $allowed = explode(',', $value);
1477 foreach ($allowed as $uid) {
1478 if (isset($users[$uid])) {
1479 $user = $users[$uid];
1480 $result[$user->id] = $user;
1489 * Invalidates browser caches and cached data in temp
1491 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1492 * {@see phpunit_util::reset_dataroot()}
1496 function purge_all_caches() {
1499 reset_text_filters_cache();
1500 js_reset_all_caches();
1501 theme_reset_all_caches();
1502 get_string_manager()->reset_caches();
1503 textlib::reset_caches();
1505 cache_helper::purge_all();
1507 // purge all other caches: rss, simplepie, etc.
1508 remove_dir($CFG->cachedir.'', true);
1510 // make sure cache dir is writable, throws exception if not
1511 make_cache_directory('');
1513 // hack: this script may get called after the purifier was initialised,
1514 // but we do not want to verify repeatedly this exists in each call
1515 make_cache_directory('htmlpurifier');
1519 * Get volatile flags
1521 * @param string $type
1522 * @param int $changedsince default null
1523 * @return records array
1525 function get_cache_flags($type, $changedsince=NULL) {
1528 $params = array('type'=>$type, 'expiry'=>time());
1529 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1530 if ($changedsince !== NULL) {
1531 $params['changedsince'] = $changedsince;
1532 $sqlwhere .= " AND timemodified > :changedsince";
1536 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1537 foreach ($flags as $flag) {
1538 $cf[$flag->name] = $flag->value;
1545 * Get volatile flags
1547 * @param string $type
1548 * @param string $name
1549 * @param int $changedsince default null
1550 * @return records array
1552 function get_cache_flag($type, $name, $changedsince=NULL) {
1555 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1557 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1558 if ($changedsince !== NULL) {
1559 $params['changedsince'] = $changedsince;
1560 $sqlwhere .= " AND timemodified > :changedsince";
1563 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1567 * Set a volatile flag
1569 * @param string $type the "type" namespace for the key
1570 * @param string $name the key to set
1571 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1572 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1573 * @return bool Always returns true
1575 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1578 $timemodified = time();
1579 if ($expiry===NULL || $expiry < $timemodified) {
1580 $expiry = $timemodified + 24 * 60 * 60;
1582 $expiry = (int)$expiry;
1585 if ($value === NULL) {
1586 unset_cache_flag($type,$name);
1590 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1591 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1592 return true; //no need to update; helps rcache too
1595 $f->expiry = $expiry;
1596 $f->timemodified = $timemodified;
1597 $DB->update_record('cache_flags', $f);
1599 $f = new stdClass();
1600 $f->flagtype = $type;
1603 $f->expiry = $expiry;
1604 $f->timemodified = $timemodified;
1605 $DB->insert_record('cache_flags', $f);
1611 * Removes a single volatile flag
1614 * @param string $type the "type" namespace for the key
1615 * @param string $name the key to set
1618 function unset_cache_flag($type, $name) {
1620 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1625 * Garbage-collect volatile flags
1627 * @return bool Always returns true
1629 function gc_cache_flags() {
1631 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1635 // USER PREFERENCE API
1638 * Refresh user preference cache. This is used most often for $USER
1639 * object that is stored in session, but it also helps with performance in cron script.
1641 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1644 * @category preference
1646 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1647 * @param int $cachelifetime Cache life time on the current page (in seconds)
1648 * @throws coding_exception
1651 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1653 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1655 if (!isset($user->id)) {
1656 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1659 if (empty($user->id) or isguestuser($user->id)) {
1660 // No permanent storage for not-logged-in users and guest
1661 if (!isset($user->preference)) {
1662 $user->preference = array();
1669 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1670 // Already loaded at least once on this page. Are we up to date?
1671 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1672 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1675 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1676 // no change since the lastcheck on this page
1677 $user->preference['_lastloaded'] = $timenow;
1682 // OK, so we have to reload all preferences
1683 $loadedusers[$user->id] = true;
1684 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1685 $user->preference['_lastloaded'] = $timenow;
1689 * Called from set/unset_user_preferences, so that the prefs can
1690 * be correctly reloaded in different sessions.
1692 * NOTE: internal function, do not call from other code.
1696 * @param integer $userid the user whose prefs were changed.
1698 function mark_user_preferences_changed($userid) {
1701 if (empty($userid) or isguestuser($userid)) {
1702 // no cache flags for guest and not-logged-in users
1706 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1710 * Sets a preference for the specified user.
1712 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1715 * @category preference
1717 * @param string $name The key to set as preference for the specified user
1718 * @param string $value The value to set for the $name key in the specified user's
1719 * record, null means delete current value.
1720 * @param stdClass|int|null $user A moodle user object or id, null means current user
1721 * @throws coding_exception
1722 * @return bool Always true or exception
1724 function set_user_preference($name, $value, $user = null) {
1727 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1728 throw new coding_exception('Invalid preference name in set_user_preference() call');
1731 if (is_null($value)) {
1732 // null means delete current
1733 return unset_user_preference($name, $user);
1734 } else if (is_object($value)) {
1735 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1736 } else if (is_array($value)) {
1737 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1739 $value = (string)$value;
1740 if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1741 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1744 if (is_null($user)) {
1746 } else if (isset($user->id)) {
1747 // $user is valid object
1748 } else if (is_numeric($user)) {
1749 $user = (object)array('id'=>(int)$user);
1751 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1754 check_user_preferences_loaded($user);
1756 if (empty($user->id) or isguestuser($user->id)) {
1757 // no permanent storage for not-logged-in users and guest
1758 $user->preference[$name] = $value;
1762 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1763 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1764 // preference already set to this value
1767 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1770 $preference = new stdClass();
1771 $preference->userid = $user->id;
1772 $preference->name = $name;
1773 $preference->value = $value;
1774 $DB->insert_record('user_preferences', $preference);
1777 // update value in cache
1778 $user->preference[$name] = $value;
1780 // set reload flag for other sessions
1781 mark_user_preferences_changed($user->id);
1787 * Sets a whole array of preferences for the current user
1789 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1792 * @category preference
1794 * @param array $prefarray An array of key/value pairs to be set
1795 * @param stdClass|int|null $user A moodle user object or id, null means current user
1796 * @return bool Always true or exception
1798 function set_user_preferences(array $prefarray, $user = null) {
1799 foreach ($prefarray as $name => $value) {
1800 set_user_preference($name, $value, $user);
1806 * Unsets a preference completely by deleting it from the database
1808 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1811 * @category preference
1813 * @param string $name The key to unset as preference for the specified user
1814 * @param stdClass|int|null $user A moodle user object or id, null means current user
1815 * @throws coding_exception
1816 * @return bool Always true or exception
1818 function unset_user_preference($name, $user = null) {
1821 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1822 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1825 if (is_null($user)) {
1827 } else if (isset($user->id)) {
1828 // $user is valid object
1829 } else if (is_numeric($user)) {
1830 $user = (object)array('id'=>(int)$user);
1832 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1835 check_user_preferences_loaded($user);
1837 if (empty($user->id) or isguestuser($user->id)) {
1838 // no permanent storage for not-logged-in user and guest
1839 unset($user->preference[$name]);
1844 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1846 // delete the preference from cache
1847 unset($user->preference[$name]);
1849 // set reload flag for other sessions
1850 mark_user_preferences_changed($user->id);
1856 * Used to fetch user preference(s)
1858 * If no arguments are supplied this function will return
1859 * all of the current user preferences as an array.
1861 * If a name is specified then this function
1862 * attempts to return that particular preference value. If
1863 * none is found, then the optional value $default is returned,
1866 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1869 * @category preference
1871 * @param string $name Name of the key to use in finding a preference value
1872 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1873 * @param stdClass|int|null $user A moodle user object or id, null means current user
1874 * @throws coding_exception
1875 * @return string|mixed|null A string containing the value of a single preference. An
1876 * array with all of the preferences or null
1878 function get_user_preferences($name = null, $default = null, $user = null) {
1881 if (is_null($name)) {
1883 } else if (is_numeric($name) or $name === '_lastloaded') {
1884 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1887 if (is_null($user)) {
1889 } else if (isset($user->id)) {
1890 // $user is valid object
1891 } else if (is_numeric($user)) {
1892 $user = (object)array('id'=>(int)$user);
1894 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1897 check_user_preferences_loaded($user);
1900 return $user->preference; // All values
1901 } else if (isset($user->preference[$name])) {
1902 return $user->preference[$name]; // The single string value
1904 return $default; // Default value (null if not specified)
1908 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1911 * Given date parts in user time produce a GMT timestamp.
1915 * @param int $year The year part to create timestamp of
1916 * @param int $month The month part to create timestamp of
1917 * @param int $day The day part to create timestamp of
1918 * @param int $hour The hour part to create timestamp of
1919 * @param int $minute The minute part to create timestamp of
1920 * @param int $second The second part to create timestamp of
1921 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1922 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
1923 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1924 * applied only if timezone is 99 or string.
1925 * @return int GMT timestamp
1927 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1929 //save input timezone, required for dst offset check.
1930 $passedtimezone = $timezone;
1932 $timezone = get_user_timezone_offset($timezone);
1934 if (abs($timezone) > 13) { //server time
1935 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1937 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1938 $time = usertime($time, $timezone);
1940 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1941 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1942 $time -= dst_offset_on($time, $passedtimezone);
1951 * Format a date/time (seconds) as weeks, days, hours etc as needed
1953 * Given an amount of time in seconds, returns string
1954 * formatted nicely as weeks, days, hours etc as needed
1962 * @param int $totalsecs Time in seconds
1963 * @param object $str Should be a time object
1964 * @return string A nicely formatted date/time string
1966 function format_time($totalsecs, $str=NULL) {
1968 $totalsecs = abs($totalsecs);
1970 if (!$str) { // Create the str structure the slow way
1971 $str = new stdClass();
1972 $str->day = get_string('day');
1973 $str->days = get_string('days');
1974 $str->hour = get_string('hour');
1975 $str->hours = get_string('hours');
1976 $str->min = get_string('min');
1977 $str->mins = get_string('mins');
1978 $str->sec = get_string('sec');
1979 $str->secs = get_string('secs');
1980 $str->year = get_string('year');
1981 $str->years = get_string('years');
1985 $years = floor($totalsecs/YEARSECS);
1986 $remainder = $totalsecs - ($years*YEARSECS);
1987 $days = floor($remainder/DAYSECS);
1988 $remainder = $totalsecs - ($days*DAYSECS);
1989 $hours = floor($remainder/HOURSECS);
1990 $remainder = $remainder - ($hours*HOURSECS);
1991 $mins = floor($remainder/MINSECS);
1992 $secs = $remainder - ($mins*MINSECS);
1994 $ss = ($secs == 1) ? $str->sec : $str->secs;
1995 $sm = ($mins == 1) ? $str->min : $str->mins;
1996 $sh = ($hours == 1) ? $str->hour : $str->hours;
1997 $sd = ($days == 1) ? $str->day : $str->days;
1998 $sy = ($years == 1) ? $str->year : $str->years;
2006 if ($years) $oyears = $years .' '. $sy;
2007 if ($days) $odays = $days .' '. $sd;
2008 if ($hours) $ohours = $hours .' '. $sh;
2009 if ($mins) $omins = $mins .' '. $sm;
2010 if ($secs) $osecs = $secs .' '. $ss;
2012 if ($years) return trim($oyears .' '. $odays);
2013 if ($days) return trim($odays .' '. $ohours);
2014 if ($hours) return trim($ohours .' '. $omins);
2015 if ($mins) return trim($omins .' '. $osecs);
2016 if ($secs) return $osecs;
2017 return get_string('now');
2021 * Returns a formatted string that represents a date in user time
2023 * Returns a formatted string that represents a date in user time
2024 * <b>WARNING: note that the format is for strftime(), not date().</b>
2025 * Because of a bug in most Windows time libraries, we can't use
2026 * the nicer %e, so we have to use %d which has leading zeroes.
2027 * A lot of the fuss in the function is just getting rid of these leading
2028 * zeroes as efficiently as possible.
2030 * If parameter fixday = true (default), then take off leading
2031 * zero from %d, else maintain it.
2035 * @param int $date the timestamp in UTC, as obtained from the database.
2036 * @param string $format strftime format. You should probably get this using
2037 * get_string('strftime...', 'langconfig');
2038 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2039 * not 99 then daylight saving will not be added.
2040 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2041 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2042 * If false then the leading zero is maintained.
2043 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2044 * @return string the formatted date/time.
2046 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2050 if (empty($format)) {
2051 $format = get_string('strftimedaydatetime', 'langconfig');
2054 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
2056 } else if ($fixday) {
2057 $formatnoday = str_replace('%d', 'DD', $format);
2058 $fixday = ($formatnoday != $format);
2059 $format = $formatnoday;
2062 // Note: This logic about fixing 12-hour time to remove unnecessary leading
2063 // zero is required because on Windows, PHP strftime function does not
2064 // support the correct 'hour without leading zero' parameter (%l).
2065 if (!empty($CFG->nofixhour)) {
2066 // Config.php can force %I not to be fixed.
2068 } else if ($fixhour) {
2069 $formatnohour = str_replace('%I', 'HH', $format);
2070 $fixhour = ($formatnohour != $format);
2071 $format = $formatnohour;
2074 //add daylight saving offset for string timezones only, as we can't get dst for
2075 //float values. if timezone is 99 (user default timezone), then try update dst.
2076 if ((99 == $timezone) || !is_numeric($timezone)) {
2077 $date += dst_offset_on($date, $timezone);
2080 $timezone = get_user_timezone_offset($timezone);
2082 // If we are running under Windows convert to windows encoding and then back to UTF-8
2083 // (because it's impossible to specify UTF-8 to fetch locale info in Win32)
2085 if (abs($timezone) > 13) { /// Server time
2086 $datestring = date_format_string($date, $format, $timezone);
2088 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
2089 $datestring = str_replace('DD', $daystring, $datestring);
2092 $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2093 $datestring = str_replace('HH', $hourstring, $datestring);
2097 $date += (int)($timezone * 3600);
2098 $datestring = date_format_string($date, $format, $timezone);
2100 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
2101 $datestring = str_replace('DD', $daystring, $datestring);
2104 $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2105 $datestring = str_replace('HH', $hourstring, $datestring);
2113 * Returns a formatted date ensuring it is UTF-8.
2115 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2116 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2118 * This function does not do any calculation regarding the user preferences and should
2119 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2120 * to differenciate the use of server time or not (strftime() against gmstrftime()).
2122 * @param int $date the timestamp.
2123 * @param string $format strftime format.
2124 * @param int|float $timezone the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2125 * @return string the formatted date/time.
2128 function date_format_string($date, $format, $tz = 99) {
2130 if (abs($tz) > 13) {
2131 if ($CFG->ostype == 'WINDOWS') {
2132 $localewincharset = get_string('localewincharset', 'langconfig');
2133 $format = textlib::convert($format, 'utf-8', $localewincharset);
2134 $datestring = strftime($format, $date);
2135 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2137 $datestring = strftime($format, $date);
2140 if ($CFG->ostype == 'WINDOWS') {
2141 $localewincharset = get_string('localewincharset', 'langconfig');
2142 $format = textlib::convert($format, 'utf-8', $localewincharset);
2143 $datestring = gmstrftime($format, $date);
2144 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2146 $datestring = gmstrftime($format, $date);
2153 * Given a $time timestamp in GMT (seconds since epoch),
2154 * returns an array that represents the date in user time
2159 * @param int $time Timestamp in GMT
2160 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2161 * dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
2162 * @return array An array that represents the date in user time
2164 function usergetdate($time, $timezone=99) {
2166 //save input timezone, required for dst offset check.
2167 $passedtimezone = $timezone;
2169 $timezone = get_user_timezone_offset($timezone);
2171 if (abs($timezone) > 13) { // Server time
2172 return getdate($time);
2175 //add daylight saving offset for string timezones only, as we can't get dst for
2176 //float values. if timezone is 99 (user default timezone), then try update dst.
2177 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2178 $time += dst_offset_on($time, $passedtimezone);
2181 $time += intval((float)$timezone * HOURSECS);
2183 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2185 //be careful to ensure the returned array matches that produced by getdate() above
2188 $getdate['weekday'],
2195 $getdate['minutes'],
2197 ) = explode('_', $datestring);
2199 // set correct datatype to match with getdate()
2200 $getdate['seconds'] = (int)$getdate['seconds'];
2201 $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
2202 $getdate['year'] = (int)$getdate['year'];
2203 $getdate['mon'] = (int)$getdate['mon'];
2204 $getdate['wday'] = (int)$getdate['wday'];
2205 $getdate['mday'] = (int)$getdate['mday'];
2206 $getdate['hours'] = (int)$getdate['hours'];
2207 $getdate['minutes'] = (int)$getdate['minutes'];
2212 * Given a GMT timestamp (seconds since epoch), offsets it by
2213 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2218 * @param int $date Timestamp in GMT
2219 * @param float|int|string $timezone timezone to calculate GMT time offset before
2220 * calculating user time, 99 is default user timezone
2221 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2224 function usertime($date, $timezone=99) {
2226 $timezone = get_user_timezone_offset($timezone);
2228 if (abs($timezone) > 13) {
2231 return $date - (int)($timezone * HOURSECS);
2235 * Given a time, return the GMT timestamp of the most recent midnight
2236 * for the current user.
2240 * @param int $date Timestamp in GMT
2241 * @param float|int|string $timezone timezone to calculate GMT time offset before
2242 * calculating user midnight time, 99 is default user timezone
2243 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2244 * @return int Returns a GMT timestamp
2246 function usergetmidnight($date, $timezone=99) {
2248 $userdate = usergetdate($date, $timezone);
2250 // Time of midnight of this user's day, in GMT
2251 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2256 * Returns a string that prints the user's timezone
2260 * @param float|int|string $timezone timezone to calculate GMT time offset before
2261 * calculating user timezone, 99 is default user timezone
2262 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2265 function usertimezone($timezone=99) {
2267 $tz = get_user_timezone($timezone);
2269 if (!is_float($tz)) {
2273 if(abs($tz) > 13) { // Server time
2274 return get_string('serverlocaltime');
2277 if($tz == intval($tz)) {
2278 // Don't show .0 for whole hours
2295 * Returns a float which represents the user's timezone difference from GMT in hours
2296 * Checks various settings and picks the most dominant of those which have a value
2300 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2301 * 99 is default user timezone
2302 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2305 function get_user_timezone_offset($tz = 99) {
2309 $tz = get_user_timezone($tz);
2311 if (is_float($tz)) {
2314 $tzrecord = get_timezone_record($tz);
2315 if (empty($tzrecord)) {
2318 return (float)$tzrecord->gmtoff / HOURMINS;
2323 * Returns an int which represents the systems's timezone difference from GMT in seconds
2327 * @param float|int|string $tz timezone for which offset is required.
2328 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2329 * @return int|bool if found, false is timezone 99 or error
2331 function get_timezone_offset($tz) {
2338 if (is_numeric($tz)) {
2339 return intval($tz * 60*60);
2342 if (!$tzrecord = get_timezone_record($tz)) {
2345 return intval($tzrecord->gmtoff * 60);
2349 * Returns a float or a string which denotes the user's timezone
2350 * 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)
2351 * means that for this timezone there are also DST rules to be taken into account
2352 * Checks various settings and picks the most dominant of those which have a value
2356 * @param float|int|string $tz timezone to calculate GMT time offset before
2357 * calculating user timezone, 99 is default user timezone
2358 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2359 * @return float|string
2361 function get_user_timezone($tz = 99) {
2366 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2367 isset($USER->timezone) ? $USER->timezone : 99,
2368 isset($CFG->timezone) ? $CFG->timezone : 99,
2373 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array
2374 while(((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2375 $tz = $next['value'];
2377 return is_numeric($tz) ? (float) $tz : $tz;
2381 * Returns cached timezone record for given $timezonename
2384 * @param string $timezonename name of the timezone
2385 * @return stdClass|bool timezonerecord or false
2387 function get_timezone_record($timezonename) {
2389 static $cache = NULL;
2391 if ($cache === NULL) {
2395 if (isset($cache[$timezonename])) {
2396 return $cache[$timezonename];
2399 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2400 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2404 * Build and store the users Daylight Saving Time (DST) table
2407 * @param int $from_year Start year for the table, defaults to 1971
2408 * @param int $to_year End year for the table, defaults to 2035
2409 * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
2412 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2413 global $CFG, $SESSION, $DB;
2415 $usertz = get_user_timezone($strtimezone);
2417 if (is_float($usertz)) {
2418 // Trivial timezone, no DST
2422 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2423 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2424 unset($SESSION->dst_offsets);
2425 unset($SESSION->dst_range);
2428 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2429 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2430 // This will be the return path most of the time, pretty light computationally
2434 // Reaching here means we either need to extend our table or create it from scratch
2436 // Remember which TZ we calculated these changes for
2437 $SESSION->dst_offsettz = $usertz;
2439 if(empty($SESSION->dst_offsets)) {
2440 // If we 're creating from scratch, put the two guard elements in there
2441 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2443 if(empty($SESSION->dst_range)) {
2444 // If creating from scratch
2445 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2446 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2448 // Fill in the array with the extra years we need to process
2449 $yearstoprocess = array();
2450 for($i = $from; $i <= $to; ++$i) {
2451 $yearstoprocess[] = $i;
2454 // Take note of which years we have processed for future calls
2455 $SESSION->dst_range = array($from, $to);
2458 // If needing to extend the table, do the same
2459 $yearstoprocess = array();
2461 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2462 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2464 if($from < $SESSION->dst_range[0]) {
2465 // Take note of which years we need to process and then note that we have processed them for future calls
2466 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2467 $yearstoprocess[] = $i;
2469 $SESSION->dst_range[0] = $from;
2471 if($to > $SESSION->dst_range[1]) {
2472 // Take note of which years we need to process and then note that we have processed them for future calls
2473 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2474 $yearstoprocess[] = $i;
2476 $SESSION->dst_range[1] = $to;
2480 if(empty($yearstoprocess)) {
2481 // This means that there was a call requesting a SMALLER range than we have already calculated
2485 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2486 // Also, the array is sorted in descending timestamp order!
2490 static $presets_cache = array();
2491 if (!isset($presets_cache[$usertz])) {
2492 $presets_cache[$usertz] = $DB->get_records('timezone', array('name'=>$usertz), 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, std_startday, std_weekday, std_skipweeks, std_time');
2494 if(empty($presets_cache[$usertz])) {
2498 // Remove ending guard (first element of the array)
2499 reset($SESSION->dst_offsets);
2500 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2502 // Add all required change timestamps
2503 foreach($yearstoprocess as $y) {
2504 // Find the record which is in effect for the year $y
2505 foreach($presets_cache[$usertz] as $year => $preset) {
2511 $changes = dst_changes_for_year($y, $preset);
2513 if($changes === NULL) {
2516 if($changes['dst'] != 0) {
2517 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2519 if($changes['std'] != 0) {
2520 $SESSION->dst_offsets[$changes['std']] = 0;
2524 // Put in a guard element at the top
2525 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2526 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2529 krsort($SESSION->dst_offsets);
2535 * Calculates the required DST change and returns a Timestamp Array
2541 * @param int|string $year Int or String Year to focus on
2542 * @param object $timezone Instatiated Timezone object
2543 * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
2545 function dst_changes_for_year($year, $timezone) {
2547 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2551 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2552 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2554 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2555 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2557 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2558 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2560 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2561 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2562 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2564 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2565 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2567 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2571 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2572 * - Note: Daylight saving only works for string timezones and not for float.
2576 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2577 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2578 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2581 function dst_offset_on($time, $strtimezone = NULL) {
2584 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2588 reset($SESSION->dst_offsets);
2589 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2590 if($from <= $time) {
2595 // This is the normal return path
2596 if($offset !== NULL) {
2600 // Reaching this point means we haven't calculated far enough, do it now:
2601 // Calculate extra DST changes if needed and recurse. The recursion always
2602 // moves toward the stopping condition, so will always end.
2605 // We need a year smaller than $SESSION->dst_range[0]
2606 if($SESSION->dst_range[0] == 1971) {
2609 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2610 return dst_offset_on($time, $strtimezone);
2613 // We need a year larger than $SESSION->dst_range[1]
2614 if($SESSION->dst_range[1] == 2035) {
2617 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2618 return dst_offset_on($time, $strtimezone);
2623 * Calculates when the day appears in specific month
2627 * @param int $startday starting day of the month
2628 * @param int $weekday The day when week starts (normally taken from user preferences)
2629 * @param int $month The month whose day is sought
2630 * @param int $year The year of the month whose day is sought
2633 function find_day_in_month($startday, $weekday, $month, $year) {
2635 $daysinmonth = days_in_month($month, $year);
2637 if($weekday == -1) {
2638 // Don't care about weekday, so return:
2639 // abs($startday) if $startday != -1
2640 // $daysinmonth otherwise
2641 return ($startday == -1) ? $daysinmonth : abs($startday);
2644 // From now on we 're looking for a specific weekday
2646 // Give "end of month" its actual value, since we know it
2647 if($startday == -1) {
2648 $startday = -1 * $daysinmonth;
2651 // Starting from day $startday, the sign is the direction
2655 $startday = abs($startday);
2656 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2658 // This is the last such weekday of the month
2659 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2660 if($lastinmonth > $daysinmonth) {
2664 // Find the first such weekday <= $startday
2665 while($lastinmonth > $startday) {
2669 return $lastinmonth;
2674 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2676 $diff = $weekday - $indexweekday;
2681 // This is the first such weekday of the month equal to or after $startday
2682 $firstfromindex = $startday + $diff;
2684 return $firstfromindex;
2690 * Calculate the number of days in a given month
2694 * @param int $month The month whose day count is sought
2695 * @param int $year The year of the month whose day count is sought
2698 function days_in_month($month, $year) {
2699 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2703 * Calculate the position in the week of a specific calendar day
2707 * @param int $day The day of the date whose position in the week is sought
2708 * @param int $month The month of the date whose position in the week is sought
2709 * @param int $year The year of the date whose position in the week is sought
2712 function dayofweek($day, $month, $year) {
2713 // I wonder if this is any different from
2714 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2715 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2718 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2721 * Returns full login url.
2723 * @return string login url
2725 function get_login_url() {
2728 $url = "$CFG->wwwroot/login/index.php";
2730 if (!empty($CFG->loginhttps)) {
2731 $url = str_replace('http:', 'https:', $url);
2738 * This function checks that the current user is logged in and has the
2739 * required privileges
2741 * This function checks that the current user is logged in, and optionally
2742 * whether they are allowed to be in a particular course and view a particular
2744 * If they are not logged in, then it redirects them to the site login unless
2745 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2746 * case they are automatically logged in as guests.
2747 * If $courseid is given and the user is not enrolled in that course then the
2748 * user is redirected to the course enrolment page.
2749 * If $cm is given and the course module is hidden and the user is not a teacher
2750 * in the course then the user is redirected to the course home page.
2752 * When $cm parameter specified, this function sets page layout to 'module'.
2753 * You need to change it manually later if some other layout needed.
2755 * @package core_access
2758 * @param mixed $courseorid id of the course or course object
2759 * @param bool $autologinguest default true
2760 * @param object $cm course module object
2761 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2762 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2763 * in order to keep redirects working properly. MDL-14495
2764 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2765 * @return mixed Void, exit, and die depending on path
2767 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2768 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2770 // setup global $COURSE, themes, language and locale
2771 if (!empty($courseorid)) {
2772 if (is_object($courseorid)) {
2773 $course = $courseorid;
2774 } else if ($courseorid == SITEID) {
2775 $course = clone($SITE);
2777 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2780 if ($cm->course != $course->id) {
2781 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2783 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2784 if (!($cm instanceof cm_info)) {
2785 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2786 // db queries so this is not really a performance concern, however it is obviously
2787 // better if you use get_fast_modinfo to get the cm before calling this.
2788 $modinfo = get_fast_modinfo($course);
2789 $cm = $modinfo->get_cm($cm->id);
2791 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2792 $PAGE->set_pagelayout('incourse');
2794 $PAGE->set_course($course); // set's up global $COURSE
2797 // do not touch global $COURSE via $PAGE->set_course(),
2798 // the reasons is we need to be able to call require_login() at any time!!
2801 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2805 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2806 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2807 // risk leading the user back to the AJAX request URL.
2808 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2809 $setwantsurltome = false;
2812 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2813 if (!empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2814 if ($setwantsurltome) {
2815 $SESSION->wantsurl = qualified_me();
2817 redirect(get_login_url());
2820 // If the user is not even logged in yet then make sure they are
2821 if (!isloggedin()) {
2822 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2823 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2824 // misconfigured site guest, just redirect to login page
2825 redirect(get_login_url());
2826 exit; // never reached
2828 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2829 complete_user_login($guest);
2830 $USER->autologinguest = true;
2831 $SESSION->lang = $lang;
2833 //NOTE: $USER->site check was obsoleted by session test cookie,
2834 // $USER->confirmed test is in login/index.php
2835 if ($preventredirect) {
2836 throw new require_login_exception('You are not logged in');
2839 if ($setwantsurltome) {
2840 $SESSION->wantsurl = qualified_me();
2842 if (!empty($_SERVER['HTTP_REFERER'])) {
2843 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2845 redirect(get_login_url());
2846 exit; // never reached
2850 // loginas as redirection if needed
2851 if ($course->id != SITEID and session_is_loggedinas()) {
2852 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2853 if ($USER->loginascontext->instanceid != $course->id) {
2854 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2859 // check whether the user should be changing password (but only if it is REALLY them)
2860 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2861 $userauth = get_auth_plugin($USER->auth);
2862 if ($userauth->can_change_password() and !$preventredirect) {
2863 if ($setwantsurltome) {
2864 $SESSION->wantsurl = qualified_me();
2866 if ($changeurl = $userauth->change_password_url()) {
2867 //use plugin custom url
2868 redirect($changeurl);
2870 //use moodle internal method
2871 if (empty($CFG->loginhttps)) {
2872 redirect($CFG->wwwroot .'/login/change_password.php');
2874 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2875 redirect($wwwroot .'/login/change_password.php');
2879 print_error('nopasswordchangeforced', 'auth');
2883 // Check that the user account is properly set up
2884 if (user_not_fully_set_up($USER)) {
2885 if ($preventredirect) {
2886 throw new require_login_exception('User not fully set-up');
2888 if ($setwantsurltome) {
2889 $SESSION->wantsurl = qualified_me();
2891 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2894 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2897 // Do not bother admins with any formalities
2898 if (is_siteadmin()) {
2899 //set accesstime or the user will appear offline which messes up messaging
2900 user_accesstime_log($course->id);
2904 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2905 if (!$USER->policyagreed and !is_siteadmin()) {
2906 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2907 if ($preventredirect) {
2908 throw new require_login_exception('Policy not agreed');
2910 if ($setwantsurltome) {
2911 $SESSION->wantsurl = qualified_me();
2913 redirect($CFG->wwwroot .'/user/policy.php');
2914 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2915 if ($preventredirect) {
2916 throw new require_login_exception('Policy not agreed');
2918 if ($setwantsurltome) {
2919 $SESSION->wantsurl = qualified_me();
2921 redirect($CFG->wwwroot .'/user/policy.php');
2925 // Fetch the system context, the course context, and prefetch its child contexts
2926 $sysctx = context_system::instance();
2927 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2929 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2934 // If the site is currently under maintenance, then print a message
2935 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2936 if ($preventredirect) {
2937 throw new require_login_exception('Maintenance in progress');
2940 print_maintenance_message();
2943 // make sure the course itself is not hidden
2944 if ($course->id == SITEID) {
2945 // frontpage can not be hidden
2947 if (is_role_switched($course->id)) {
2948 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2950 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2951 // originally there was also test of parent category visibility,
2952 // BUT is was very slow in complex queries involving "my courses"
2953 // now it is also possible to simply hide all courses user is not enrolled in :-)
2954 if ($preventredirect) {
2955 throw new require_login_exception('Course is hidden');
2957 // We need to override the navigation URL as the course won't have
2958 // been added to the navigation and thus the navigation will mess up
2959 // when trying to find it.
2960 navigation_node::override_active_url(new moodle_url('/'));
2961 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2966 // is the user enrolled?
2967 if ($course->id == SITEID) {
2968 // everybody is enrolled on the frontpage
2971 if (session_is_loggedinas()) {
2972 // Make sure the REAL person can access this course first
2973 $realuser = session_get_realuser();
2974 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2975 if ($preventredirect) {
2976 throw new require_login_exception('Invalid course login-as access');
2978 echo $OUTPUT->header();
2979 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2985 if (is_role_switched($course->id)) {
2986 // ok, user had to be inside this course before the switch
2989 } else if (is_viewing($coursecontext, $USER)) {
2990 // ok, no need to mess with enrol
2994 if (isset($USER->enrol['enrolled'][$course->id])) {
2995 if ($USER->enrol['enrolled'][$course->id] > time()) {
2997 if (isset($USER->enrol['tempguest'][$course->id])) {
2998 unset($USER->enrol['tempguest'][$course->id]);
2999 remove_temp_course_roles($coursecontext);
3003 unset($USER->enrol['enrolled'][$course->id]);
3006 if (isset($USER->enrol['tempguest'][$course->id])) {
3007 if ($USER->enrol['tempguest'][$course->id] == 0) {
3009 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3013 unset($USER->enrol['tempguest'][$course->id]);
3014 remove_temp_course_roles($coursecontext);
3021 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3022 if ($until !== false) {
3023 // active participants may always access, a timestamp in the future, 0 (always) or false.
3025 $until = ENROL_MAX_TIMESTAMP;
3027 $USER->enrol['enrolled'][$course->id] = $until;
3031 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
3032 $enrols = enrol_get_plugins(true);
3033 // first ask all enabled enrol instances in course if they want to auto enrol user
3034 foreach($instances as $instance) {
3035 if (!isset($enrols[$instance->enrol])) {
3038 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3039 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3040 if ($until !== false) {
3042 $until = ENROL_MAX_TIMESTAMP;
3044 $USER->enrol['enrolled'][$course->id] = $until;
3049 // if not enrolled yet try to gain temporary guest access
3051 foreach($instances as $instance) {
3052 if (!isset($enrols[$instance->enrol])) {
3055 // Get a duration for the guest access, a timestamp in the future or false.
3056 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3057 if ($until !== false and $until > time()) {
3058 $USER->enrol['tempguest'][$course->id] = $until;
3069 if ($preventredirect) {
3070 throw new require_login_exception('Not enrolled');
3072 if ($setwantsurltome) {
3073 $SESSION->wantsurl = qualified_me();
3075 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3079 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
3080 // conditional availability, etc
3081 if ($cm && !$cm->uservisible) {
3082 if ($preventredirect) {
3083 throw new require_login_exception('Activity is hidden');
3085 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
3088 // Finally access granted, update lastaccess times
3089 user_accesstime_log($course->id);
3094 * This function just makes sure a user is logged out.
3096 * @package core_access
3098 function require_logout() {
3104 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
3106 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
3107 foreach($authsequence as $authname) {
3108 $authplugin = get_auth_plugin($authname);
3109 $authplugin->prelogout_hook();
3113 events_trigger('user_logout', $params);
3114 session_get_instance()->terminate_current();
3119 * Weaker version of require_login()
3121 * This is a weaker version of {@link require_login()} which only requires login
3122 * when called from within a course rather than the site page, unless
3123 * the forcelogin option is turned on.
3124 * @see require_login()
3126 * @package core_access
3129 * @param mixed $courseorid The course object or id in question
3130 * @param bool $autologinguest Allow autologin guests if that is wanted
3131 * @param object $cm Course activity module if known
3132 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3133 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3134 * in order to keep redirects working properly. MDL-14495
3135 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3138 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
3139 global $CFG, $PAGE, $SITE;
3140 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3141 or (!is_object($courseorid) and $courseorid == SITEID);
3142 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3143 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
3144 // db queries so this is not really a performance concern, however it is obviously
3145 // better if you use get_fast_modinfo to get the cm before calling this.
3146 if (is_object($courseorid)) {
3147 $course = $courseorid;
3149 $course = clone($SITE);
3151 $modinfo = get_fast_modinfo($course);
3152 $cm = $modinfo->get_cm($cm->id);
3154 if (!empty($CFG->forcelogin)) {
3155 // login required for both SITE and courses
3156 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3158 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3159 // always login for hidden activities
3160 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3162 } else if ($issite) {
3163 //login for SITE not required
3164 if ($cm and empty($cm->visible)) {
3165 // hidden activities are not accessible without login
3166 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3167 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3168 // not-logged-in users do not have any group membership
3169 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3171 // We still need to instatiate PAGE vars properly so that things
3172 // that rely on it like navigation function correctly.
3173 if (!empty($courseorid)) {
3174 if (is_object($courseorid)) {
3175 $course = $courseorid;
3177 $course = clone($SITE);
3180 if ($cm->course != $course->id) {
3181 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3183 $PAGE->set_cm($cm, $course);
3184 $PAGE->set_pagelayout('incourse');
3186 $PAGE->set_course($course);
3189 // If $PAGE->course, and hence $PAGE->context, have not already been set
3190 // up properly, set them up now.
3191 $PAGE->set_course($PAGE->course);
3193 //TODO: verify conditional activities here
3194 user_accesstime_log(SITEID);
3199 // course login always required
3200 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3205 * Require key login. Function terminates with error if key not found or incorrect.
3211 * @uses NO_MOODLE_COOKIES
3212 * @uses PARAM_ALPHANUM
3213 * @param string $script unique script identifier
3214 * @param int $instance optional instance id
3215 * @return int Instance ID
3217 function require_user_key_login($script, $instance=null) {
3218 global $USER, $SESSION, $CFG, $DB;
3220 if (!NO_MOODLE_COOKIES) {
3221 print_error('sessioncookiesdisable');
3225 @session_write_close();
3227 $keyvalue = required_param('key', PARAM_ALPHANUM);
3229 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3230 print_error('invalidkey');
3233 if (!empty($key->validuntil) and $key->validuntil < time()) {
3234 print_error('expiredkey');
3237 if ($key->iprestriction) {
3238 $remoteaddr = getremoteaddr(null);
3239 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3240 print_error('ipmismatch');
3244 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
3245 print_error('invaliduserid');
3248 /// emulate normal session
3249 enrol_check_plugins($user);
3250 session_set_user($user);
3252 /// note we are not using normal login
3253 if (!defined('USER_KEY_LOGIN')) {
3254 define('USER_KEY_LOGIN', true);
3257 /// return instance id - it might be empty
3258 return $key->instance;
3262 * Creates a new private user access key.
3265 * @param string $script unique target identifier
3266 * @param int $userid
3267 * @param int $instance optional instance id
3268 * @param string $iprestriction optional ip restricted access
3269 * @param timestamp $validuntil key valid only until given data
3270 * @return string access key value
3272 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3275 $key = new stdClass();
3276 $key->script = $script;
3277 $key->userid = $userid;
3278 $key->instance = $instance;
3279 $key->iprestriction = $iprestriction;
3280 $key->validuntil = $validuntil;
3281 $key->timecreated = time();
3283 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
3284 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3286 $key->value = md5($userid.'_'.time().random_string(40));
3288 $DB->insert_record('user_private_key', $key);
3293 * Delete the user's new private user access keys for a particular script.
3296 * @param string $script unique target identifier
3297 * @param int $userid
3300 function delete_user_key($script,$userid) {
3302 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3306 * Gets a private user access key (and creates one if one doesn't exist).
3309 * @param string $script unique target identifier
3310 * @param int $userid
3311 * @param int $instance optional instance id
3312 * @param string $iprestriction optional ip restricted access
3313 * @param timestamp $validuntil key valid only until given data
3314 * @return string access key value
3316 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3319 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3320 'instance'=>$instance, 'iprestriction'=>$iprestriction,
3321 'validuntil'=>$validuntil))) {
3324 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3330 * Modify the user table by setting the currently logged in user's
3331 * last login to now.
3335 * @return bool Always returns true
3337 function update_user_login_times() {
3340 if (isguestuser()) {
3341 // Do not update guest access times/ips for performance.
3347 $user = new stdClass();
3348 $user->id = $USER->id;
3350 // Make sure all users that logged in have some firstaccess.
3351 if ($USER->firstaccess == 0) {
3352 $USER->firstaccess = $user->firstaccess = $now;
3355 // Store the previous current as lastlogin.
3356 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3358 $USER->currentlogin = $user->currentlogin = $now;
3360 // Function user_accesstime_log() may not update immediately, better do it here.
3361 $USER->lastaccess = $user->lastaccess = $now;
3362 $USER->lastip = $user->lastip = getremoteaddr();
3364 $DB->update_record('user', $user);
3369 * Determines if a user has completed setting up their account.
3371 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3374 function user_not_fully_set_up($user) {
3375 if (isguestuser($user)) {
3378 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3382 * Check whether the user has exceeded the bounce threshold
3386 * @param user $user A {@link $USER} object
3387 * @return bool true=>User has exceeded bounce threshold
3389 function over_bounce_threshold($user) {
3392 if (empty($CFG->handlebounces)) {
3396 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3400 // set sensible defaults
3401 if (empty($CFG->minbounces)) {
3402 $CFG->minbounces = 10;
3404 if (empty($CFG->bounceratio)) {
3405 $CFG->bounceratio = .20;
3409 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3410 $bouncecount = $bounce->value;
3412 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3413 $sendcount = $send->value;
3415 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3419 * Used to increment or reset email sent count
3422 * @param user $user object containing an id
3423 * @param bool $reset will reset the count to 0
3426 function set_send_count($user,$reset=false) {
3429 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3433 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3434 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3435 $DB->update_record('user_preferences', $pref);
3437 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3439 $pref = new stdClass();
3440 $pref->name = 'email_send_count';
3442 $pref->userid = $user->id;
3443 $DB->insert_record('user_preferences', $pref, false);
3448 * Increment or reset user's email bounce count
3451 * @param user $user object containing an id
3452 * @param bool $reset will reset the count to 0
3454 function set_bounce_count($user,$reset=false) {
3457 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3458 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3459 $DB->update_record('user_preferences', $pref);
3461 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3463 $pref = new stdClass();
3464 $pref->name = 'email_bounce_count';
3466 $pref->userid = $user->id;
3467 $DB->insert_record('user_preferences', $pref, false);
3472 * Keeps track of login attempts
3476 function update_login_count() {
3481 if (empty($SESSION->logincount)) {
3482 $SESSION->logincount = 1;
3484 $SESSION->logincount++;
3487 if ($SESSION->logincount > $max_logins) {
3488 unset($SESSION->wantsurl);
3489 print_error('errortoomanylogins');
3494 * Resets login attempts
3498 function reset_login_count() {
3501 $SESSION->logincount = 0;
3505 * Determines if the currently logged in user is in editing mode.
3506 * Note: originally this function had $userid parameter - it was not usable anyway
3508 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3509 * @todo Deprecated function remove when ready
3512 * @uses DEBUG_DEVELOPER
3515 function isediting() {
3517 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3518 return $PAGE->user_is_editing();
3522 * Determines if the logged in user is currently moving an activity
3525 * @param int $courseid The id of the course being tested
3528 function ismoving($courseid) {
3531 if (!empty($USER->activitycopy)) {
3532 return ($USER->activitycopycourse == $courseid);
3538 * Returns a persons full name
3540 * Given an object containing firstname and lastname
3541 * values, this function returns a string with the
3542 * full name of the person.
3543 * The result may depend on system settings
3544 * or language. 'override' will force both names
3545 * to be used even if system settings specify one.
3549 * @param object $user A {@link $USER} object to get full name of
3550 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3553 function fullname($user, $override=false) {
3554 global $CFG, $SESSION;
3556 if (!isset($user->firstname) and !isset($user->lastname)) {
3561 if (!empty($CFG->forcefirstname)) {
3562 $user->firstname = $CFG->forcefirstname;
3564 if (!empty($CFG->forcelastname)) {
3565 $user->lastname = $CFG->forcelastname;
3569 if (!empty($SESSION->fullnamedisplay)) {
3570 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3573 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3574 return $user->firstname .' '. $user->lastname;
3576 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3577 return $user->lastname .' '. $user->firstname;
3579 } else if ($CFG->fullnamedisplay == 'firstname') {
3581 return get_string('fullnamedisplay', '', $user);
3583 return $user->firstname;
3587 return get_string('fullnamedisplay', '', $user);
3591 * Checks if current user is shown any extra fields when listing users.
3592 * @param object $context Context
3593 * @param array $already Array of fields that we're going to show anyway
3594 * so don't bother listing them
3595 * @return array Array of field names from user table, not including anything
3596 * listed in $already
3598 function get_extra_user_fields($context, $already = array()) {
3601 // Only users with permission get the extra fields
3602 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3606 // Split showuseridentity on comma
3607 if (empty($CFG->showuseridentity)) {
3608 // Explode gives wrong result with empty string
3611 $extra = explode(',', $CFG->showuseridentity);
3614 foreach ($extra as $key => $field) {
3615 if (in_array($field, $already)) {
3616 unset($extra[$key]);
3621 // For consistency, if entries are removed from array, renumber it
3622 // so they are numbered as you would expect
3623 $extra = array_merge($extra);
3629 * If the current user is to be shown extra user fields when listing or
3630 * selecting users, returns a string suitable for including in an SQL select
3631 * clause to retrieve those fields.
3632 * @param object $context Context
3633 * @param string $alias Alias of user table, e.g. 'u' (default none)
3634 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3635 * @param array $already Array of fields that we're going to include anyway
3636 * so don't list them (default none)
3637 * @return string Partial SQL select clause, beginning with comma, for example
3638 * ',u.idnumber,u.department' unless it is blank
3640 function get_extra_user_fields_sql($context, $alias='', $prefix='',
3641 $already = array()) {
3642 $fields = get_extra_user_fields($context, $already);
3644 // Add punctuation for alias
3645 if ($alias !== '') {
3648 foreach ($fields as $field) {
3649 $result .= ', ' . $alias . $field;
3651 $result .= ' AS ' . $prefix . $field;
3658 * Returns the display name of a field in the user table. Works for most fields
3659 * that are commonly displayed to users.
3660 * @param string $field Field name, e.g. 'phone1'
3661 * @return string Text description taken from language file, e.g. 'Phone number'
3663 function get_user_field_name($field) {
3664 // Some fields have language strings which are not the same as field name
3666 case 'phone1' : return get_string('phone');
3667 case 'url' : return get_string('webpage');
3668 case 'icq' : return get_string('icqnumber');
3669 case 'skype' : return get_string('skypeid');
3670 case 'aim' : return get_string('aimid');
3671 case 'yahoo' : return get_string('yahooid');
3672 case 'msn' : return get_string('msnid');
3674 // Otherwise just use the same lang string
3675 return get_string($field);
3679 * Returns whether a given authentication plugin exists.
3682 * @param string $auth Form of authentication to check for. Defaults to the
3683 * global setting in {@link $CFG}.
3684 * @return boolean Whether the plugin is available.
3686 function exists_auth_plugin($auth) {
3689 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3690 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3696 * Checks if a given plugin is in the list of enabled authentication plugins.
3698 * @param string $auth Authentication plugin.
3699 * @return boolean Whether the plugin is enabled.
3701 function is_enabled_auth($auth) {
3706 $enabled = get_enabled_auth_plugins();
3708 return in_array($auth, $enabled);
3712 * Returns an authentication plugin instance.
3715 * @param string $auth name of authentication plugin
3716 * @return auth_plugin_base An instance of the required authentication plugin.
3718 function get_auth_plugin($auth) {
3721 // check the plugin exists first
3722 if (! exists_auth_plugin($auth)) {
3723 print_error('authpluginnotfound', 'debug', '', $auth);
3726 // return auth plugin instance
3727 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3728 $class = "auth_plugin_$auth";
3733 * Returns array of active auth plugins.
3735 * @param bool $fix fix $CFG->auth if needed
3738 function get_enabled_auth_plugins($fix=false) {
3741 $default = array('manual', 'nologin');
3743 if (empty($CFG->auth)) {
3746 $auths = explode(',', $CFG->auth);
3750 $auths = array_unique($auths);
3751 foreach($auths as $k=>$authname) {
3752 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3756 $newconfig = implode(',', $auths);
3757 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3758 set_config('auth', $newconfig);
3762 return (array_merge($default, $auths));
3766 * Returns true if an internal authentication method is being used.
3767 * if method not specified then, global default is assumed
3769 * @param string $auth Form of authentication required
3772 function is_internal_auth($auth) {
3773 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3774 return $authplugin->is_internal();
3778 * Returns true if the user is a 'restored' one
3780 * Used in the login process to inform the user
3781 * and allow him/her to reset the password
3785 * @param string $username username to be checked
3788 function is_restored_user($username) {
3791 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3795 * Returns an array of user fields
3797 * @return array User field/column names
3799 function get_user_fieldnames() {
3802 $fieldarray = $DB->get_columns('user');
3803 unset($fieldarray['id']);
3804 $fieldarray = array_keys($fieldarray);
3810 * Creates a bare-bones user record
3812 * @todo Outline auth types and provide code example
3814 * @param string $username New user's username to add to record
3815 * @param string $password New user's password to add to record
3816 * @param string $auth Form of authentication required
3817 * @return stdClass A complete user object
3819 function create_user_record($username, $password, $auth = 'manual') {
3822 //just in case check text case
3823 $username = trim(textlib::strtolower($username));
3825 $authplugin = get_auth_plugin($auth);
3827 $newuser = new stdClass();
3829 if ($newinfo = $authplugin->get_userinfo($username)) {
3830 $newinfo = truncate_userinfo($newinfo);
3831 foreach ($newinfo as $key => $value){
3832 $newuser->$key = $value;
3836 if (!empty($newuser->email)) {
3837 if (email_is_not_allowed($newuser->email)) {
3838 unset($newuser->email);
3842 if (!isset($newuser->city)) {
3843 $newuser->city = '';
3846 $newuser->auth = $auth;
3847 $newuser->username = $username;
3850 // user CFG lang for user if $newuser->lang is empty
3851 // or $user->lang is not an installed language
3852 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3853 $newuser->lang = $CFG->lang;
3855 $newuser->confirmed = 1;
3856 $newuser->lastip = getremoteaddr();
3857 $newuser->timecreated = time();
3858 $newuser->timemodified = $newuser->timecreated;
3859 $newuser->mnethostid = $CFG->mnet_localhost_id;
3861 $newuser->id = $DB->insert_record('user', $newuser);
3862 $user = get_complete_user_data('id', $newuser->id);
3863 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3864 set_user_preference('auth_forcepasswordchange', 1, $user);
3866 update_internal_user_password($user, $password);
3868 // fetch full user record for the event, the complete user data contains too much info
3869 // and we want to be consistent with other places that trigger this event
3870 events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
3876 * Will update a local user record from an external source.
3877 * (MNET users can not be updated using this method!)
3879 * @param string $username user's username to update the record
3880 * @return stdClass A complete user object
3882 function update_user_record($username) {
3885 $username = trim(textlib::strtolower($username)); /// just in case check text case
3887 $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
3889 $userauth = get_auth_plugin($oldinfo->auth);
3891 if ($newinfo = $userauth->get_userinfo($username)) {
3892 $newinfo = truncate_userinfo($newinfo);
3893 foreach ($newinfo as $key => $value){
3894 $key = strtolower($key);
3895 if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id'
3896 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3897 // unknown or must not be changed
3900 $confval = $userauth->config->{'field_updatelocal_' . $key};
3901 $lockval = $userauth->config->{'field_lock_' . $key};
3902 if (empty($confval) || empty($lockval)) {
3905 if ($confval === 'onlogin') {
3906 // MDL-4207 Don't overwrite modified user profile values with
3907 // empty LDAP values when 'unlocked if empty' is set. The purpose
3908 // of the setting 'unlocked if empty' is to allow the user to fill
3909 // in a value for the selected field _if LDAP is giving
3910 // nothing_ for this field. Thus it makes sense to let this value
3911 // stand in until LDAP is giving a value for this field.
3912 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3913 if ((string)$oldinfo->$key !== (string)$value) {
3914 $newuser[$key] = (string)$value;
3920 $newuser['id'] = $oldinfo->id;
3921 $newuser['timemodified'] = time();
3922 $DB->update_record('user', $newuser);
3923 // fetch full user record for the event, the complete user data contains too much info
3924 // and we want to be consistent with other places that trigger this event
3925 events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id)));
3929 return get_complete_user_data('id', $oldinfo->id);
3933 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3934 * which may have large fields
3936 * @todo Add vartype handling to ensure $info is an array
3938 * @param array $info Array of user properties to truncate if needed
3939 * @return array The now truncated information that was passed in
3941 function truncate_userinfo($info) {
3942 // define the limits
3952 'institution' => 40,
3960 // apply where needed
3961 foreach (array_keys($info) as $key) {
3962 if (!empty($limit[$key])) {
3963 $info[$key] = trim(textlib::substr($info[$key],0, $limit[$key]));
3971 * Marks user deleted in internal user database and notifies the auth plugin.
3972 * Also unenrols user from all roles and does other cleanup.
3974 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3976 * @param stdClass $user full user object before delete
3977 * @return boolean success
3978 * @throws coding_exception if invalid $user parameter detected
3980 function delete_user(stdClass $user) {
3982 require_once($CFG->libdir.'/grouplib.php');
3983 require_once($CFG->libdir.'/gradelib.php');
3984 require_once($CFG->dirroot.'/message/lib.php');
3985 require_once($CFG->dirroot.'/tag/lib.php');
3987 // Make sure nobody sends bogus record type as parameter.
3988 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
3989 throw new coding_exception('Invalid $user parameter in delete_user() detected');
3992 // Better not trust the parameter and fetch the latest info,
3993 // this will be very expensive anyway.
3994 if (!$user = $DB->get_record('user', array('id'=>$user->id))) {
3995 debugging('Attempt to delete unknown user account.');
3999 // There must be always exactly one guest record,
4000 // originally the guest account was identified by username only,
4001 // now we use $CFG->siteguest for performance reasons.
4002 if ($user->username === 'guest' or isguestuser($user)) {
4003 debugging('Guest user account can not be deleted.');
4007 // Admin can be theoretically from different auth plugin,
4008 // but we want to prevent deletion of internal accoutns only,
4009 // if anything goes wrong ppl may force somebody to be admin via
4010 // config.php setting $CFG->siteadmins.
4011 if ($user->auth === 'manual' and is_siteadmin($user)) {
4012 debugging('Local administrator accounts can not be deleted.');
4016 // delete all grades - backup is kept in grade_grades_history table
4017 grade_user_delete($user->id);
4019 //move unread messages from this user to read
4020 message_move_userfrom_unread2read($user->id);
4022 // TODO: remove from cohorts using standard API here
4025 tag_set('user', $user->id, array());
4027 // unconditionally unenrol from all courses
4028 enrol_user_delete($user);
4030 // unenrol from all roles in all contexts
4031 role_unassign_all(array('userid'=>$user->id)); // this might be slow but it is really needed - modules might do some extra cleanup!
4033 //now do a brute force cleanup
4035 // remove from all cohorts
4036 $DB->delete_records('cohort_members', array('userid'=>$user->id));
4038 // remove from all groups
4039 $DB->delete_records('groups_members', array('userid'=>$user->id));
4041 // brute force unenrol from all courses
4042 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
4044 // purge user preferences
4045 $DB->delete_records('user_preferences', array('userid'=>$user->id));
4047 // purge user extra profile info
4048 $DB->delete_records('user_info_data', array('userid'=>$user->id));
4050 // last course access not necessary either
4051 $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
4053 // remove all user tokens
4054 $DB->delete_records('external_tokens', array('userid'=>$user->id));
4056 // unauthorise the user for all services
4057 $DB->delete_records('external_services_users', array('userid'=>$user->id));
4059 // force logout - may fail if file based sessions used, sorry
4060 session_kill_user($user->id);
4062 // now do a final accesslib cleanup - removes all role assignments in user context and context itself
4063 delete_context(CONTEXT_USER, $user->id);
4065 // workaround for bulk deletes of users with the same email address
4066 $delname = "$user->email.".time();
4067 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
4071 // mark internal user record as "deleted"
4072 $updateuser = new stdClass();
4073 $updateuser->id = $user->id;
4074 $updateuser->deleted = 1;
4075 $updateuser->username = $delname; // Remember it just in case
4076 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
4077 $updateuser->idnumber = ''; // Clear this field to free it up
4078 $updateuser->picture = 0;
4079 $updateuser->timemodified = time();
4081 $DB->update_record('user', $updateuser);
4082 // Add this action to log
4083 add_to_log(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
4086 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4087 // should know about this updated property persisted to the user's table.
4088 $user->timemodified = $updateuser->timemodified;
4090 // notify auth plugin - do not block the delete even when plugin fails
4091 $authplugin = get_auth_plugin($user->auth);
4092 $authplugin->user_delete($user);
4094 // any plugin that needs to cleanup should register this event
4095 events_trigger('user_deleted', $user);
4101 * Retrieve the guest user object
4105 * @return user A {@link $USER} object
4107 function guest_user() {
4110 if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
4111 $newuser->confirmed = 1;
4112 $newuser->lang = $CFG->lang;
4113 $newuser->lastip = getremoteaddr();
4120 * Authenticates a user against the chosen authentication mechanism
4122 * Given a username and password, this function looks them
4123 * up using the currently selected authentication mechanism,
4124 * and if the authentication is successful, it returns a
4125 * valid $user object from the 'user' table.
4127 * Uses auth_ functions from the currently active auth module
4129 * After authenticate_user_login() returns success, you will need to
4130 * log that the user has logged in, and call complete_user_login() to set
4133 * Note: this function works only with non-mnet accounts!
4135 * @param string $username User's username
4136 * @param string $password User's password
4137 * @return user|flase A {@link $USER} object or false if error
4139 function authenticate_user_login($username, $password) {
4142 $authsenabled = get_enabled_auth_plugins();
4144 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4145 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
4146 if (!empty($user->suspended)) {
4147 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4148 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4151 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4152 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4153 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4156 $auths = array($auth);
4159 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4160 if ($DB->get_field('user', 'id', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>1))) {
4161 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4165 // Do not try to authenticate non-existent accounts when user creation is not disabled.
4166 if (!empty($CFG->authpreventaccountcreation)) {
4167 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4168 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".$_SERVER['HTTP_USER_AGENT']);
4172 // User does not exist
4173 $auths = $authsenabled;
4174 $user = new stdClass();
4178 foreach ($auths as $auth) {
4179 $authplugin = get_auth_plugin($auth);
4181 // on auth fail fall through to the next plugin
4182 if (!$authplugin->user_login($username, $password)) {
4186 // successful authentication
4187 if ($user->id) { // User already exists in database
4188 if (empty($user->auth)) { // For some reason auth isn't set yet
4189 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
4190 $user->auth = $auth;
4193 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
4195 if ($authplugin->is_synchronised_with_external()) { // update user record from external DB
4196 $user = update_user_record($username);
4199 // Create account, we verified above that user creation is allowed.
4200 $user = create_user_record($username, $password, $auth);
4203 $authplugin->sync_roles($user);
4205 foreach ($authsenabled as $hau) {
4206 $hauth = get_auth_plugin($hau);
4207 $hauth->user_authenticated_hook($user, $username, $password);
4210 if (empty($user->id)) {
4214 if (!empty($user->suspended)) {
4215 // just in case some auth plugin suspended account
4216 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4217 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4224 // failed if all the plugins have failed
4225 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4226 if (debugging('', DEBUG_ALL)) {
4227 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4233 * Call to complete the user login process after authenticate_user_login()
4234 * has succeeded. It will setup the $USER variable and other required bits
4238 * - It will NOT log anything -- up to the caller to decide what to log.
4239 * - this function does not set any cookies any more!
4241 * @param object $user
4242 * @return object A {@link $USER} object - BC only, do not use
4244 function complete_user_login($user) {
4247 // regenerate session id and delete old session,
4248 // this helps prevent session fixation attacks from the same domain
4249 session_regenerate_id(true);
4251 // let enrol plugins deal with new enrolments if necessary
4252 enrol_check_plugins($user);
4254 // check enrolments, load caps and setup $USER object
4255 session_set_user($user);
4257 // reload preferences from DB
4258 unset($USER->preference);
4259 check_user_preferences_loaded($USER);
4261 // update login times
4262 update_user_login_times();
4264 // extra session prefs init
4265 set_login_session_preferences();
4267 if (isguestuser()) {
4268 // no need to continue when user is THE guest
4272 /// Select password change url
4273 $userauth = get_auth_plugin($USER->auth);
4275 /// check whether the user should be changing password
4276 if (get_user_preferences('auth_forcepasswordchange', false)){
4277 if ($userauth->can_change_password()) {
4278 if ($changeurl = $userauth->change_password_url()) {
4279 redirect($changeurl);
4281 redirect($CFG->httpswwwroot.'/login/change_password.php');
4284 print_error('nopasswordchangeforced', 'auth');
4291 * Compare password against hash stored in internal user table.
4292 * If necessary it also updates the stored hash to new format.
4294 * @param stdClass $user (password property may be updated)
4295 * @param string $password plain text password
4296 * @return bool is password valid?
4298 function validate_internal_user_password($user, $password) {
4301 if (!isset($CFG->passwordsaltmain)) {
4302 $CFG->passwordsaltmain = '';
4307 if ($user->password === 'not cached') {
4308 // internal password is not used at all, it can not validate
4310 } else if ($user->password === md5($password.$CFG->passwordsaltmain)
4311 or $user->password === md5($password)
4312 or $user->password === md5(addslashes($password).$CFG->passwordsaltmain)
4313 or $user->password === md5(addslashes($password))) {
4314 // note: we are intentionally using the addslashes() here because we
4315 // need to accept old password hashes of passwords with magic quotes
4319 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
4320 $alt = 'passwordsaltalt'.$i;
4321 if (!empty($CFG->$alt)) {
4322 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4331 // force update of password hash using latest main password salt and encoding if needed
4332 update_internal_user_password($user, $password);
4339 * Calculate hashed value from password using current hash mechanism.
4341 * @param string $password
4342 * @return string password hash
4344 function hash_internal_user_password($password) {