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
258 define('PARAM_INTEGER', 'int');
261 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
263 define('PARAM_NUMBER', 'float');
266 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
267 * NOTE: originally alias for PARAM_APLHA
269 define('PARAM_ACTION', 'alphanumext');
272 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
273 * NOTE: originally alias for PARAM_APLHA
275 define('PARAM_FORMAT', 'alphanumext');
278 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
280 define('PARAM_MULTILANG', 'text');
283 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
284 * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
285 * America/Port-au-Prince)
287 define('PARAM_TIMEZONE', 'timezone');
290 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
292 define('PARAM_CLEANFILE', 'file');
295 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
296 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
297 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
298 * NOTE: numbers and underscores are strongly discouraged in plugin names!
300 define('PARAM_COMPONENT', 'component');
303 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
304 * It is usually used together with context id and component.
305 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
307 define('PARAM_AREA', 'area');
310 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
311 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
312 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
314 define('PARAM_PLUGIN', 'plugin');
320 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
322 define('VALUE_REQUIRED', 1);
325 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
327 define('VALUE_OPTIONAL', 2);
330 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
332 define('VALUE_DEFAULT', 0);
335 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
337 define('NULL_NOT_ALLOWED', false);
340 * NULL_ALLOWED - the parameter can be set to null in the database
342 define('NULL_ALLOWED', true);
346 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
348 define('PAGE_COURSE_VIEW', 'course-view');
350 /** Get remote addr constant */
351 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
352 /** Get remote addr constant */
353 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
355 /// Blog access level constant declaration ///
356 define ('BLOG_USER_LEVEL', 1);
357 define ('BLOG_GROUP_LEVEL', 2);
358 define ('BLOG_COURSE_LEVEL', 3);
359 define ('BLOG_SITE_LEVEL', 4);
360 define ('BLOG_GLOBAL_LEVEL', 5);
365 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
366 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
367 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
369 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
371 define('TAG_MAX_LENGTH', 50);
373 /// Password policy constants ///
374 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
375 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
376 define ('PASSWORD_DIGITS', '0123456789');
377 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
379 /// Feature constants ///
380 // Used for plugin_supports() to report features that are, or are not, supported by a module.
382 /** True if module can provide a grade */
383 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
384 /** True if module supports outcomes */
385 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
386 /** True if module supports advanced grading methods */
387 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
388 /** True if module controls the grade visibility over the gradebook */
389 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
391 /** True if module has code to track whether somebody viewed it */
392 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
393 /** True if module has custom completion rules */
394 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
396 /** True if module has no 'view' page (like label) */
397 define('FEATURE_NO_VIEW_LINK', 'viewlink');
398 /** True if module supports outcomes */
399 define('FEATURE_IDNUMBER', 'idnumber');
400 /** True if module supports groups */
401 define('FEATURE_GROUPS', 'groups');
402 /** True if module supports groupings */
403 define('FEATURE_GROUPINGS', 'groupings');
404 /** True if module supports groupmembersonly */
405 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
407 /** Type of module */
408 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
409 /** True if module supports intro editor */
410 define('FEATURE_MOD_INTRO', 'mod_intro');
411 /** True if module has default completion */
412 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
414 define('FEATURE_COMMENT', 'comment');
416 define('FEATURE_RATE', 'rate');
417 /** True if module supports backup/restore of moodle2 format */
418 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
420 /** True if module can show description on course main page */
421 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
423 /** Unspecified module archetype */
424 define('MOD_ARCHETYPE_OTHER', 0);
425 /** Resource-like type module */
426 define('MOD_ARCHETYPE_RESOURCE', 1);
427 /** Assignment module archetype */
428 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
429 /** System (not user-addable) module archetype */
430 define('MOD_ARCHETYPE_SYSTEM', 3);
433 * Security token used for allowing access
434 * from external application such as web services.
435 * Scripts do not use any session, performance is relatively
436 * low because we need to load access info in each request.
437 * Scripts are executed in parallel.
439 define('EXTERNAL_TOKEN_PERMANENT', 0);
442 * Security token used for allowing access
443 * of embedded applications, the code is executed in the
444 * active user session. Token is invalidated after user logs out.
445 * Scripts are executed serially - normal session locking is used.
447 define('EXTERNAL_TOKEN_EMBEDDED', 1);
450 * The home page should be the site home
452 define('HOMEPAGE_SITE', 0);
454 * The home page should be the users my page
456 define('HOMEPAGE_MY', 1);
458 * The home page can be chosen by the user
460 define('HOMEPAGE_USER', 2);
463 * Hub directory url (should be moodle.org)
465 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
469 * Moodle.org url (should be moodle.org)
471 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
474 * Moodle mobile app service name
476 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
479 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
481 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
483 /// PARAMETER HANDLING ////////////////////////////////////////////////////
486 * Returns a particular value for the named variable, taken from
487 * POST or GET. If the parameter doesn't exist then an error is
488 * thrown because we require this variable.
490 * This function should be used to initialise all required values
491 * in a script that are based on parameters. Usually it will be
493 * $id = required_param('id', PARAM_INT);
495 * Please note the $type parameter is now required and the value can not be array.
497 * @param string $parname the name of the page parameter we want
498 * @param string $type expected type of parameter
501 function required_param($parname, $type) {
502 if (func_num_args() != 2 or empty($parname) or empty($type)) {
503 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
505 if (isset($_POST[$parname])) { // POST has precedence
506 $param = $_POST[$parname];
507 } else if (isset($_GET[$parname])) {
508 $param = $_GET[$parname];
510 print_error('missingparam', '', '', $parname);
513 if (is_array($param)) {
514 debugging('Invalid array parameter detected in required_param(): '.$parname);
515 // TODO: switch to fatal error in Moodle 2.3
516 //print_error('missingparam', '', '', $parname);
517 return required_param_array($parname, $type);
520 return clean_param($param, $type);
524 * Returns a particular array value for the named variable, taken from
525 * POST or GET. If the parameter doesn't exist then an error is
526 * thrown because we require this variable.
528 * This function should be used to initialise all required values
529 * in a script that are based on parameters. Usually it will be
531 * $ids = required_param_array('ids', PARAM_INT);
533 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
535 * @param string $parname the name of the page parameter we want
536 * @param string $type expected type of parameter
539 function required_param_array($parname, $type) {
540 if (func_num_args() != 2 or empty($parname) or empty($type)) {
541 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
543 if (isset($_POST[$parname])) { // POST has precedence
544 $param = $_POST[$parname];
545 } else if (isset($_GET[$parname])) {
546 $param = $_GET[$parname];
548 print_error('missingparam', '', '', $parname);
550 if (!is_array($param)) {
551 print_error('missingparam', '', '', $parname);
555 foreach($param as $key=>$value) {
556 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
557 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
560 $result[$key] = clean_param($value, $type);
567 * Returns a particular value for the named variable, taken from
568 * POST or GET, otherwise returning a given default.
570 * This function should be used to initialise all optional values
571 * in a script that are based on parameters. Usually it will be
573 * $name = optional_param('name', 'Fred', PARAM_TEXT);
575 * Please note the $type parameter is now required and the value can not be array.
577 * @param string $parname the name of the page parameter we want
578 * @param mixed $default the default value to return if nothing is found
579 * @param string $type expected type of parameter
582 function optional_param($parname, $default, $type) {
583 if (func_num_args() != 3 or empty($parname) or empty($type)) {
584 throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
586 if (!isset($default)) {
590 if (isset($_POST[$parname])) { // POST has precedence
591 $param = $_POST[$parname];
592 } else if (isset($_GET[$parname])) {
593 $param = $_GET[$parname];
598 if (is_array($param)) {
599 debugging('Invalid array parameter detected in required_param(): '.$parname);
600 // TODO: switch to $default in Moodle 2.3
602 return optional_param_array($parname, $default, $type);
605 return clean_param($param, $type);
609 * Returns a particular array value for the named variable, taken from
610 * POST or GET, otherwise returning a given default.
612 * This function should be used to initialise all optional values
613 * in a script that are based on parameters. Usually it will be
615 * $ids = optional_param('id', array(), PARAM_INT);
617 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
619 * @param string $parname the name of the page parameter we want
620 * @param mixed $default the default value to return if nothing is found
621 * @param string $type expected type of parameter
624 function optional_param_array($parname, $default, $type) {
625 if (func_num_args() != 3 or empty($parname) or empty($type)) {
626 throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
629 if (isset($_POST[$parname])) { // POST has precedence
630 $param = $_POST[$parname];
631 } else if (isset($_GET[$parname])) {
632 $param = $_GET[$parname];
636 if (!is_array($param)) {
637 debugging('optional_param_array() expects array parameters only: '.$parname);
642 foreach($param as $key=>$value) {
643 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
644 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
647 $result[$key] = clean_param($value, $type);
654 * Strict validation of parameter values, the values are only converted
655 * to requested PHP type. Internally it is using clean_param, the values
656 * before and after cleaning must be equal - otherwise
657 * an invalid_parameter_exception is thrown.
658 * Objects and classes are not accepted.
660 * @param mixed $param
661 * @param string $type PARAM_ constant
662 * @param bool $allownull are nulls valid value?
663 * @param string $debuginfo optional debug information
664 * @return mixed the $param value converted to PHP type
665 * @throws invalid_parameter_exception if $param is not of given type
667 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
668 if (is_null($param)) {
669 if ($allownull == NULL_ALLOWED) {
672 throw new invalid_parameter_exception($debuginfo);
675 if (is_array($param) or is_object($param)) {
676 throw new invalid_parameter_exception($debuginfo);
679 $cleaned = clean_param($param, $type);
681 if ($type == PARAM_FLOAT) {
682 // Do not detect precision loss here.
683 if (is_float($param) or is_int($param)) {
685 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
686 throw new invalid_parameter_exception($debuginfo);
688 } else if ((string)$param !== (string)$cleaned) {
689 // conversion to string is usually lossless
690 throw new invalid_parameter_exception($debuginfo);
697 * Makes sure array contains only the allowed types,
698 * this function does not validate array key names!
700 * $options = clean_param($options, PARAM_INT);
703 * @param array $param the variable array we are cleaning
704 * @param string $type expected format of param after cleaning.
705 * @param bool $recursive clean recursive arrays
708 function clean_param_array(array $param = null, $type, $recursive = false) {
709 $param = (array)$param; // convert null to empty array
710 foreach ($param as $key => $value) {
711 if (is_array($value)) {
713 $param[$key] = clean_param_array($value, $type, true);
715 throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
718 $param[$key] = clean_param($value, $type);
725 * Used by {@link optional_param()} and {@link required_param()} to
726 * clean the variables and/or cast to specific types, based on
729 * $course->format = clean_param($course->format, PARAM_ALPHA);
730 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
733 * @param mixed $param the variable we are cleaning
734 * @param string $type expected format of param after cleaning.
737 function clean_param($param, $type) {
741 if (is_array($param)) {
742 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
743 } else if (is_object($param)) {
744 if (method_exists($param, '__toString')) {
745 $param = $param->__toString();
747 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
752 case PARAM_RAW: // no cleaning at all
753 $param = fix_utf8($param);
756 case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
757 $param = fix_utf8($param);
760 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
761 // this is deprecated!, please use more specific type instead
762 if (is_numeric($param)) {
765 $param = fix_utf8($param);
766 return clean_text($param); // Sweep for scripts, etc
768 case PARAM_CLEANHTML: // clean html fragment
769 $param = fix_utf8($param);
770 $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
774 return (int)$param; // Convert to integer
778 return (float)$param; // Convert to float
780 case PARAM_ALPHA: // Remove everything not a-z
781 return preg_replace('/[^a-zA-Z]/i', '', $param);
783 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
784 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
786 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
787 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
789 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
790 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
792 case PARAM_SEQUENCE: // Remove everything not 0-9,
793 return preg_replace('/[^0-9,]/i', '', $param);
795 case PARAM_BOOL: // Convert to 1 or 0
796 $tempstr = strtolower($param);
797 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
799 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
802 $param = empty($param) ? 0 : 1;
806 case PARAM_NOTAGS: // Strip all tags
807 $param = fix_utf8($param);
808 return strip_tags($param);
810 case PARAM_TEXT: // leave only tags needed for multilang
811 $param = fix_utf8($param);
812 // if the multilang syntax is not correct we strip all tags
813 // because it would break xhtml strict which is required for accessibility standards
814 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
816 if (strpos($param, '</lang>') !== false) {
817 // old and future mutilang syntax
818 $param = strip_tags($param, '<lang>');
819 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
823 foreach ($matches[0] as $match) {
824 if ($match === '</lang>') {
832 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
843 } else if (strpos($param, '</span>') !== false) {
844 // current problematic multilang syntax
845 $param = strip_tags($param, '<span>');
846 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
850 foreach ($matches[0] as $match) {
851 if ($match === '</span>') {
859 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
871 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
872 return strip_tags($param);
874 case PARAM_COMPONENT:
875 // we do not want any guessing here, either the name is correct or not
876 // please note only normalised component names are accepted
877 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
880 if (strpos($param, '__') !== false) {
883 if (strpos($param, 'mod_') === 0) {
884 // module names must not contain underscores because we need to differentiate them from invalid plugin types
885 if (substr_count($param, '_') != 1) {
893 // we do not want any guessing here, either the name is correct or not
894 if (!preg_match('/^[a-z][a-z0-9_]*[a-z0-9]$/', $param)) {
897 if (strpos($param, '__') !== false) {
902 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
903 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
905 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
906 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
908 case PARAM_FILE: // Strip all suspicious characters from filename
909 $param = fix_utf8($param);
910 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
911 $param = preg_replace('~\.\.+~', '', $param);
912 if ($param === '.') {
917 case PARAM_PATH: // Strip all suspicious characters from file path
918 $param = fix_utf8($param);
919 $param = str_replace('\\', '/', $param);
920 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
921 $param = preg_replace('~\.\.+~', '', $param);
922 $param = preg_replace('~//+~', '/', $param);
923 return preg_replace('~/(\./)+~', '/', $param);
925 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
926 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
927 // match ipv4 dotted quad
928 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
929 // confirm values are ok
933 || $match[4] > 255 ) {
934 // hmmm, what kind of dotted quad is this?
937 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
938 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
939 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
941 // all is ok - $param is respected
948 case PARAM_URL: // allow safe ftp, http, mailto urls
949 $param = fix_utf8($param);
950 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
951 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
952 // all is ok, param is respected
954 $param =''; // not really ok
958 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
959 $param = clean_param($param, PARAM_URL);
960 if (!empty($param)) {
961 if (preg_match(':^/:', $param)) {
962 // root-relative, ok!
963 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
964 // absolute, and matches our wwwroot
966 // relative - let's make sure there are no tricks
967 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
977 $param = trim($param);
978 // PEM formatted strings may contain letters/numbers and the symbols
982 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
983 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
984 list($wholething, $body) = $matches;
985 unset($wholething, $matches);
986 $b64 = clean_param($body, PARAM_BASE64);
988 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
996 if (!empty($param)) {
997 // PEM formatted strings may contain letters/numbers and the symbols
1001 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1004 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1005 // Each line of base64 encoded data must be 64 characters in
1006 // length, except for the last line which may be less than (or
1007 // equal to) 64 characters long.
1008 for ($i=0, $j=count($lines); $i < $j; $i++) {
1010 if (64 < strlen($lines[$i])) {
1016 if (64 != strlen($lines[$i])) {
1020 return implode("\n",$lines);
1026 $param = fix_utf8($param);
1027 // Please note it is not safe to use the tag name directly anywhere,
1028 // it must be processed with s(), urlencode() before embedding anywhere.
1029 // remove some nasties
1030 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1031 //convert many whitespace chars into one
1032 $param = preg_replace('/\s+/', ' ', $param);
1033 $param = textlib::substr(trim($param), 0, TAG_MAX_LENGTH);
1037 $param = fix_utf8($param);
1038 $tags = explode(',', $param);
1040 foreach ($tags as $tag) {
1041 $res = clean_param($tag, PARAM_TAG);
1047 return implode(',', $result);
1052 case PARAM_CAPABILITY:
1053 if (get_capability_info($param)) {
1059 case PARAM_PERMISSION:
1060 $param = (int)$param;
1061 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1068 $param = clean_param($param, PARAM_PLUGIN);
1069 if (empty($param)) {
1071 } else if (exists_auth_plugin($param)) {
1078 $param = clean_param($param, PARAM_SAFEDIR);
1079 if (get_string_manager()->translation_exists($param)) {
1082 return ''; // Specified language is not installed or param malformed
1086 $param = clean_param($param, PARAM_PLUGIN);
1087 if (empty($param)) {
1089 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1091 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1094 return ''; // Specified theme is not installed
1097 case PARAM_USERNAME:
1098 $param = fix_utf8($param);
1099 $param = str_replace(" " , "", $param);
1100 $param = textlib::strtolower($param); // Convert uppercase to lowercase MDL-16919
1101 if (empty($CFG->extendedusernamechars)) {
1102 // regular expression, eliminate all chars EXCEPT:
1103 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1104 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1109 $param = fix_utf8($param);
1110 if (validate_email($param)) {
1116 case PARAM_STRINGID:
1117 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1123 case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1124 $param = fix_utf8($param);
1125 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1126 if (preg_match($timezonepattern, $param)) {
1132 default: // throw error, switched parameters in optional_param or another serious problem
1133 print_error("unknownparamtype", '', '', $type);
1138 * Makes sure the data is using valid utf8, invalid characters are discarded.
1140 * Note: this function is not intended for full objects with methods and private properties.
1142 * @param mixed $value
1143 * @return mixed with proper utf-8 encoding
1145 function fix_utf8($value) {
1146 if (is_null($value) or $value === '') {
1149 } else if (is_string($value)) {
1150 if ((string)(int)$value === $value) {
1155 // Lower error reporting because glibc throws bogus notices.
1156 $olderror = error_reporting();
1157 if ($olderror & E_NOTICE) {
1158 error_reporting($olderror ^ E_NOTICE);
1161 // Note: this duplicates min_fix_utf8() intentionally.
1162 static $buggyiconv = null;
1163 if ($buggyiconv === null) {
1164 $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1168 if (function_exists('mb_convert_encoding')) {
1169 $subst = mb_substitute_character();
1170 mb_substitute_character('');
1171 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1172 mb_substitute_character($subst);
1175 // Warn admins on admin/index.php page.
1180 $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1183 if ($olderror & E_NOTICE) {
1184 error_reporting($olderror);
1189 } else if (is_array($value)) {
1190 foreach ($value as $k=>$v) {
1191 $value[$k] = fix_utf8($v);
1195 } else if (is_object($value)) {
1196 $value = clone($value); // do not modify original
1197 foreach ($value as $k=>$v) {
1198 $value->$k = fix_utf8($v);
1203 // this is some other type, no utf-8 here
1209 * Return true if given value is integer or string with integer value
1211 * @param mixed $value String or Int
1212 * @return bool true if number, false if not
1214 function is_number($value) {
1215 if (is_int($value)) {
1217 } else if (is_string($value)) {
1218 return ((string)(int)$value) === $value;
1225 * Returns host part from url
1226 * @param string $url full url
1227 * @return string host, null if not found
1229 function get_host_from_url($url) {
1230 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1238 * Tests whether anything was returned by text editor
1240 * This function is useful for testing whether something you got back from
1241 * the HTML editor actually contains anything. Sometimes the HTML editor
1242 * appear to be empty, but actually you get back a <br> tag or something.
1244 * @param string $string a string containing HTML.
1245 * @return boolean does the string contain any actual content - that is text,
1246 * images, objects, etc.
1248 function html_is_blank($string) {
1249 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1253 * Set a key in global configuration
1255 * Set a key/value pair in both this session's {@link $CFG} global variable
1256 * and in the 'config' database table for future sessions.
1258 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1259 * In that case it doesn't affect $CFG.
1261 * A NULL value will delete the entry.
1265 * @param string $name the key to set
1266 * @param string $value the value to set (without magic quotes)
1267 * @param string $plugin (optional) the plugin scope, default NULL
1268 * @return bool true or exception
1270 function set_config($name, $value, $plugin=NULL) {
1273 if (empty($plugin)) {
1274 if (!array_key_exists($name, $CFG->config_php_settings)) {
1275 // So it's defined for this invocation at least
1276 if (is_null($value)) {
1279 $CFG->$name = (string)$value; // settings from db are always strings
1283 if ($DB->get_field('config', 'name', array('name'=>$name))) {
1284 if ($value === null) {
1285 $DB->delete_records('config', array('name'=>$name));
1287 $DB->set_field('config', 'value', $value, array('name'=>$name));
1290 if ($value !== null) {
1291 $config = new stdClass();
1292 $config->name = $name;
1293 $config->value = $value;
1294 $DB->insert_record('config', $config, false);
1298 } else { // plugin scope
1299 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1300 if ($value===null) {
1301 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1303 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1306 if ($value !== null) {
1307 $config = new stdClass();
1308 $config->plugin = $plugin;
1309 $config->name = $name;
1310 $config->value = $value;
1311 $DB->insert_record('config_plugins', $config, false);
1320 * Get configuration values from the global config table
1321 * or the config_plugins table.
1323 * If called with one parameter, it will load all the config
1324 * variables for one plugin, and return them as an object.
1326 * If called with 2 parameters it will return a string single
1327 * value or false if the value is not found.
1329 * @param string $plugin full component name
1330 * @param string $name default NULL
1331 * @return mixed hash-like object or single value, return false no config found
1333 function get_config($plugin, $name = NULL) {
1336 // normalise component name
1337 if ($plugin === 'moodle' or $plugin === 'core') {
1341 if (!empty($name)) { // the user is asking for a specific value
1342 if (!empty($plugin)) {
1343 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1344 // setting forced in config file
1345 return $CFG->forced_plugin_settings[$plugin][$name];
1347 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1350 if (array_key_exists($name, $CFG->config_php_settings)) {
1351 // setting force in config file
1352 return $CFG->config_php_settings[$name];
1354 return $DB->get_field('config', 'value', array('name'=>$name));
1359 // the user is after a recordset
1361 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1362 if (isset($CFG->forced_plugin_settings[$plugin])) {
1363 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1364 if (is_null($v) or is_array($v) or is_object($v)) {
1365 // we do not want any extra mess here, just real settings that could be saved in db
1366 unset($localcfg[$n]);
1368 //convert to string as if it went through the DB
1369 $localcfg[$n] = (string)$v;
1374 return (object)$localcfg;
1376 return new stdClass();
1380 // this part is not really used any more, but anyway...
1381 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1382 foreach($CFG->config_php_settings as $n=>$v) {
1383 if (is_null($v) or is_array($v) or is_object($v)) {
1384 // we do not want any extra mess here, just real settings that could be saved in db
1385 unset($localcfg[$n]);
1387 //convert to string as if it went through the DB
1388 $localcfg[$n] = (string)$v;
1391 return (object)$localcfg;
1396 * Removes a key from global configuration
1398 * @param string $name the key to set
1399 * @param string $plugin (optional) the plugin scope
1401 * @return boolean whether the operation succeeded.
1403 function unset_config($name, $plugin=NULL) {
1406 if (empty($plugin)) {
1408 $DB->delete_records('config', array('name'=>$name));
1410 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1417 * Remove all the config variables for a given plugin.
1419 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1420 * @return boolean whether the operation succeeded.
1422 function unset_all_config_for_plugin($plugin) {
1424 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1425 $like = $DB->sql_like('name', '?', true, true, false, '|');
1426 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1427 $DB->delete_records_select('config', $like, $params);
1432 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1434 * All users are verified if they still have the necessary capability.
1436 * @param string $value the value of the config setting.
1437 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1438 * @param bool $include admins, include administrators
1439 * @return array of user objects.
1441 function get_users_from_config($value, $capability, $includeadmins = true) {
1444 if (empty($value) or $value === '$@NONE@$') {
1448 // we have to make sure that users still have the necessary capability,
1449 // it should be faster to fetch them all first and then test if they are present
1450 // instead of validating them one-by-one
1451 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1452 if ($includeadmins) {
1453 $admins = get_admins();
1454 foreach ($admins as $admin) {
1455 $users[$admin->id] = $admin;
1459 if ($value === '$@ALL@$') {
1463 $result = array(); // result in correct order
1464 $allowed = explode(',', $value);
1465 foreach ($allowed as $uid) {
1466 if (isset($users[$uid])) {
1467 $user = $users[$uid];
1468 $result[$user->id] = $user;
1477 * Invalidates browser caches and cached data in temp
1480 function purge_all_caches() {
1483 reset_text_filters_cache();
1484 js_reset_all_caches();
1485 theme_reset_all_caches();
1486 get_string_manager()->reset_caches();
1487 textlib::reset_caches();
1489 // purge all other caches: rss, simplepie, etc.
1490 remove_dir($CFG->cachedir.'', true);
1492 // make sure cache dir is writable, throws exception if not
1493 make_cache_directory('');
1495 // hack: this script may get called after the purifier was initialised,
1496 // but we do not want to verify repeatedly this exists in each call
1497 make_cache_directory('htmlpurifier');
1501 * Get volatile flags
1503 * @param string $type
1504 * @param int $changedsince default null
1505 * @return records array
1507 function get_cache_flags($type, $changedsince=NULL) {
1510 $params = array('type'=>$type, 'expiry'=>time());
1511 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1512 if ($changedsince !== NULL) {
1513 $params['changedsince'] = $changedsince;
1514 $sqlwhere .= " AND timemodified > :changedsince";
1518 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1519 foreach ($flags as $flag) {
1520 $cf[$flag->name] = $flag->value;
1527 * Get volatile flags
1529 * @param string $type
1530 * @param string $name
1531 * @param int $changedsince default null
1532 * @return records array
1534 function get_cache_flag($type, $name, $changedsince=NULL) {
1537 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1539 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1540 if ($changedsince !== NULL) {
1541 $params['changedsince'] = $changedsince;
1542 $sqlwhere .= " AND timemodified > :changedsince";
1545 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1549 * Set a volatile flag
1551 * @param string $type the "type" namespace for the key
1552 * @param string $name the key to set
1553 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1554 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1555 * @return bool Always returns true
1557 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1560 $timemodified = time();
1561 if ($expiry===NULL || $expiry < $timemodified) {
1562 $expiry = $timemodified + 24 * 60 * 60;
1564 $expiry = (int)$expiry;
1567 if ($value === NULL) {
1568 unset_cache_flag($type,$name);
1572 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1573 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1574 return true; //no need to update; helps rcache too
1577 $f->expiry = $expiry;
1578 $f->timemodified = $timemodified;
1579 $DB->update_record('cache_flags', $f);
1581 $f = new stdClass();
1582 $f->flagtype = $type;
1585 $f->expiry = $expiry;
1586 $f->timemodified = $timemodified;
1587 $DB->insert_record('cache_flags', $f);
1593 * Removes a single volatile flag
1596 * @param string $type the "type" namespace for the key
1597 * @param string $name the key to set
1600 function unset_cache_flag($type, $name) {
1602 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1607 * Garbage-collect volatile flags
1609 * @return bool Always returns true
1611 function gc_cache_flags() {
1613 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1617 // USER PREFERENCE API
1620 * Refresh user preference cache. This is used most often for $USER
1621 * object that is stored in session, but it also helps with performance in cron script.
1623 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1626 * @category preference
1628 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1629 * @param int $cachelifetime Cache life time on the current page (in seconds)
1630 * @throws coding_exception
1633 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1635 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1637 if (!isset($user->id)) {
1638 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1641 if (empty($user->id) or isguestuser($user->id)) {
1642 // No permanent storage for not-logged-in users and guest
1643 if (!isset($user->preference)) {
1644 $user->preference = array();
1651 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1652 // Already loaded at least once on this page. Are we up to date?
1653 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1654 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1657 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1658 // no change since the lastcheck on this page
1659 $user->preference['_lastloaded'] = $timenow;
1664 // OK, so we have to reload all preferences
1665 $loadedusers[$user->id] = true;
1666 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1667 $user->preference['_lastloaded'] = $timenow;
1671 * Called from set/unset_user_preferences, so that the prefs can
1672 * be correctly reloaded in different sessions.
1674 * NOTE: internal function, do not call from other code.
1678 * @param integer $userid the user whose prefs were changed.
1680 function mark_user_preferences_changed($userid) {
1683 if (empty($userid) or isguestuser($userid)) {
1684 // no cache flags for guest and not-logged-in users
1688 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1692 * Sets a preference for the specified user.
1694 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1697 * @category preference
1699 * @param string $name The key to set as preference for the specified user
1700 * @param string $value The value to set for the $name key in the specified user's
1701 * record, null means delete current value.
1702 * @param stdClass|int|null $user A moodle user object or id, null means current user
1703 * @throws coding_exception
1704 * @return bool Always true or exception
1706 function set_user_preference($name, $value, $user = null) {
1709 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1710 throw new coding_exception('Invalid preference name in set_user_preference() call');
1713 if (is_null($value)) {
1714 // null means delete current
1715 return unset_user_preference($name, $user);
1716 } else if (is_object($value)) {
1717 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1718 } else if (is_array($value)) {
1719 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1721 $value = (string)$value;
1722 if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1723 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1726 if (is_null($user)) {
1728 } else if (isset($user->id)) {
1729 // $user is valid object
1730 } else if (is_numeric($user)) {
1731 $user = (object)array('id'=>(int)$user);
1733 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1736 check_user_preferences_loaded($user);
1738 if (empty($user->id) or isguestuser($user->id)) {
1739 // no permanent storage for not-logged-in users and guest
1740 $user->preference[$name] = $value;
1744 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1745 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1746 // preference already set to this value
1749 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1752 $preference = new stdClass();
1753 $preference->userid = $user->id;
1754 $preference->name = $name;
1755 $preference->value = $value;
1756 $DB->insert_record('user_preferences', $preference);
1759 // update value in cache
1760 $user->preference[$name] = $value;
1762 // set reload flag for other sessions
1763 mark_user_preferences_changed($user->id);
1769 * Sets a whole array of preferences for the current user
1771 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1774 * @category preference
1776 * @param array $prefarray An array of key/value pairs to be set
1777 * @param stdClass|int|null $user A moodle user object or id, null means current user
1778 * @return bool Always true or exception
1780 function set_user_preferences(array $prefarray, $user = null) {
1781 foreach ($prefarray as $name => $value) {
1782 set_user_preference($name, $value, $user);
1788 * Unsets a preference completely by deleting it from the database
1790 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1793 * @category preference
1795 * @param string $name The key to unset as preference for the specified user
1796 * @param stdClass|int|null $user A moodle user object or id, null means current user
1797 * @throws coding_exception
1798 * @return bool Always true or exception
1800 function unset_user_preference($name, $user = null) {
1803 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1804 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1807 if (is_null($user)) {
1809 } else if (isset($user->id)) {
1810 // $user is valid object
1811 } else if (is_numeric($user)) {
1812 $user = (object)array('id'=>(int)$user);
1814 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1817 check_user_preferences_loaded($user);
1819 if (empty($user->id) or isguestuser($user->id)) {
1820 // no permanent storage for not-logged-in user and guest
1821 unset($user->preference[$name]);
1826 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1828 // delete the preference from cache
1829 unset($user->preference[$name]);
1831 // set reload flag for other sessions
1832 mark_user_preferences_changed($user->id);
1838 * Used to fetch user preference(s)
1840 * If no arguments are supplied this function will return
1841 * all of the current user preferences as an array.
1843 * If a name is specified then this function
1844 * attempts to return that particular preference value. If
1845 * none is found, then the optional value $default is returned,
1848 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1851 * @category preference
1853 * @param string $name Name of the key to use in finding a preference value
1854 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1855 * @param stdClass|int|null $user A moodle user object or id, null means current user
1856 * @throws coding_exception
1857 * @return string|mixed|null A string containing the value of a single preference. An
1858 * array with all of the preferences or null
1860 function get_user_preferences($name = null, $default = null, $user = null) {
1863 if (is_null($name)) {
1865 } else if (is_numeric($name) or $name === '_lastloaded') {
1866 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1869 if (is_null($user)) {
1871 } else if (isset($user->id)) {
1872 // $user is valid object
1873 } else if (is_numeric($user)) {
1874 $user = (object)array('id'=>(int)$user);
1876 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1879 check_user_preferences_loaded($user);
1882 return $user->preference; // All values
1883 } else if (isset($user->preference[$name])) {
1884 return $user->preference[$name]; // The single string value
1886 return $default; // Default value (null if not specified)
1890 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1893 * Given date parts in user time produce a GMT timestamp.
1897 * @param int $year The year part to create timestamp of
1898 * @param int $month The month part to create timestamp of
1899 * @param int $day The day part to create timestamp of
1900 * @param int $hour The hour part to create timestamp of
1901 * @param int $minute The minute part to create timestamp of
1902 * @param int $second The second part to create timestamp of
1903 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1904 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
1905 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1906 * applied only if timezone is 99 or string.
1907 * @return int GMT timestamp
1909 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1911 //save input timezone, required for dst offset check.
1912 $passedtimezone = $timezone;
1914 $timezone = get_user_timezone_offset($timezone);
1916 if (abs($timezone) > 13) { //server time
1917 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1919 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1920 $time = usertime($time, $timezone);
1922 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1923 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1924 $time -= dst_offset_on($time, $passedtimezone);
1933 * Format a date/time (seconds) as weeks, days, hours etc as needed
1935 * Given an amount of time in seconds, returns string
1936 * formatted nicely as weeks, days, hours etc as needed
1944 * @param int $totalsecs Time in seconds
1945 * @param object $str Should be a time object
1946 * @return string A nicely formatted date/time string
1948 function format_time($totalsecs, $str=NULL) {
1950 $totalsecs = abs($totalsecs);
1952 if (!$str) { // Create the str structure the slow way
1953 $str = new stdClass();
1954 $str->day = get_string('day');
1955 $str->days = get_string('days');
1956 $str->hour = get_string('hour');
1957 $str->hours = get_string('hours');
1958 $str->min = get_string('min');
1959 $str->mins = get_string('mins');
1960 $str->sec = get_string('sec');
1961 $str->secs = get_string('secs');
1962 $str->year = get_string('year');
1963 $str->years = get_string('years');
1967 $years = floor($totalsecs/YEARSECS);
1968 $remainder = $totalsecs - ($years*YEARSECS);
1969 $days = floor($remainder/DAYSECS);
1970 $remainder = $totalsecs - ($days*DAYSECS);
1971 $hours = floor($remainder/HOURSECS);
1972 $remainder = $remainder - ($hours*HOURSECS);
1973 $mins = floor($remainder/MINSECS);
1974 $secs = $remainder - ($mins*MINSECS);
1976 $ss = ($secs == 1) ? $str->sec : $str->secs;
1977 $sm = ($mins == 1) ? $str->min : $str->mins;
1978 $sh = ($hours == 1) ? $str->hour : $str->hours;
1979 $sd = ($days == 1) ? $str->day : $str->days;
1980 $sy = ($years == 1) ? $str->year : $str->years;
1988 if ($years) $oyears = $years .' '. $sy;
1989 if ($days) $odays = $days .' '. $sd;
1990 if ($hours) $ohours = $hours .' '. $sh;
1991 if ($mins) $omins = $mins .' '. $sm;
1992 if ($secs) $osecs = $secs .' '. $ss;
1994 if ($years) return trim($oyears .' '. $odays);
1995 if ($days) return trim($odays .' '. $ohours);
1996 if ($hours) return trim($ohours .' '. $omins);
1997 if ($mins) return trim($omins .' '. $osecs);
1998 if ($secs) return $osecs;
1999 return get_string('now');
2003 * Returns a formatted string that represents a date in user time
2005 * Returns a formatted string that represents a date in user time
2006 * <b>WARNING: note that the format is for strftime(), not date().</b>
2007 * Because of a bug in most Windows time libraries, we can't use
2008 * the nicer %e, so we have to use %d which has leading zeroes.
2009 * A lot of the fuss in the function is just getting rid of these leading
2010 * zeroes as efficiently as possible.
2012 * If parameter fixday = true (default), then take off leading
2013 * zero from %d, else maintain it.
2017 * @param int $date the timestamp in UTC, as obtained from the database.
2018 * @param string $format strftime format. You should probably get this using
2019 * get_string('strftime...', 'langconfig');
2020 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2021 * not 99 then daylight saving will not be added.
2022 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2023 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2024 * If false then the leading zero is maintained.
2025 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2026 * @return string the formatted date/time.
2028 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2032 if (empty($format)) {
2033 $format = get_string('strftimedaydatetime', 'langconfig');
2036 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
2038 } else if ($fixday) {
2039 $formatnoday = str_replace('%d', 'DD', $format);
2040 $fixday = ($formatnoday != $format);
2041 $format = $formatnoday;
2044 // Note: This logic about fixing 12-hour time to remove unnecessary leading
2045 // zero is required because on Windows, PHP strftime function does not
2046 // support the correct 'hour without leading zero' parameter (%l).
2047 if (!empty($CFG->nofixhour)) {
2048 // Config.php can force %I not to be fixed.
2050 } else if ($fixhour) {
2051 $formatnohour = str_replace('%I', 'HH', $format);
2052 $fixhour = ($formatnohour != $format);
2053 $format = $formatnohour;
2056 //add daylight saving offset for string timezones only, as we can't get dst for
2057 //float values. if timezone is 99 (user default timezone), then try update dst.
2058 if ((99 == $timezone) || !is_numeric($timezone)) {
2059 $date += dst_offset_on($date, $timezone);
2062 $timezone = get_user_timezone_offset($timezone);
2064 // If we are running under Windows convert to windows encoding and then back to UTF-8
2065 // (because it's impossible to specify UTF-8 to fetch locale info in Win32)
2067 if (abs($timezone) > 13) { /// Server time
2068 if ($CFG->ostype == 'WINDOWS' and ($localewincharset = get_string('localewincharset', 'langconfig'))) {
2069 $format = textlib::convert($format, 'utf-8', $localewincharset);
2070 $datestring = strftime($format, $date);
2071 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2073 $datestring = strftime($format, $date);
2076 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
2077 $datestring = str_replace('DD', $daystring, $datestring);
2080 $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2081 $datestring = str_replace('HH', $hourstring, $datestring);
2085 $date += (int)($timezone * 3600);
2086 if ($CFG->ostype == 'WINDOWS' and ($localewincharset = get_string('localewincharset', 'langconfig'))) {
2087 $format = textlib::convert($format, 'utf-8', $localewincharset);
2088 $datestring = gmstrftime($format, $date);
2089 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2091 $datestring = gmstrftime($format, $date);
2094 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
2095 $datestring = str_replace('DD', $daystring, $datestring);
2098 $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2099 $datestring = str_replace('HH', $hourstring, $datestring);
2107 * Given a $time timestamp in GMT (seconds since epoch),
2108 * returns an array that represents the date in user time
2113 * @param int $time Timestamp in GMT
2114 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2115 * dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
2116 * @return array An array that represents the date in user time
2118 function usergetdate($time, $timezone=99) {
2120 //save input timezone, required for dst offset check.
2121 $passedtimezone = $timezone;
2123 $timezone = get_user_timezone_offset($timezone);
2125 if (abs($timezone) > 13) { // Server time
2126 return getdate($time);
2129 //add daylight saving offset for string timezones only, as we can't get dst for
2130 //float values. if timezone is 99 (user default timezone), then try update dst.
2131 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2132 $time += dst_offset_on($time, $passedtimezone);
2135 $time += intval((float)$timezone * HOURSECS);
2137 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2139 //be careful to ensure the returned array matches that produced by getdate() above
2142 $getdate['weekday'],
2149 $getdate['minutes'],
2151 ) = explode('_', $datestring);
2153 // set correct datatype to match with getdate()
2154 $getdate['seconds'] = (int)$getdate['seconds'];
2155 $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
2156 $getdate['year'] = (int)$getdate['year'];
2157 $getdate['mon'] = (int)$getdate['mon'];
2158 $getdate['wday'] = (int)$getdate['wday'];
2159 $getdate['mday'] = (int)$getdate['mday'];
2160 $getdate['hours'] = (int)$getdate['hours'];
2161 $getdate['minutes'] = (int)$getdate['minutes'];
2166 * Given a GMT timestamp (seconds since epoch), offsets it by
2167 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2172 * @param int $date Timestamp in GMT
2173 * @param float|int|string $timezone timezone to calculate GMT time offset before
2174 * calculating user time, 99 is default user timezone
2175 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2178 function usertime($date, $timezone=99) {
2180 $timezone = get_user_timezone_offset($timezone);
2182 if (abs($timezone) > 13) {
2185 return $date - (int)($timezone * HOURSECS);
2189 * Given a time, return the GMT timestamp of the most recent midnight
2190 * for the current user.
2194 * @param int $date Timestamp in GMT
2195 * @param float|int|string $timezone timezone to calculate GMT time offset before
2196 * calculating user midnight time, 99 is default user timezone
2197 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2198 * @return int Returns a GMT timestamp
2200 function usergetmidnight($date, $timezone=99) {
2202 $userdate = usergetdate($date, $timezone);
2204 // Time of midnight of this user's day, in GMT
2205 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2210 * Returns a string that prints the user's timezone
2214 * @param float|int|string $timezone timezone to calculate GMT time offset before
2215 * calculating user timezone, 99 is default user timezone
2216 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2219 function usertimezone($timezone=99) {
2221 $tz = get_user_timezone($timezone);
2223 if (!is_float($tz)) {
2227 if(abs($tz) > 13) { // Server time
2228 return get_string('serverlocaltime');
2231 if($tz == intval($tz)) {
2232 // Don't show .0 for whole hours
2249 * Returns a float which represents the user's timezone difference from GMT in hours
2250 * Checks various settings and picks the most dominant of those which have a value
2254 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2255 * 99 is default user timezone
2256 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2259 function get_user_timezone_offset($tz = 99) {
2263 $tz = get_user_timezone($tz);
2265 if (is_float($tz)) {
2268 $tzrecord = get_timezone_record($tz);
2269 if (empty($tzrecord)) {
2272 return (float)$tzrecord->gmtoff / HOURMINS;
2277 * Returns an int which represents the systems's timezone difference from GMT in seconds
2281 * @param float|int|string $tz timezone for which offset is required.
2282 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2283 * @return int|bool if found, false is timezone 99 or error
2285 function get_timezone_offset($tz) {
2292 if (is_numeric($tz)) {
2293 return intval($tz * 60*60);
2296 if (!$tzrecord = get_timezone_record($tz)) {
2299 return intval($tzrecord->gmtoff * 60);
2303 * Returns a float or a string which denotes the user's timezone
2304 * 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)
2305 * means that for this timezone there are also DST rules to be taken into account
2306 * Checks various settings and picks the most dominant of those which have a value
2310 * @param float|int|string $tz timezone to calculate GMT time offset before
2311 * calculating user timezone, 99 is default user timezone
2312 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2313 * @return float|string
2315 function get_user_timezone($tz = 99) {
2320 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2321 isset($USER->timezone) ? $USER->timezone : 99,
2322 isset($CFG->timezone) ? $CFG->timezone : 99,
2327 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
2328 $tz = $next['value'];
2331 return is_numeric($tz) ? (float) $tz : $tz;
2335 * Returns cached timezone record for given $timezonename
2338 * @param string $timezonename name of the timezone
2339 * @return stdClass|bool timezonerecord or false
2341 function get_timezone_record($timezonename) {
2343 static $cache = NULL;
2345 if ($cache === NULL) {
2349 if (isset($cache[$timezonename])) {
2350 return $cache[$timezonename];
2353 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2354 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2358 * Build and store the users Daylight Saving Time (DST) table
2361 * @param int $from_year Start year for the table, defaults to 1971
2362 * @param int $to_year End year for the table, defaults to 2035
2363 * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
2366 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2367 global $CFG, $SESSION, $DB;
2369 $usertz = get_user_timezone($strtimezone);
2371 if (is_float($usertz)) {
2372 // Trivial timezone, no DST
2376 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2377 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2378 unset($SESSION->dst_offsets);
2379 unset($SESSION->dst_range);
2382 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2383 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2384 // This will be the return path most of the time, pretty light computationally
2388 // Reaching here means we either need to extend our table or create it from scratch
2390 // Remember which TZ we calculated these changes for
2391 $SESSION->dst_offsettz = $usertz;
2393 if(empty($SESSION->dst_offsets)) {
2394 // If we 're creating from scratch, put the two guard elements in there
2395 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2397 if(empty($SESSION->dst_range)) {
2398 // If creating from scratch
2399 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2400 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2402 // Fill in the array with the extra years we need to process
2403 $yearstoprocess = array();
2404 for($i = $from; $i <= $to; ++$i) {
2405 $yearstoprocess[] = $i;
2408 // Take note of which years we have processed for future calls
2409 $SESSION->dst_range = array($from, $to);
2412 // If needing to extend the table, do the same
2413 $yearstoprocess = array();
2415 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2416 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2418 if($from < $SESSION->dst_range[0]) {
2419 // Take note of which years we need to process and then note that we have processed them for future calls
2420 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2421 $yearstoprocess[] = $i;
2423 $SESSION->dst_range[0] = $from;
2425 if($to > $SESSION->dst_range[1]) {
2426 // Take note of which years we need to process and then note that we have processed them for future calls
2427 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2428 $yearstoprocess[] = $i;
2430 $SESSION->dst_range[1] = $to;
2434 if(empty($yearstoprocess)) {
2435 // This means that there was a call requesting a SMALLER range than we have already calculated
2439 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2440 // Also, the array is sorted in descending timestamp order!
2444 static $presets_cache = array();
2445 if (!isset($presets_cache[$usertz])) {
2446 $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');
2448 if(empty($presets_cache[$usertz])) {
2452 // Remove ending guard (first element of the array)
2453 reset($SESSION->dst_offsets);
2454 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2456 // Add all required change timestamps
2457 foreach($yearstoprocess as $y) {
2458 // Find the record which is in effect for the year $y
2459 foreach($presets_cache[$usertz] as $year => $preset) {
2465 $changes = dst_changes_for_year($y, $preset);
2467 if($changes === NULL) {
2470 if($changes['dst'] != 0) {
2471 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2473 if($changes['std'] != 0) {
2474 $SESSION->dst_offsets[$changes['std']] = 0;
2478 // Put in a guard element at the top
2479 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2480 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2483 krsort($SESSION->dst_offsets);
2489 * Calculates the required DST change and returns a Timestamp Array
2495 * @param int|string $year Int or String Year to focus on
2496 * @param object $timezone Instatiated Timezone object
2497 * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
2499 function dst_changes_for_year($year, $timezone) {
2501 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2505 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2506 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2508 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2509 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2511 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2512 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2514 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2515 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2516 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2518 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2519 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2521 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2525 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2526 * - Note: Daylight saving only works for string timezones and not for float.
2530 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2531 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2532 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2535 function dst_offset_on($time, $strtimezone = NULL) {
2538 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2542 reset($SESSION->dst_offsets);
2543 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2544 if($from <= $time) {
2549 // This is the normal return path
2550 if($offset !== NULL) {
2554 // Reaching this point means we haven't calculated far enough, do it now:
2555 // Calculate extra DST changes if needed and recurse. The recursion always
2556 // moves toward the stopping condition, so will always end.
2559 // We need a year smaller than $SESSION->dst_range[0]
2560 if($SESSION->dst_range[0] == 1971) {
2563 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2564 return dst_offset_on($time, $strtimezone);
2567 // We need a year larger than $SESSION->dst_range[1]
2568 if($SESSION->dst_range[1] == 2035) {
2571 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2572 return dst_offset_on($time, $strtimezone);
2577 * Calculates when the day appears in specific month
2581 * @param int $startday starting day of the month
2582 * @param int $weekday The day when week starts (normally taken from user preferences)
2583 * @param int $month The month whose day is sought
2584 * @param int $year The year of the month whose day is sought
2587 function find_day_in_month($startday, $weekday, $month, $year) {
2589 $daysinmonth = days_in_month($month, $year);
2591 if($weekday == -1) {
2592 // Don't care about weekday, so return:
2593 // abs($startday) if $startday != -1
2594 // $daysinmonth otherwise
2595 return ($startday == -1) ? $daysinmonth : abs($startday);
2598 // From now on we 're looking for a specific weekday
2600 // Give "end of month" its actual value, since we know it
2601 if($startday == -1) {
2602 $startday = -1 * $daysinmonth;
2605 // Starting from day $startday, the sign is the direction
2609 $startday = abs($startday);
2610 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2612 // This is the last such weekday of the month
2613 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2614 if($lastinmonth > $daysinmonth) {
2618 // Find the first such weekday <= $startday
2619 while($lastinmonth > $startday) {
2623 return $lastinmonth;
2628 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2630 $diff = $weekday - $indexweekday;
2635 // This is the first such weekday of the month equal to or after $startday
2636 $firstfromindex = $startday + $diff;
2638 return $firstfromindex;
2644 * Calculate the number of days in a given month
2648 * @param int $month The month whose day count is sought
2649 * @param int $year The year of the month whose day count is sought
2652 function days_in_month($month, $year) {
2653 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2657 * Calculate the position in the week of a specific calendar day
2661 * @param int $day The day of the date whose position in the week is sought
2662 * @param int $month The month of the date whose position in the week is sought
2663 * @param int $year The year of the date whose position in the week is sought
2666 function dayofweek($day, $month, $year) {
2667 // I wonder if this is any different from
2668 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2669 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2672 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2675 * Returns full login url.
2677 * @return string login url
2679 function get_login_url() {
2682 $url = "$CFG->wwwroot/login/index.php";
2684 if (!empty($CFG->loginhttps)) {
2685 $url = str_replace('http:', 'https:', $url);
2692 * This function checks that the current user is logged in and has the
2693 * required privileges
2695 * This function checks that the current user is logged in, and optionally
2696 * whether they are allowed to be in a particular course and view a particular
2698 * If they are not logged in, then it redirects them to the site login unless
2699 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2700 * case they are automatically logged in as guests.
2701 * If $courseid is given and the user is not enrolled in that course then the
2702 * user is redirected to the course enrolment page.
2703 * If $cm is given and the course module is hidden and the user is not a teacher
2704 * in the course then the user is redirected to the course home page.
2706 * When $cm parameter specified, this function sets page layout to 'module'.
2707 * You need to change it manually later if some other layout needed.
2709 * @package core_access
2712 * @param mixed $courseorid id of the course or course object
2713 * @param bool $autologinguest default true
2714 * @param object $cm course module object
2715 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2716 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2717 * in order to keep redirects working properly. MDL-14495
2718 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2719 * @return mixed Void, exit, and die depending on path
2721 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2722 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2724 // setup global $COURSE, themes, language and locale
2725 if (!empty($courseorid)) {
2726 if (is_object($courseorid)) {
2727 $course = $courseorid;
2728 } else if ($courseorid == SITEID) {
2729 $course = clone($SITE);
2731 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2734 if ($cm->course != $course->id) {
2735 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2737 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2738 if (!($cm instanceof cm_info)) {
2739 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2740 // db queries so this is not really a performance concern, however it is obviously
2741 // better if you use get_fast_modinfo to get the cm before calling this.
2742 $modinfo = get_fast_modinfo($course);
2743 $cm = $modinfo->get_cm($cm->id);
2745 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2746 $PAGE->set_pagelayout('incourse');
2748 $PAGE->set_course($course); // set's up global $COURSE
2751 // do not touch global $COURSE via $PAGE->set_course(),
2752 // the reasons is we need to be able to call require_login() at any time!!
2755 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2759 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2760 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2761 // risk leading the user back to the AJAX request URL.
2762 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2763 $setwantsurltome = false;
2766 // If the user is not even logged in yet then make sure they are
2767 if (!isloggedin()) {
2768 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2769 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2770 // misconfigured site guest, just redirect to login page
2771 redirect(get_login_url());
2772 exit; // never reached
2774 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2775 complete_user_login($guest);
2776 $USER->autologinguest = true;
2777 $SESSION->lang = $lang;
2779 //NOTE: $USER->site check was obsoleted by session test cookie,
2780 // $USER->confirmed test is in login/index.php
2781 if ($preventredirect) {
2782 throw new require_login_exception('You are not logged in');
2785 if ($setwantsurltome) {
2786 $SESSION->wantsurl = qualified_me();
2788 if (!empty($_SERVER['HTTP_REFERER'])) {
2789 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2791 redirect(get_login_url());
2792 exit; // never reached
2796 // loginas as redirection if needed
2797 if ($course->id != SITEID and session_is_loggedinas()) {
2798 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2799 if ($USER->loginascontext->instanceid != $course->id) {
2800 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2805 // check whether the user should be changing password (but only if it is REALLY them)
2806 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2807 $userauth = get_auth_plugin($USER->auth);
2808 if ($userauth->can_change_password() and !$preventredirect) {
2809 if ($setwantsurltome) {
2810 $SESSION->wantsurl = qualified_me();
2812 if ($changeurl = $userauth->change_password_url()) {
2813 //use plugin custom url
2814 redirect($changeurl);
2816 //use moodle internal method
2817 if (empty($CFG->loginhttps)) {
2818 redirect($CFG->wwwroot .'/login/change_password.php');
2820 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2821 redirect($wwwroot .'/login/change_password.php');
2825 print_error('nopasswordchangeforced', 'auth');
2829 // Check that the user account is properly set up
2830 if (user_not_fully_set_up($USER)) {
2831 if ($preventredirect) {
2832 throw new require_login_exception('User not fully set-up');
2834 if ($setwantsurltome) {
2835 $SESSION->wantsurl = qualified_me();
2837 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2840 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2843 // Do not bother admins with any formalities
2844 if (is_siteadmin()) {
2845 //set accesstime or the user will appear offline which messes up messaging
2846 user_accesstime_log($course->id);
2850 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2851 if (!$USER->policyagreed and !is_siteadmin()) {
2852 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2853 if ($preventredirect) {
2854 throw new require_login_exception('Policy not agreed');
2856 if ($setwantsurltome) {
2857 $SESSION->wantsurl = qualified_me();
2859 redirect($CFG->wwwroot .'/user/policy.php');
2860 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2861 if ($preventredirect) {
2862 throw new require_login_exception('Policy not agreed');
2864 if ($setwantsurltome) {
2865 $SESSION->wantsurl = qualified_me();
2867 redirect($CFG->wwwroot .'/user/policy.php');
2871 // Fetch the system context, the course context, and prefetch its child contexts
2872 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2873 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2875 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2880 // If the site is currently under maintenance, then print a message
2881 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2882 if ($preventredirect) {
2883 throw new require_login_exception('Maintenance in progress');
2886 print_maintenance_message();
2889 // make sure the course itself is not hidden
2890 if ($course->id == SITEID) {
2891 // frontpage can not be hidden
2893 if (is_role_switched($course->id)) {
2894 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2896 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2897 // originally there was also test of parent category visibility,
2898 // BUT is was very slow in complex queries involving "my courses"
2899 // now it is also possible to simply hide all courses user is not enrolled in :-)
2900 if ($preventredirect) {
2901 throw new require_login_exception('Course is hidden');
2903 // We need to override the navigation URL as the course won't have
2904 // been added to the navigation and thus the navigation will mess up
2905 // when trying to find it.
2906 navigation_node::override_active_url(new moodle_url('/'));
2907 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2912 // is the user enrolled?
2913 if ($course->id == SITEID) {
2914 // everybody is enrolled on the frontpage
2917 if (session_is_loggedinas()) {
2918 // Make sure the REAL person can access this course first
2919 $realuser = session_get_realuser();
2920 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2921 if ($preventredirect) {
2922 throw new require_login_exception('Invalid course login-as access');
2924 echo $OUTPUT->header();
2925 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2931 if (is_role_switched($course->id)) {
2932 // ok, user had to be inside this course before the switch
2935 } else if (is_viewing($coursecontext, $USER)) {
2936 // ok, no need to mess with enrol
2940 if (isset($USER->enrol['enrolled'][$course->id])) {
2941 if ($USER->enrol['enrolled'][$course->id] > time()) {
2943 if (isset($USER->enrol['tempguest'][$course->id])) {
2944 unset($USER->enrol['tempguest'][$course->id]);
2945 remove_temp_course_roles($coursecontext);
2949 unset($USER->enrol['enrolled'][$course->id]);
2952 if (isset($USER->enrol['tempguest'][$course->id])) {
2953 if ($USER->enrol['tempguest'][$course->id] == 0) {
2955 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2959 unset($USER->enrol['tempguest'][$course->id]);
2960 remove_temp_course_roles($coursecontext);
2967 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2968 if ($until !== false) {
2969 // active participants may always access, a timestamp in the future, 0 (always) or false.
2971 $until = ENROL_MAX_TIMESTAMP;
2973 $USER->enrol['enrolled'][$course->id] = $until;
2977 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2978 $enrols = enrol_get_plugins(true);
2979 // first ask all enabled enrol instances in course if they want to auto enrol user
2980 foreach($instances as $instance) {
2981 if (!isset($enrols[$instance->enrol])) {
2984 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2985 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2986 if ($until !== false) {
2988 $until = ENROL_MAX_TIMESTAMP;
2990 $USER->enrol['enrolled'][$course->id] = $until;
2995 // if not enrolled yet try to gain temporary guest access
2997 foreach($instances as $instance) {
2998 if (!isset($enrols[$instance->enrol])) {
3001 // Get a duration for the guest access, a timestamp in the future or false.
3002 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3003 if ($until !== false and $until > time()) {
3004 $USER->enrol['tempguest'][$course->id] = $until;
3015 if ($preventredirect) {
3016 throw new require_login_exception('Not enrolled');
3018 if ($setwantsurltome) {
3019 $SESSION->wantsurl = qualified_me();
3021 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3025 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
3026 // conditional availability, etc
3027 if ($cm && !$cm->uservisible) {
3028 if ($preventredirect) {
3029 throw new require_login_exception('Activity is hidden');
3031 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
3034 // Finally access granted, update lastaccess times
3035 user_accesstime_log($course->id);
3040 * This function just makes sure a user is logged out.
3042 * @package core_access
3044 function require_logout() {
3050 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
3052 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
3053 foreach($authsequence as $authname) {
3054 $authplugin = get_auth_plugin($authname);
3055 $authplugin->prelogout_hook();
3059 events_trigger('user_logout', $params);
3060 session_get_instance()->terminate_current();
3065 * Weaker version of require_login()
3067 * This is a weaker version of {@link require_login()} which only requires login
3068 * when called from within a course rather than the site page, unless
3069 * the forcelogin option is turned on.
3070 * @see require_login()
3072 * @package core_access
3075 * @param mixed $courseorid The course object or id in question
3076 * @param bool $autologinguest Allow autologin guests if that is wanted
3077 * @param object $cm Course activity module if known
3078 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3079 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3080 * in order to keep redirects working properly. MDL-14495
3081 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3084 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
3085 global $CFG, $PAGE, $SITE;
3086 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3087 or (!is_object($courseorid) and $courseorid == SITEID);
3088 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3089 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
3090 // db queries so this is not really a performance concern, however it is obviously
3091 // better if you use get_fast_modinfo to get the cm before calling this.
3092 if (is_object($courseorid)) {
3093 $course = $courseorid;
3095 $course = clone($SITE);
3097 $modinfo = get_fast_modinfo($course);
3098 $cm = $modinfo->get_cm($cm->id);
3100 if (!empty($CFG->forcelogin)) {
3101 // login required for both SITE and courses
3102 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3104 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3105 // always login for hidden activities
3106 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3108 } else if ($issite) {
3109 //login for SITE not required
3110 if ($cm and empty($cm->visible)) {
3111 // hidden activities are not accessible without login
3112 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3113 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3114 // not-logged-in users do not have any group membership
3115 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3117 // We still need to instatiate PAGE vars properly so that things
3118 // that rely on it like navigation function correctly.
3119 if (!empty($courseorid)) {
3120 if (is_object($courseorid)) {
3121 $course = $courseorid;
3123 $course = clone($SITE);
3126 if ($cm->course != $course->id) {
3127 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3129 $PAGE->set_cm($cm, $course);
3130 $PAGE->set_pagelayout('incourse');
3132 $PAGE->set_course($course);
3135 // If $PAGE->course, and hence $PAGE->context, have not already been set
3136 // up properly, set them up now.
3137 $PAGE->set_course($PAGE->course);
3139 //TODO: verify conditional activities here
3140 user_accesstime_log(SITEID);
3145 // course login always required
3146 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3151 * Require key login. Function terminates with error if key not found or incorrect.
3157 * @uses NO_MOODLE_COOKIES
3158 * @uses PARAM_ALPHANUM
3159 * @param string $script unique script identifier
3160 * @param int $instance optional instance id
3161 * @return int Instance ID
3163 function require_user_key_login($script, $instance=null) {
3164 global $USER, $SESSION, $CFG, $DB;
3166 if (!NO_MOODLE_COOKIES) {
3167 print_error('sessioncookiesdisable');
3171 @session_write_close();
3173 $keyvalue = required_param('key', PARAM_ALPHANUM);
3175 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3176 print_error('invalidkey');
3179 if (!empty($key->validuntil) and $key->validuntil < time()) {
3180 print_error('expiredkey');
3183 if ($key->iprestriction) {
3184 $remoteaddr = getremoteaddr(null);
3185 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3186 print_error('ipmismatch');
3190 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
3191 print_error('invaliduserid');
3194 /// emulate normal session
3195 enrol_check_plugins($user);
3196 session_set_user($user);
3198 /// note we are not using normal login
3199 if (!defined('USER_KEY_LOGIN')) {
3200 define('USER_KEY_LOGIN', true);
3203 /// return instance id - it might be empty
3204 return $key->instance;
3208 * Creates a new private user access key.
3211 * @param string $script unique target identifier
3212 * @param int $userid
3213 * @param int $instance optional instance id
3214 * @param string $iprestriction optional ip restricted access
3215 * @param timestamp $validuntil key valid only until given data
3216 * @return string access key value
3218 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3221 $key = new stdClass();
3222 $key->script = $script;
3223 $key->userid = $userid;
3224 $key->instance = $instance;
3225 $key->iprestriction = $iprestriction;
3226 $key->validuntil = $validuntil;
3227 $key->timecreated = time();
3229 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
3230 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3232 $key->value = md5($userid.'_'.time().random_string(40));
3234 $DB->insert_record('user_private_key', $key);
3239 * Delete the user's new private user access keys for a particular script.
3242 * @param string $script unique target identifier
3243 * @param int $userid
3246 function delete_user_key($script,$userid) {
3248 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3252 * Gets a private user access key (and creates one if one doesn't exist).
3255 * @param string $script unique target identifier
3256 * @param int $userid
3257 * @param int $instance optional instance id
3258 * @param string $iprestriction optional ip restricted access
3259 * @param timestamp $validuntil key valid only until given data
3260 * @return string access key value
3262 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3265 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3266 'instance'=>$instance, 'iprestriction'=>$iprestriction,
3267 'validuntil'=>$validuntil))) {
3270 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3276 * Modify the user table by setting the currently logged in user's
3277 * last login to now.
3281 * @return bool Always returns true
3283 function update_user_login_times() {
3286 $user = new stdClass();
3287 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3288 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
3290 $user->id = $USER->id;
3292 $DB->update_record('user', $user);
3297 * Determines if a user has completed setting up their account.
3299 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3302 function user_not_fully_set_up($user) {
3303 if (isguestuser($user)) {
3306 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3310 * Check whether the user has exceeded the bounce threshold
3314 * @param user $user A {@link $USER} object
3315 * @return bool true=>User has exceeded bounce threshold
3317 function over_bounce_threshold($user) {
3320 if (empty($CFG->handlebounces)) {
3324 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3328 // set sensible defaults
3329 if (empty($CFG->minbounces)) {
3330 $CFG->minbounces = 10;
3332 if (empty($CFG->bounceratio)) {
3333 $CFG->bounceratio = .20;
3337 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3338 $bouncecount = $bounce->value;
3340 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3341 $sendcount = $send->value;
3343 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3347 * Used to increment or reset email sent count
3350 * @param user $user object containing an id
3351 * @param bool $reset will reset the count to 0
3354 function set_send_count($user,$reset=false) {
3357 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3361 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3362 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3363 $DB->update_record('user_preferences', $pref);
3365 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3367 $pref = new stdClass();
3368 $pref->name = 'email_send_count';
3370 $pref->userid = $user->id;
3371 $DB->insert_record('user_preferences', $pref, false);
3376 * Increment or reset user's email bounce count
3379 * @param user $user object containing an id
3380 * @param bool $reset will reset the count to 0
3382 function set_bounce_count($user,$reset=false) {
3385 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3386 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3387 $DB->update_record('user_preferences', $pref);
3389 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3391 $pref = new stdClass();
3392 $pref->name = 'email_bounce_count';
3394 $pref->userid = $user->id;
3395 $DB->insert_record('user_preferences', $pref, false);
3400 * Keeps track of login attempts
3404 function update_login_count() {
3409 if (empty($SESSION->logincount)) {
3410 $SESSION->logincount = 1;
3412 $SESSION->logincount++;
3415 if ($SESSION->logincount > $max_logins) {
3416 unset($SESSION->wantsurl);
3417 print_error('errortoomanylogins');
3422 * Resets login attempts
3426 function reset_login_count() {
3429 $SESSION->logincount = 0;
3433 * Determines if the currently logged in user is in editing mode.
3434 * Note: originally this function had $userid parameter - it was not usable anyway
3436 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3437 * @todo Deprecated function remove when ready
3440 * @uses DEBUG_DEVELOPER
3443 function isediting() {
3445 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3446 return $PAGE->user_is_editing();
3450 * Determines if the logged in user is currently moving an activity
3453 * @param int $courseid The id of the course being tested
3456 function ismoving($courseid) {
3459 if (!empty($USER->activitycopy)) {
3460 return ($USER->activitycopycourse == $courseid);
3466 * Returns a persons full name
3468 * Given an object containing firstname and lastname
3469 * values, this function returns a string with the
3470 * full name of the person.
3471 * The result may depend on system settings
3472 * or language. 'override' will force both names
3473 * to be used even if system settings specify one.
3477 * @param object $user A {@link $USER} object to get full name of
3478 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3481 function fullname($user, $override=false) {
3482 global $CFG, $SESSION;
3484 if (!isset($user->firstname) and !isset($user->lastname)) {
3489 if (!empty($CFG->forcefirstname)) {
3490 $user->firstname = $CFG->forcefirstname;
3492 if (!empty($CFG->forcelastname)) {
3493 $user->lastname = $CFG->forcelastname;
3497 if (!empty($SESSION->fullnamedisplay)) {
3498 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3501 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3502 return $user->firstname .' '. $user->lastname;
3504 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3505 return $user->lastname .' '. $user->firstname;
3507 } else if ($CFG->fullnamedisplay == 'firstname') {
3509 return get_string('fullnamedisplay', '', $user);
3511 return $user->firstname;
3515 return get_string('fullnamedisplay', '', $user);
3519 * Checks if current user is shown any extra fields when listing users.
3520 * @param object $context Context
3521 * @param array $already Array of fields that we're going to show anyway
3522 * so don't bother listing them
3523 * @return array Array of field names from user table, not including anything
3524 * listed in $already
3526 function get_extra_user_fields($context, $already = array()) {
3529 // Only users with permission get the extra fields
3530 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3534 // Split showuseridentity on comma
3535 if (empty($CFG->showuseridentity)) {
3536 // Explode gives wrong result with empty string
3539 $extra = explode(',', $CFG->showuseridentity);
3542 foreach ($extra as $key => $field) {
3543 if (in_array($field, $already)) {
3544 unset($extra[$key]);
3549 // For consistency, if entries are removed from array, renumber it
3550 // so they are numbered as you would expect
3551 $extra = array_merge($extra);
3557 * If the current user is to be shown extra user fields when listing or
3558 * selecting users, returns a string suitable for including in an SQL select
3559 * clause to retrieve those fields.
3560 * @param object $context Context
3561 * @param string $alias Alias of user table, e.g. 'u' (default none)
3562 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3563 * @param array $already Array of fields that we're going to include anyway
3564 * so don't list them (default none)
3565 * @return string Partial SQL select clause, beginning with comma, for example
3566 * ',u.idnumber,u.department' unless it is blank
3568 function get_extra_user_fields_sql($context, $alias='', $prefix='',
3569 $already = array()) {
3570 $fields = get_extra_user_fields($context, $already);
3572 // Add punctuation for alias
3573 if ($alias !== '') {
3576 foreach ($fields as $field) {
3577 $result .= ', ' . $alias . $field;
3579 $result .= ' AS ' . $prefix . $field;
3586 * Returns the display name of a field in the user table. Works for most fields
3587 * that are commonly displayed to users.
3588 * @param string $field Field name, e.g. 'phone1'
3589 * @return string Text description taken from language file, e.g. 'Phone number'
3591 function get_user_field_name($field) {
3592 // Some fields have language strings which are not the same as field name
3594 case 'phone1' : return get_string('phone');
3596 // Otherwise just use the same lang string
3597 return get_string($field);
3601 * Returns whether a given authentication plugin exists.
3604 * @param string $auth Form of authentication to check for. Defaults to the
3605 * global setting in {@link $CFG}.
3606 * @return boolean Whether the plugin is available.
3608 function exists_auth_plugin($auth) {
3611 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3612 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3618 * Checks if a given plugin is in the list of enabled authentication plugins.
3620 * @param string $auth Authentication plugin.
3621 * @return boolean Whether the plugin is enabled.
3623 function is_enabled_auth($auth) {
3628 $enabled = get_enabled_auth_plugins();
3630 return in_array($auth, $enabled);
3634 * Returns an authentication plugin instance.
3637 * @param string $auth name of authentication plugin
3638 * @return auth_plugin_base An instance of the required authentication plugin.
3640 function get_auth_plugin($auth) {
3643 // check the plugin exists first
3644 if (! exists_auth_plugin($auth)) {
3645 print_error('authpluginnotfound', 'debug', '', $auth);
3648 // return auth plugin instance
3649 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3650 $class = "auth_plugin_$auth";
3655 * Returns array of active auth plugins.
3657 * @param bool $fix fix $CFG->auth if needed
3660 function get_enabled_auth_plugins($fix=false) {
3663 $default = array('manual', 'nologin');
3665 if (empty($CFG->auth)) {
3668 $auths = explode(',', $CFG->auth);
3672 $auths = array_unique($auths);
3673 foreach($auths as $k=>$authname) {
3674 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3678 $newconfig = implode(',', $auths);
3679 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3680 set_config('auth', $newconfig);
3684 return (array_merge($default, $auths));
3688 * Returns true if an internal authentication method is being used.
3689 * if method not specified then, global default is assumed
3691 * @param string $auth Form of authentication required
3694 function is_internal_auth($auth) {
3695 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3696 return $authplugin->is_internal();
3700 * Returns true if the user is a 'restored' one
3702 * Used in the login process to inform the user
3703 * and allow him/her to reset the password
3707 * @param string $username username to be checked
3710 function is_restored_user($username) {
3713 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3717 * Returns an array of user fields
3719 * @return array User field/column names
3721 function get_user_fieldnames() {
3724 $fieldarray = $DB->get_columns('user');
3725 unset($fieldarray['id']);
3726 $fieldarray = array_keys($fieldarray);
3732 * Creates a bare-bones user record
3734 * @todo Outline auth types and provide code example
3736 * @param string $username New user's username to add to record
3737 * @param string $password New user's password to add to record
3738 * @param string $auth Form of authentication required
3739 * @return stdClass A complete user object
3741 function create_user_record($username, $password, $auth = 'manual') {
3744 //just in case check text case
3745 $username = trim(textlib::strtolower($username));
3747 $authplugin = get_auth_plugin($auth);
3749 $newuser = new stdClass();
3751 if ($newinfo = $authplugin->get_userinfo($username)) {
3752 $newinfo = truncate_userinfo($newinfo);
3753 foreach ($newinfo as $key => $value){
3754 $newuser->$key = $value;
3758 if (!empty($newuser->email)) {
3759 if (email_is_not_allowed($newuser->email)) {
3760 unset($newuser->email);
3764 if (!isset($newuser->city)) {
3765 $newuser->city = '';
3768 $newuser->auth = $auth;
3769 $newuser->username = $username;
3772 // user CFG lang for user if $newuser->lang is empty
3773 // or $user->lang is not an installed language
3774 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3775 $newuser->lang = $CFG->lang;
3777 $newuser->confirmed = 1;
3778 $newuser->lastip = getremoteaddr();
3779 $newuser->timecreated = time();
3780 $newuser->timemodified = $newuser->timecreated;
3781 $newuser->mnethostid = $CFG->mnet_localhost_id;
3783 $newuser->id = $DB->insert_record('user', $newuser);
3784 $user = get_complete_user_data('id', $newuser->id);
3785 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3786 set_user_preference('auth_forcepasswordchange', 1, $user);
3788 update_internal_user_password($user, $password);
3790 // fetch full user record for the event, the complete user data contains too much info
3791 // and we want to be consistent with other places that trigger this event
3792 events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
3798 * Will update a local user record from an external source.
3799 * (MNET users can not be updated using this method!)
3801 * @param string $username user's username to update the record
3802 * @return stdClass A complete user object
3804 function update_user_record($username) {
3807 $username = trim(textlib::strtolower($username)); /// just in case check text case
3809 $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
3811 $userauth = get_auth_plugin($oldinfo->auth);
3813 if ($newinfo = $userauth->get_userinfo($username)) {
3814 $newinfo = truncate_userinfo($newinfo);
3815 foreach ($newinfo as $key => $value){
3816 $key = strtolower($key);
3817 if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id'
3818 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3819 // unknown or must not be changed
3822 $confval = $userauth->config->{'field_updatelocal_' . $key};
3823 $lockval = $userauth->config->{'field_lock_' . $key};
3824 if (empty($confval) || empty($lockval)) {
3827 if ($confval === 'onlogin') {
3828 // MDL-4207 Don't overwrite modified user profile values with
3829 // empty LDAP values when 'unlocked if empty' is set. The purpose
3830 // of the setting 'unlocked if empty' is to allow the user to fill
3831 // in a value for the selected field _if LDAP is giving
3832 // nothing_ for this field. Thus it makes sense to let this value
3833 // stand in until LDAP is giving a value for this field.
3834 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3835 if ((string)$oldinfo->$key !== (string)$value) {
3836 $newuser[$key] = (string)$value;
3842 $newuser['id'] = $oldinfo->id;
3843 $newuser['timemodified'] = time();
3844 $DB->update_record('user', $newuser);
3845 // fetch full user record for the event, the complete user data contains too much info
3846 // and we want to be consistent with other places that trigger this event
3847 events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id)));
3851 return get_complete_user_data('id', $oldinfo->id);
3855 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3856 * which may have large fields
3858 * @todo Add vartype handling to ensure $info is an array
3860 * @param array $info Array of user properties to truncate if needed
3861 * @return array The now truncated information that was passed in
3863 function truncate_userinfo($info) {
3864 // define the limits
3874 'institution' => 40,
3882 // apply where needed
3883 foreach (array_keys($info) as $key) {
3884 if (!empty($limit[$key])) {
3885 $info[$key] = trim(textlib::substr($info[$key],0, $limit[$key]));
3893 * Marks user deleted in internal user database and notifies the auth plugin.
3894 * Also unenrols user from all roles and does other cleanup.
3896 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3898 * @param stdClass $user full user object before delete
3899 * @return boolean always true
3901 function delete_user($user) {
3903 require_once($CFG->libdir.'/grouplib.php');
3904 require_once($CFG->libdir.'/gradelib.php');
3905 require_once($CFG->dirroot.'/message/lib.php');
3906 require_once($CFG->dirroot.'/tag/lib.php');
3908 // delete all grades - backup is kept in grade_grades_history table
3909 grade_user_delete($user->id);
3911 //move unread messages from this user to read
3912 message_move_userfrom_unread2read($user->id);
3914 // TODO: remove from cohorts using standard API here
3917 tag_set('user', $user->id, array());
3919 // unconditionally unenrol from all courses
3920 enrol_user_delete($user);
3922 // unenrol from all roles in all contexts
3923 role_unassign_all(array('userid'=>$user->id)); // this might be slow but it is really needed - modules might do some extra cleanup!
3925 //now do a brute force cleanup
3927 // remove from all cohorts
3928 $DB->delete_records('cohort_members', array('userid'=>$user->id));
3930 // remove from all groups
3931 $DB->delete_records('groups_members', array('userid'=>$user->id));
3933 // brute force unenrol from all courses
3934 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
3936 // purge user preferences
3937 $DB->delete_records('user_preferences', array('userid'=>$user->id));
3939 // purge user extra profile info
3940 $DB->delete_records('user_info_data', array('userid'=>$user->id));
3942 // last course access not necessary either
3943 $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
3945 // remove all user tokens
3946 $DB->delete_records('external_tokens', array('userid'=>$user->id));
3948 // unauthorise the user for all services
3949 $DB->delete_records('external_services_users', array('userid'=>$user->id));
3951 // force logout - may fail if file based sessions used, sorry
3952 session_kill_user($user->id);
3954 // now do a final accesslib cleanup - removes all role assignments in user context and context itself
3955 delete_context(CONTEXT_USER, $user->id);
3957 // workaround for bulk deletes of users with the same email address
3958 $delname = "$user->email.".time();
3959 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3963 // mark internal user record as "deleted"
3964 $updateuser = new stdClass();
3965 $updateuser->id = $user->id;
3966 $updateuser->deleted = 1;
3967 $updateuser->username = $delname; // Remember it just in case
3968 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
3969 $updateuser->idnumber = ''; // Clear this field to free it up
3970 $updateuser->picture = 0;
3971 $updateuser->timemodified = time();
3973 $DB->update_record('user', $updateuser);
3974 // Add this action to log
3975 add_to_log(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
3978 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
3979 // should know about this updated property persisted to the user's table.
3980 $user->timemodified = $updateuser->timemodified;
3982 // notify auth plugin - do not block the delete even when plugin fails
3983 $authplugin = get_auth_plugin($user->auth);
3984 $authplugin->user_delete($user);
3986 // any plugin that needs to cleanup should register this event
3987 events_trigger('user_deleted', $user);
3993 * Retrieve the guest user object
3997 * @return user A {@link $USER} object
3999 function guest_user() {
4002 if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
4003 $newuser->confirmed = 1;
4004 $newuser->lang = $CFG->lang;
4005 $newuser->lastip = getremoteaddr();
4012 * Authenticates a user against the chosen authentication mechanism
4014 * Given a username and password, this function looks them
4015 * up using the currently selected authentication mechanism,
4016 * and if the authentication is successful, it returns a
4017 * valid $user object from the 'user' table.
4019 * Uses auth_ functions from the currently active auth module
4021 * After authenticate_user_login() returns success, you will need to
4022 * log that the user has logged in, and call complete_user_login() to set
4025 * Note: this function works only with non-mnet accounts!
4027 * @param string $username User's username
4028 * @param string $password User's password
4029 * @return user|flase A {@link $USER} object or false if error
4031 function authenticate_user_login($username, $password) {
4034 $authsenabled = get_enabled_auth_plugins();
4036 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4037 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
4038 if (!empty($user->suspended)) {
4039 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4040 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4043 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4044 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4045 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4048 $auths = array($auth);
4051 // check if there's a deleted record (cheaply)
4052 if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
4053 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4057 // User does not exist
4058 $auths = $authsenabled;
4059 $user = new stdClass();
4063 foreach ($auths as $auth) {
4064 $authplugin = get_auth_plugin($auth);
4066 // on auth fail fall through to the next plugin
4067 if (!$authplugin->user_login($username, $password)) {
4071 // successful authentication
4072 if ($user->id) { // User already exists in database
4073 if (empty($user->auth)) { // For some reason auth isn't set yet
4074 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
4075 $user->auth = $auth;
4077 if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
4078 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
4079 $user->firstaccess = $user->timemodified;
4082 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
4084 if ($authplugin->is_synchronised_with_external()) { // update user record from external DB
4085 $user = update_user_record($username);
4088 // if user not found and user creation is not disabled, create it
4089 if (empty($CFG->authpreventaccountcreation)) {
4090 $user = create_user_record($username, $password, $auth);
4096 $authplugin->sync_roles($user);
4098 foreach ($authsenabled as $hau) {
4099 $hauth = get_auth_plugin($hau);
4100 $hauth->user_authenticated_hook($user, $username, $password);
4103 if (empty($user->id)) {
4107 if (!empty($user->suspended)) {
4108 // just in case some auth plugin suspended account
4109 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4110 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4117 // failed if all the plugins have failed
4118 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4119 if (debugging('', DEBUG_ALL)) {
4120 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4126 * Call to complete the user login process after authenticate_user_login()
4127 * has succeeded. It will setup the $USER variable and other required bits
4131 * - It will NOT log anything -- up to the caller to decide what to log.
4132 * - this function does not set any cookies any more!
4134 * @param object $user
4135 * @return object A {@link $USER} object - BC only, do not use
4137 function complete_user_login($user) {
4140 // regenerate session id and delete old session,
4141 // this helps prevent session fixation attacks from the same domain
4142 session_regenerate_id(true);
4144 // let enrol plugins deal with new enrolments if necessary
4145 enrol_check_plugins($user);
4147 // check enrolments, load caps and setup $USER object
4148 session_set_user($user);
4150 // reload preferences from DB
4151 unset($USER->preference);
4152 check_user_preferences_loaded($USER);
4154 // update login times
4155 update_user_login_times();
4157 // extra session prefs init
4158 set_login_session_preferences();
4160 if (isguestuser()) {
4161 // no need to continue when user is THE guest
4165 /// Select password change url
4166 $userauth = get_auth_plugin($USER->auth);
4168 /// check whether the user should be changing password
4169 if (get_user_preferences('auth_forcepasswordchange', false)){
4170 if ($userauth->can_change_password()) {
4171 if ($changeurl = $userauth->change_password_url()) {
4172 redirect($changeurl);
4174 redirect($CFG->httpswwwroot.'/login/change_password.php');
4177 print_error('nopasswordchangeforced', 'auth');
4184 * Compare password against hash stored in internal user table.
4185 * If necessary it also updates the stored hash to new format.
4187 * @param stdClass $user (password property may be updated)
4188 * @param string $password plain text password
4189 * @return bool is password valid?
4191 function validate_internal_user_password($user, $password) {
4194 if (!isset($CFG->passwordsaltmain)) {
4195 $CFG->passwordsaltmain = '';
4200 if ($user->password === 'not cached') {
4201 // internal password is not used at all, it can not validate
4203 } else if ($user->password === md5($password.$CFG->passwordsaltmain)
4204 or $user->password === md5($password)
4205 or $user->password === md5(addslashes($password).$CFG->passwordsaltmain)
4206 or $user->password === md5(addslashes($password))) {
4207 // note: we are intentionally using the addslashes() here because we
4208 // need to accept old password hashes of passwords with magic quotes
4212 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
4213 $alt = 'passwordsaltalt'.$i;
4214 if (!empty($CFG->$alt)) {
4215 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4224 // force update of password hash using latest main password salt and encoding if needed
4225 update_internal_user_password($user, $password);
4232 * Calculate hashed value from password using current hash mechanism.
4234 * @param string $password
4235 * @return string password hash
4237 function hash_internal_user_password($password) {
4240 if (isset($CFG->passwordsaltmain)) {
4241 return md5($password.$CFG->passwordsaltmain);
4243 return md5($password);
4248 * Update password hash in user object.
4250 * @param stdClass $user (password property may be updated)
4251 * @param string $password plain text password
4252 * @return bool always returns true
4254 function update_internal_user_password($user, $password) {
4257 $authplugin = get_auth_plugin($user->auth);
4258 if ($authplugin->prevent_local_passwords()) {
4259 $hashedpassword = 'not cached';
4261 $hashedpassword = hash_internal_user_password($password);
4264 if ($user->password !== $hashedpassword) {
4265 $DB->set_field('user', 'password', $hashedpassword, array('id'=>$user->id));
4266 $user->password = $hashedpassword;
4273 * Get a complete user record, which includes all the info
4274 * in the user record.
4276 * Intended for setting as $USER session variable
4278 * @param string $field The user field to be checked for a given value.
4279 * @param string $value The value to match for $field.
4280 * @param int $mnethostid
4281 * @return mixed False, or A {@link $USER} object.
4283 function get_complete_user_data($field, $value, $mnethostid = null) {
4286 if (!$field || !$value) {
4290 /// Build the WHERE clause for an SQL query
4291 $params = array('fieldval'=>$value);
4292 $constraints = "$field = :fieldval AND deleted <> 1";
4294 // If we are loading user data based on anything other than id,
4295 // we must also restrict our search based on mnet host.
4296 if ($field != 'id') {
4297 if (empty($mnethostid)) {
4298 // if empty, we restrict to local users
4299 $mnethostid = $CFG->mnet_localhost_id;
4302 if (!empty($mnethostid)) {
4303 $params['mnethostid'] = $mnethostid;
4304 $constraints .= " AND mnethostid = :mnethostid";
4307 /// Get all the basic user data
4309 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4313 /// Get various settings and preferences
4315 // preload preference cache
4316 check_user_preferences_loaded($user);
4318 // load course enrolment related stuff
4319 $user->lastcourseaccess = array(); // during last session
4320 $user->currentcourseaccess = array(); // during current session
4321 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid'=>$user->id))) {
4322 foreach ($lastaccesses as $lastaccess) {
4323 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4327 $sql = "SELECT g.id, g.courseid
4328 FROM {groups} g, {groups_members} gm
4329 WHERE gm.groupid=g.id AND gm.userid=?";
4331 // this is a special hack to speedup calendar display
4332 $user->groupmember = array();
4333 if (!isguestuser($user)) {
4334 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4335 foreach ($groups as $group) {
4336 if (!array_key_exists($group->courseid, $user->groupmember)) {
4337 $user->groupmember[$group->courseid] = array();
4339 $user->groupmember[$group->courseid][$group->id] = $group->id;
4344 /// Add the custom profile fields to the user record
4345 $user->profile = array();
4346 if (!isguestuser($user)) {
4347 require_once($CFG->dirroot.'/user/profile/lib.php');
4348 profile_load_custom_fields($user);
4351 /// Rewrite some variables if necessary
4352 if (!empty($user->description)) {