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. Note that you almost never want
120 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
121 * the input (required/optional_param or formslib) and then sanitse the HTML
122 * using format_text on output. This is for the rare cases when you want to
123 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
125 define('PARAM_CLEANHTML', 'cleanhtml');
128 * PARAM_EMAIL - an email address following the RFC
130 define('PARAM_EMAIL', 'email');
133 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
135 define('PARAM_FILE', 'file');
138 * PARAM_FLOAT - a real/floating point number.
140 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
141 * It does not work for languages that use , as a decimal separator.
142 * Instead, do something like
143 * $rawvalue = required_param('name', PARAM_RAW);
144 * // ... other code including require_login, which sets current lang ...
145 * $realvalue = unformat_float($rawvalue);
146 * // ... then use $realvalue
148 define('PARAM_FLOAT', 'float');
151 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
153 define('PARAM_HOST', 'host');
156 * PARAM_INT - integers only, use when expecting only numbers.
158 define('PARAM_INT', 'int');
161 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
163 define('PARAM_LANG', 'lang');
166 * 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!)
168 define('PARAM_LOCALURL', 'localurl');
171 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
173 define('PARAM_NOTAGS', 'notags');
176 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
177 * note: the leading slash is not removed, window drive letter is not allowed
179 define('PARAM_PATH', 'path');
182 * PARAM_PEM - Privacy Enhanced Mail format
184 define('PARAM_PEM', 'pem');
187 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
189 define('PARAM_PERMISSION', 'permission');
192 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
194 define('PARAM_RAW', 'raw');
197 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
199 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
202 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
204 define('PARAM_SAFEDIR', 'safedir');
207 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
209 define('PARAM_SAFEPATH', 'safepath');
212 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
214 define('PARAM_SEQUENCE', 'sequence');
217 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
219 define('PARAM_TAG', 'tag');
222 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
224 define('PARAM_TAGLIST', 'taglist');
227 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
229 define('PARAM_TEXT', 'text');
232 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
234 define('PARAM_THEME', 'theme');
237 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user accounts, do NOT use when syncing with external systems!!
244 define('PARAM_USERNAME', 'username');
247 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
249 define('PARAM_STRINGID', 'stringid');
251 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
253 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
254 * It was one of the first types, that is why it is abused so much ;-)
255 * @deprecated since 2.0
257 define('PARAM_CLEAN', 'clean');
260 * PARAM_INTEGER - deprecated alias for PARAM_INT
261 * @deprecated since 2.0
263 define('PARAM_INTEGER', 'int');
266 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
267 * @deprecated since 2.0
269 define('PARAM_NUMBER', 'float');
272 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
273 * NOTE: originally alias for PARAM_APLHA
274 * @deprecated since 2.0
276 define('PARAM_ACTION', 'alphanumext');
279 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
280 * NOTE: originally alias for PARAM_APLHA
281 * @deprecated since 2.0
283 define('PARAM_FORMAT', 'alphanumext');
286 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
287 * @deprecated since 2.0
289 define('PARAM_MULTILANG', 'text');
292 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
293 * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
294 * America/Port-au-Prince)
296 define('PARAM_TIMEZONE', 'timezone');
299 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
301 define('PARAM_CLEANFILE', 'file');
304 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
305 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
306 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
307 * NOTE: numbers and underscores are strongly discouraged in plugin names!
309 define('PARAM_COMPONENT', 'component');
312 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
313 * It is usually used together with context id and component.
314 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
316 define('PARAM_AREA', 'area');
319 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
320 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
321 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
323 define('PARAM_PLUGIN', 'plugin');
329 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
331 define('VALUE_REQUIRED', 1);
334 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
336 define('VALUE_OPTIONAL', 2);
339 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
341 define('VALUE_DEFAULT', 0);
344 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
346 define('NULL_NOT_ALLOWED', false);
349 * NULL_ALLOWED - the parameter can be set to null in the database
351 define('NULL_ALLOWED', true);
355 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
357 define('PAGE_COURSE_VIEW', 'course-view');
359 /** Get remote addr constant */
360 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
364 /// Blog access level constant declaration ///
365 define ('BLOG_USER_LEVEL', 1);
366 define ('BLOG_GROUP_LEVEL', 2);
367 define ('BLOG_COURSE_LEVEL', 3);
368 define ('BLOG_SITE_LEVEL', 4);
369 define ('BLOG_GLOBAL_LEVEL', 5);
374 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
375 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
376 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
378 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
380 define('TAG_MAX_LENGTH', 50);
382 /// Password policy constants ///
383 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
384 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
385 define ('PASSWORD_DIGITS', '0123456789');
386 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
388 /// Feature constants ///
389 // Used for plugin_supports() to report features that are, or are not, supported by a module.
391 /** True if module can provide a grade */
392 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
393 /** True if module supports outcomes */
394 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
395 /** True if module supports advanced grading methods */
396 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
397 /** True if module controls the grade visibility over the gradebook */
398 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
399 /** True if module supports plagiarism plugins */
400 define('FEATURE_PLAGIARISM', 'plagiarism');
402 /** True if module has code to track whether somebody viewed it */
403 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
404 /** True if module has custom completion rules */
405 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
407 /** True if module has no 'view' page (like label) */
408 define('FEATURE_NO_VIEW_LINK', 'viewlink');
409 /** True if module supports outcomes */
410 define('FEATURE_IDNUMBER', 'idnumber');
411 /** True if module supports groups */
412 define('FEATURE_GROUPS', 'groups');
413 /** True if module supports groupings */
414 define('FEATURE_GROUPINGS', 'groupings');
415 /** True if module supports groupmembersonly */
416 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
418 /** Type of module */
419 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
420 /** True if module supports intro editor */
421 define('FEATURE_MOD_INTRO', 'mod_intro');
422 /** True if module has default completion */
423 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
425 define('FEATURE_COMMENT', 'comment');
427 define('FEATURE_RATE', 'rate');
428 /** True if module supports backup/restore of moodle2 format */
429 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
431 /** True if module can show description on course main page */
432 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
434 /** Unspecified module archetype */
435 define('MOD_ARCHETYPE_OTHER', 0);
436 /** Resource-like type module */
437 define('MOD_ARCHETYPE_RESOURCE', 1);
438 /** Assignment module archetype */
439 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
440 /** System (not user-addable) module archetype */
441 define('MOD_ARCHETYPE_SYSTEM', 3);
444 * Security token used for allowing access
445 * from external application such as web services.
446 * Scripts do not use any session, performance is relatively
447 * low because we need to load access info in each request.
448 * Scripts are executed in parallel.
450 define('EXTERNAL_TOKEN_PERMANENT', 0);
453 * Security token used for allowing access
454 * of embedded applications, the code is executed in the
455 * active user session. Token is invalidated after user logs out.
456 * Scripts are executed serially - normal session locking is used.
458 define('EXTERNAL_TOKEN_EMBEDDED', 1);
461 * The home page should be the site home
463 define('HOMEPAGE_SITE', 0);
465 * The home page should be the users my page
467 define('HOMEPAGE_MY', 1);
469 * The home page can be chosen by the user
471 define('HOMEPAGE_USER', 2);
474 * Hub directory url (should be moodle.org)
476 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
480 * Moodle.org url (should be moodle.org)
482 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
485 * Moodle mobile app service name
487 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
490 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
492 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
495 * Course display settings
497 define('COURSE_DISPLAY_SINGLEPAGE', 0); // display all sections on one page
498 define('COURSE_DISPLAY_MULTIPAGE', 1); // split pages into a page per section
501 * Authentication constants.
503 define('AUTH_PASSWORD_NOT_CACHED', 'not cached'); // String used in password field when password is not stored.
505 /// PARAMETER HANDLING ////////////////////////////////////////////////////
508 * Returns a particular value for the named variable, taken from
509 * POST or GET. If the parameter doesn't exist then an error is
510 * thrown because we require this variable.
512 * This function should be used to initialise all required values
513 * in a script that are based on parameters. Usually it will be
515 * $id = required_param('id', PARAM_INT);
517 * Please note the $type parameter is now required and the value can not be array.
519 * @param string $parname the name of the page parameter we want
520 * @param string $type expected type of parameter
523 function required_param($parname, $type) {
524 if (func_num_args() != 2 or empty($parname) or empty($type)) {
525 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
527 if (isset($_POST[$parname])) { // POST has precedence
528 $param = $_POST[$parname];
529 } else if (isset($_GET[$parname])) {
530 $param = $_GET[$parname];
532 print_error('missingparam', '', '', $parname);
535 if (is_array($param)) {
536 debugging('Invalid array parameter detected in required_param(): '.$parname);
537 // TODO: switch to fatal error in Moodle 2.3
538 //print_error('missingparam', '', '', $parname);
539 return required_param_array($parname, $type);
542 return clean_param($param, $type);
546 * Returns a particular array value for the named variable, taken from
547 * POST or GET. If the parameter doesn't exist then an error is
548 * thrown because we require this variable.
550 * This function should be used to initialise all required values
551 * in a script that are based on parameters. Usually it will be
553 * $ids = required_param_array('ids', PARAM_INT);
555 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
557 * @param string $parname the name of the page parameter we want
558 * @param string $type expected type of parameter
561 function required_param_array($parname, $type) {
562 if (func_num_args() != 2 or empty($parname) or empty($type)) {
563 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
565 if (isset($_POST[$parname])) { // POST has precedence
566 $param = $_POST[$parname];
567 } else if (isset($_GET[$parname])) {
568 $param = $_GET[$parname];
570 print_error('missingparam', '', '', $parname);
572 if (!is_array($param)) {
573 print_error('missingparam', '', '', $parname);
577 foreach($param as $key=>$value) {
578 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
579 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
582 $result[$key] = clean_param($value, $type);
589 * Returns a particular value for the named variable, taken from
590 * POST or GET, otherwise returning a given default.
592 * This function should be used to initialise all optional values
593 * in a script that are based on parameters. Usually it will be
595 * $name = optional_param('name', 'Fred', PARAM_TEXT);
597 * Please note the $type parameter is now required and the value can not be array.
599 * @param string $parname the name of the page parameter we want
600 * @param mixed $default the default value to return if nothing is found
601 * @param string $type expected type of parameter
604 function optional_param($parname, $default, $type) {
605 if (func_num_args() != 3 or empty($parname) or empty($type)) {
606 throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
608 if (!isset($default)) {
612 if (isset($_POST[$parname])) { // POST has precedence
613 $param = $_POST[$parname];
614 } else if (isset($_GET[$parname])) {
615 $param = $_GET[$parname];
620 if (is_array($param)) {
621 debugging('Invalid array parameter detected in required_param(): '.$parname);
622 // TODO: switch to $default in Moodle 2.3
624 return optional_param_array($parname, $default, $type);
627 return clean_param($param, $type);
631 * Returns a particular array value for the named variable, taken from
632 * POST or GET, otherwise returning a given default.
634 * This function should be used to initialise all optional values
635 * in a script that are based on parameters. Usually it will be
637 * $ids = optional_param('id', array(), PARAM_INT);
639 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
641 * @param string $parname the name of the page parameter we want
642 * @param mixed $default the default value to return if nothing is found
643 * @param string $type expected type of parameter
646 function optional_param_array($parname, $default, $type) {
647 if (func_num_args() != 3 or empty($parname) or empty($type)) {
648 throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
651 if (isset($_POST[$parname])) { // POST has precedence
652 $param = $_POST[$parname];
653 } else if (isset($_GET[$parname])) {
654 $param = $_GET[$parname];
658 if (!is_array($param)) {
659 debugging('optional_param_array() expects array parameters only: '.$parname);
664 foreach($param as $key=>$value) {
665 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
666 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
669 $result[$key] = clean_param($value, $type);
676 * Strict validation of parameter values, the values are only converted
677 * to requested PHP type. Internally it is using clean_param, the values
678 * before and after cleaning must be equal - otherwise
679 * an invalid_parameter_exception is thrown.
680 * Objects and classes are not accepted.
682 * @param mixed $param
683 * @param string $type PARAM_ constant
684 * @param bool $allownull are nulls valid value?
685 * @param string $debuginfo optional debug information
686 * @return mixed the $param value converted to PHP type
687 * @throws invalid_parameter_exception if $param is not of given type
689 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
690 if (is_null($param)) {
691 if ($allownull == NULL_ALLOWED) {
694 throw new invalid_parameter_exception($debuginfo);
697 if (is_array($param) or is_object($param)) {
698 throw new invalid_parameter_exception($debuginfo);
701 $cleaned = clean_param($param, $type);
703 if ($type == PARAM_FLOAT) {
704 // Do not detect precision loss here.
705 if (is_float($param) or is_int($param)) {
707 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
708 throw new invalid_parameter_exception($debuginfo);
710 } else if ((string)$param !== (string)$cleaned) {
711 // conversion to string is usually lossless
712 throw new invalid_parameter_exception($debuginfo);
719 * Makes sure array contains only the allowed types,
720 * this function does not validate array key names!
722 * $options = clean_param($options, PARAM_INT);
725 * @param array $param the variable array we are cleaning
726 * @param string $type expected format of param after cleaning.
727 * @param bool $recursive clean recursive arrays
730 function clean_param_array(array $param = null, $type, $recursive = false) {
731 $param = (array)$param; // convert null to empty array
732 foreach ($param as $key => $value) {
733 if (is_array($value)) {
735 $param[$key] = clean_param_array($value, $type, true);
737 throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
740 $param[$key] = clean_param($value, $type);
747 * Used by {@link optional_param()} and {@link required_param()} to
748 * clean the variables and/or cast to specific types, based on
751 * $course->format = clean_param($course->format, PARAM_ALPHA);
752 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
755 * @param mixed $param the variable we are cleaning
756 * @param string $type expected format of param after cleaning.
759 function clean_param($param, $type) {
763 if (is_array($param)) {
764 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
765 } else if (is_object($param)) {
766 if (method_exists($param, '__toString')) {
767 $param = $param->__toString();
769 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
774 case PARAM_RAW: // no cleaning at all
775 $param = fix_utf8($param);
778 case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
779 $param = fix_utf8($param);
782 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
783 // this is deprecated!, please use more specific type instead
784 if (is_numeric($param)) {
787 $param = fix_utf8($param);
788 return clean_text($param); // Sweep for scripts, etc
790 case PARAM_CLEANHTML: // clean html fragment
791 $param = fix_utf8($param);
792 $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
796 return (int)$param; // Convert to integer
799 return (float)$param; // Convert to float
801 case PARAM_ALPHA: // Remove everything not a-z
802 return preg_replace('/[^a-zA-Z]/i', '', $param);
804 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
805 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
807 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
808 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
810 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
811 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
813 case PARAM_SEQUENCE: // Remove everything not 0-9,
814 return preg_replace('/[^0-9,]/i', '', $param);
816 case PARAM_BOOL: // Convert to 1 or 0
817 $tempstr = strtolower($param);
818 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
820 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
823 $param = empty($param) ? 0 : 1;
827 case PARAM_NOTAGS: // Strip all tags
828 $param = fix_utf8($param);
829 return strip_tags($param);
831 case PARAM_TEXT: // leave only tags needed for multilang
832 $param = fix_utf8($param);
833 // if the multilang syntax is not correct we strip all tags
834 // because it would break xhtml strict which is required for accessibility standards
835 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
837 if (strpos($param, '</lang>') !== false) {
838 // old and future mutilang syntax
839 $param = strip_tags($param, '<lang>');
840 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
844 foreach ($matches[0] as $match) {
845 if ($match === '</lang>') {
853 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
864 } else if (strpos($param, '</span>') !== false) {
865 // current problematic multilang syntax
866 $param = strip_tags($param, '<span>');
867 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
871 foreach ($matches[0] as $match) {
872 if ($match === '</span>') {
880 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
892 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
893 return strip_tags($param);
895 case PARAM_COMPONENT:
896 // we do not want any guessing here, either the name is correct or not
897 // please note only normalised component names are accepted
898 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
901 if (strpos($param, '__') !== false) {
904 if (strpos($param, 'mod_') === 0) {
905 // module names must not contain underscores because we need to differentiate them from invalid plugin types
906 if (substr_count($param, '_') != 1) {
914 // we do not want any guessing here, either the name is correct or not
915 if (!is_valid_plugin_name($param)) {
920 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
921 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
923 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
924 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
926 case PARAM_FILE: // Strip all suspicious characters from filename
927 $param = fix_utf8($param);
928 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
929 if ($param === '.' || $param === '..') {
934 case PARAM_PATH: // Strip all suspicious characters from file path
935 $param = fix_utf8($param);
936 $param = str_replace('\\', '/', $param);
938 // Explode the path and clean each element using the PARAM_FILE rules.
939 $breadcrumb = explode('/', $param);
940 foreach ($breadcrumb as $key => $crumb) {
941 if ($crumb === '.' && $key === 0) {
942 // Special condition to allow for relative current path such as ./currentdirfile.txt.
944 $crumb = clean_param($crumb, PARAM_FILE);
946 $breadcrumb[$key] = $crumb;
948 $param = implode('/', $breadcrumb);
950 // Remove multiple current path (./././) and multiple slashes (///).
951 $param = preg_replace('~//+~', '/', $param);
952 $param = preg_replace('~/(\./)+~', '/', $param);
955 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
956 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
957 // match ipv4 dotted quad
958 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
959 // confirm values are ok
963 || $match[4] > 255 ) {
964 // hmmm, what kind of dotted quad is this?
967 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
968 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
969 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
971 // all is ok - $param is respected
978 case PARAM_URL: // allow safe ftp, http, mailto urls
979 $param = fix_utf8($param);
980 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
981 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
982 // all is ok, param is respected
984 $param =''; // not really ok
988 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
989 $param = clean_param($param, PARAM_URL);
990 if (!empty($param)) {
991 if (preg_match(':^/:', $param)) {
992 // root-relative, ok!
993 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
994 // absolute, and matches our wwwroot
996 // relative - let's make sure there are no tricks
997 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1007 $param = trim($param);
1008 // PEM formatted strings may contain letters/numbers and the symbols
1012 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
1013 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1014 list($wholething, $body) = $matches;
1015 unset($wholething, $matches);
1016 $b64 = clean_param($body, PARAM_BASE64);
1018 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1026 if (!empty($param)) {
1027 // PEM formatted strings may contain letters/numbers and the symbols
1031 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1034 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1035 // Each line of base64 encoded data must be 64 characters in
1036 // length, except for the last line which may be less than (or
1037 // equal to) 64 characters long.
1038 for ($i=0, $j=count($lines); $i < $j; $i++) {
1040 if (64 < strlen($lines[$i])) {
1046 if (64 != strlen($lines[$i])) {
1050 return implode("\n",$lines);
1056 $param = fix_utf8($param);
1057 // Please note it is not safe to use the tag name directly anywhere,
1058 // it must be processed with s(), urlencode() before embedding anywhere.
1059 // remove some nasties
1060 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1061 //convert many whitespace chars into one
1062 $param = preg_replace('/\s+/', ' ', $param);
1063 $param = textlib::substr(trim($param), 0, TAG_MAX_LENGTH);
1067 $param = fix_utf8($param);
1068 $tags = explode(',', $param);
1070 foreach ($tags as $tag) {
1071 $res = clean_param($tag, PARAM_TAG);
1077 return implode(',', $result);
1082 case PARAM_CAPABILITY:
1083 if (get_capability_info($param)) {
1089 case PARAM_PERMISSION:
1090 $param = (int)$param;
1091 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1098 $param = clean_param($param, PARAM_PLUGIN);
1099 if (empty($param)) {
1101 } else if (exists_auth_plugin($param)) {
1108 $param = clean_param($param, PARAM_SAFEDIR);
1109 if (get_string_manager()->translation_exists($param)) {
1112 return ''; // Specified language is not installed or param malformed
1116 $param = clean_param($param, PARAM_PLUGIN);
1117 if (empty($param)) {
1119 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1121 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1124 return ''; // Specified theme is not installed
1127 case PARAM_USERNAME:
1128 $param = fix_utf8($param);
1129 $param = str_replace(" " , "", $param);
1130 $param = textlib::strtolower($param); // Convert uppercase to lowercase MDL-16919
1131 if (empty($CFG->extendedusernamechars)) {
1132 // regular expression, eliminate all chars EXCEPT:
1133 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1134 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1139 $param = fix_utf8($param);
1140 if (validate_email($param)) {
1146 case PARAM_STRINGID:
1147 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1153 case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1154 $param = fix_utf8($param);
1155 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1156 if (preg_match($timezonepattern, $param)) {
1162 default: // throw error, switched parameters in optional_param or another serious problem
1163 print_error("unknownparamtype", '', '', $type);
1168 * Makes sure the data is using valid utf8, invalid characters are discarded.
1170 * Note: this function is not intended for full objects with methods and private properties.
1172 * @param mixed $value
1173 * @return mixed with proper utf-8 encoding
1175 function fix_utf8($value) {
1176 if (is_null($value) or $value === '') {
1179 } else if (is_string($value)) {
1180 if ((string)(int)$value === $value) {
1185 // Lower error reporting because glibc throws bogus notices.
1186 $olderror = error_reporting();
1187 if ($olderror & E_NOTICE) {
1188 error_reporting($olderror ^ E_NOTICE);
1191 // Note: this duplicates min_fix_utf8() intentionally.
1192 static $buggyiconv = null;
1193 if ($buggyiconv === null) {
1194 $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1198 if (function_exists('mb_convert_encoding')) {
1199 $subst = mb_substitute_character();
1200 mb_substitute_character('');
1201 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1202 mb_substitute_character($subst);
1205 // Warn admins on admin/index.php page.
1210 $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1213 if ($olderror & E_NOTICE) {
1214 error_reporting($olderror);
1219 } else if (is_array($value)) {
1220 foreach ($value as $k=>$v) {
1221 $value[$k] = fix_utf8($v);
1225 } else if (is_object($value)) {
1226 $value = clone($value); // do not modify original
1227 foreach ($value as $k=>$v) {
1228 $value->$k = fix_utf8($v);
1233 // this is some other type, no utf-8 here
1239 * Return true if given value is integer or string with integer value
1241 * @param mixed $value String or Int
1242 * @return bool true if number, false if not
1244 function is_number($value) {
1245 if (is_int($value)) {
1247 } else if (is_string($value)) {
1248 return ((string)(int)$value) === $value;
1255 * Returns host part from url
1256 * @param string $url full url
1257 * @return string host, null if not found
1259 function get_host_from_url($url) {
1260 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1268 * Tests whether anything was returned by text editor
1270 * This function is useful for testing whether something you got back from
1271 * the HTML editor actually contains anything. Sometimes the HTML editor
1272 * appear to be empty, but actually you get back a <br> tag or something.
1274 * @param string $string a string containing HTML.
1275 * @return boolean does the string contain any actual content - that is text,
1276 * images, objects, etc.
1278 function html_is_blank($string) {
1279 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1283 * Set a key in global configuration
1285 * Set a key/value pair in both this session's {@link $CFG} global variable
1286 * and in the 'config' database table for future sessions.
1288 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1289 * In that case it doesn't affect $CFG.
1291 * A NULL value will delete the entry.
1295 * @param string $name the key to set
1296 * @param string $value the value to set (without magic quotes)
1297 * @param string $plugin (optional) the plugin scope, default NULL
1298 * @return bool true or exception
1300 function set_config($name, $value, $plugin=NULL) {
1303 if (empty($plugin)) {
1304 if (!array_key_exists($name, $CFG->config_php_settings)) {
1305 // So it's defined for this invocation at least
1306 if (is_null($value)) {
1309 $CFG->$name = (string)$value; // settings from db are always strings
1313 if ($DB->get_field('config', 'name', array('name'=>$name))) {
1314 if ($value === null) {
1315 $DB->delete_records('config', array('name'=>$name));
1317 $DB->set_field('config', 'value', $value, array('name'=>$name));
1320 if ($value !== null) {
1321 $config = new stdClass();
1322 $config->name = $name;
1323 $config->value = $value;
1324 $DB->insert_record('config', $config, false);
1327 if ($name === 'siteidentifier') {
1328 cache_helper::update_site_identifier($value);
1330 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1331 } else { // plugin scope
1332 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1333 if ($value===null) {
1334 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1336 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1339 if ($value !== null) {
1340 $config = new stdClass();
1341 $config->plugin = $plugin;
1342 $config->name = $name;
1343 $config->value = $value;
1344 $DB->insert_record('config_plugins', $config, false);
1347 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1354 * Get configuration values from the global config table
1355 * or the config_plugins table.
1357 * If called with one parameter, it will load all the config
1358 * variables for one plugin, and return them as an object.
1360 * If called with 2 parameters it will return a string single
1361 * value or false if the value is not found.
1363 * @static $siteidentifier The site identifier is not cached. We use this static cache so
1364 * that we need only fetch it once per request.
1365 * @param string $plugin full component name
1366 * @param string $name default NULL
1367 * @return mixed hash-like object or single value, return false no config found
1369 function get_config($plugin, $name = NULL) {
1372 static $siteidentifier = null;
1374 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1375 $forced =& $CFG->config_php_settings;
1379 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1380 $forced =& $CFG->forced_plugin_settings[$plugin];
1387 if ($siteidentifier === null) {
1389 // This may fail during installation.
1390 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1391 // install the database.
1392 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1393 } catch (dml_exception $ex) {
1394 // Set siteidentifier to false. We don't want to trip this continually.
1395 $siteidentifier = false;
1400 if (!empty($name)) {
1401 if (array_key_exists($name, $forced)) {
1402 return (string)$forced[$name];
1403 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1404 return $siteidentifier;
1408 $cache = cache::make('core', 'config');
1409 $result = $cache->get($plugin);
1410 if ($result === false) {
1411 // the user is after a recordset
1412 $result = new stdClass;
1414 $result = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1416 // this part is not really used any more, but anyway...
1417 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1419 $cache->set($plugin, $result);
1422 if (!empty($name)) {
1423 if (array_key_exists($name, $result)) {
1424 return $result[$name];
1429 if ($plugin === 'core') {
1430 $result['siteidentifier'] = $siteidentifier;
1433 foreach ($forced as $key => $value) {
1434 if (is_null($value) or is_array($value) or is_object($value)) {
1435 // we do not want any extra mess here, just real settings that could be saved in db
1436 unset($result[$key]);
1438 //convert to string as if it went through the DB
1439 $result[$key] = (string)$value;
1443 return (object)$result;
1447 * Removes a key from global configuration
1449 * @param string $name the key to set
1450 * @param string $plugin (optional) the plugin scope
1452 * @return boolean whether the operation succeeded.
1454 function unset_config($name, $plugin=NULL) {
1457 if (empty($plugin)) {
1459 $DB->delete_records('config', array('name'=>$name));
1460 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1462 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1463 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1470 * Remove all the config variables for a given plugin.
1472 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1473 * @return boolean whether the operation succeeded.
1475 function unset_all_config_for_plugin($plugin) {
1477 // Delete from the obvious config_plugins first
1478 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1479 // Next delete any suspect settings from config
1480 $like = $DB->sql_like('name', '?', true, true, false, '|');
1481 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1482 $DB->delete_records_select('config', $like, $params);
1483 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1484 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1490 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1492 * All users are verified if they still have the necessary capability.
1494 * @param string $value the value of the config setting.
1495 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1496 * @param bool $include admins, include administrators
1497 * @return array of user objects.
1499 function get_users_from_config($value, $capability, $includeadmins = true) {
1502 if (empty($value) or $value === '$@NONE@$') {
1506 // we have to make sure that users still have the necessary capability,
1507 // it should be faster to fetch them all first and then test if they are present
1508 // instead of validating them one-by-one
1509 $users = get_users_by_capability(context_system::instance(), $capability);
1510 if ($includeadmins) {
1511 $admins = get_admins();
1512 foreach ($admins as $admin) {
1513 $users[$admin->id] = $admin;
1517 if ($value === '$@ALL@$') {
1521 $result = array(); // result in correct order
1522 $allowed = explode(',', $value);
1523 foreach ($allowed as $uid) {
1524 if (isset($users[$uid])) {
1525 $user = $users[$uid];
1526 $result[$user->id] = $user;
1535 * Invalidates browser caches and cached data in temp
1537 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1538 * {@see phpunit_util::reset_dataroot()}
1542 function purge_all_caches() {
1545 reset_text_filters_cache();
1546 js_reset_all_caches();
1547 theme_reset_all_caches();
1548 get_string_manager()->reset_caches();
1549 textlib::reset_caches();
1551 cache_helper::purge_all();
1553 // purge all other caches: rss, simplepie, etc.
1554 remove_dir($CFG->cachedir.'', true);
1556 // make sure cache dir is writable, throws exception if not
1557 make_cache_directory('');
1559 // hack: this script may get called after the purifier was initialised,
1560 // but we do not want to verify repeatedly this exists in each call
1561 make_cache_directory('htmlpurifier');
1565 * Get volatile flags
1567 * @param string $type
1568 * @param int $changedsince default null
1569 * @return records array
1571 function get_cache_flags($type, $changedsince=NULL) {
1574 $params = array('type'=>$type, 'expiry'=>time());
1575 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1576 if ($changedsince !== NULL) {
1577 $params['changedsince'] = $changedsince;
1578 $sqlwhere .= " AND timemodified > :changedsince";
1582 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1583 foreach ($flags as $flag) {
1584 $cf[$flag->name] = $flag->value;
1591 * Get volatile flags
1593 * @param string $type
1594 * @param string $name
1595 * @param int $changedsince default null
1596 * @return records array
1598 function get_cache_flag($type, $name, $changedsince=NULL) {
1601 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1603 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1604 if ($changedsince !== NULL) {
1605 $params['changedsince'] = $changedsince;
1606 $sqlwhere .= " AND timemodified > :changedsince";
1609 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1613 * Set a volatile flag
1615 * @param string $type the "type" namespace for the key
1616 * @param string $name the key to set
1617 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1618 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1619 * @return bool Always returns true
1621 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1624 $timemodified = time();
1625 if ($expiry===NULL || $expiry < $timemodified) {
1626 $expiry = $timemodified + 24 * 60 * 60;
1628 $expiry = (int)$expiry;
1631 if ($value === NULL) {
1632 unset_cache_flag($type,$name);
1636 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1637 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1638 return true; //no need to update
1641 $f->expiry = $expiry;
1642 $f->timemodified = $timemodified;
1643 $DB->update_record('cache_flags', $f);
1645 $f = new stdClass();
1646 $f->flagtype = $type;
1649 $f->expiry = $expiry;
1650 $f->timemodified = $timemodified;
1651 $DB->insert_record('cache_flags', $f);
1657 * Removes a single volatile flag
1660 * @param string $type the "type" namespace for the key
1661 * @param string $name the key to set
1664 function unset_cache_flag($type, $name) {
1666 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1671 * Garbage-collect volatile flags
1673 * @return bool Always returns true
1675 function gc_cache_flags() {
1677 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1681 // USER PREFERENCE API
1684 * Refresh user preference cache. This is used most often for $USER
1685 * object that is stored in session, but it also helps with performance in cron script.
1687 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1690 * @category preference
1692 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1693 * @param int $cachelifetime Cache life time on the current page (in seconds)
1694 * @throws coding_exception
1697 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1699 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1701 if (!isset($user->id)) {
1702 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1705 if (empty($user->id) or isguestuser($user->id)) {
1706 // No permanent storage for not-logged-in users and guest
1707 if (!isset($user->preference)) {
1708 $user->preference = array();
1715 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1716 // Already loaded at least once on this page. Are we up to date?
1717 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1718 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1721 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1722 // no change since the lastcheck on this page
1723 $user->preference['_lastloaded'] = $timenow;
1728 // OK, so we have to reload all preferences
1729 $loadedusers[$user->id] = true;
1730 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1731 $user->preference['_lastloaded'] = $timenow;
1735 * Called from set/unset_user_preferences, so that the prefs can
1736 * be correctly reloaded in different sessions.
1738 * NOTE: internal function, do not call from other code.
1742 * @param integer $userid the user whose prefs were changed.
1744 function mark_user_preferences_changed($userid) {
1747 if (empty($userid) or isguestuser($userid)) {
1748 // no cache flags for guest and not-logged-in users
1752 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1756 * Sets a preference for the specified user.
1758 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1761 * @category preference
1763 * @param string $name The key to set as preference for the specified user
1764 * @param string $value The value to set for the $name key in the specified user's
1765 * record, null means delete current value.
1766 * @param stdClass|int|null $user A moodle user object or id, null means current user
1767 * @throws coding_exception
1768 * @return bool Always true or exception
1770 function set_user_preference($name, $value, $user = null) {
1773 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1774 throw new coding_exception('Invalid preference name in set_user_preference() call');
1777 if (is_null($value)) {
1778 // null means delete current
1779 return unset_user_preference($name, $user);
1780 } else if (is_object($value)) {
1781 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1782 } else if (is_array($value)) {
1783 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1785 $value = (string)$value;
1786 if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1787 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1790 if (is_null($user)) {
1792 } else if (isset($user->id)) {
1793 // $user is valid object
1794 } else if (is_numeric($user)) {
1795 $user = (object)array('id'=>(int)$user);
1797 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1800 check_user_preferences_loaded($user);
1802 if (empty($user->id) or isguestuser($user->id)) {
1803 // no permanent storage for not-logged-in users and guest
1804 $user->preference[$name] = $value;
1808 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1809 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1810 // preference already set to this value
1813 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1816 $preference = new stdClass();
1817 $preference->userid = $user->id;
1818 $preference->name = $name;
1819 $preference->value = $value;
1820 $DB->insert_record('user_preferences', $preference);
1823 // update value in cache
1824 $user->preference[$name] = $value;
1826 // set reload flag for other sessions
1827 mark_user_preferences_changed($user->id);
1833 * Sets a whole array of preferences for the current user
1835 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1838 * @category preference
1840 * @param array $prefarray An array of key/value pairs to be set
1841 * @param stdClass|int|null $user A moodle user object or id, null means current user
1842 * @return bool Always true or exception
1844 function set_user_preferences(array $prefarray, $user = null) {
1845 foreach ($prefarray as $name => $value) {
1846 set_user_preference($name, $value, $user);
1852 * Unsets a preference completely by deleting it from the database
1854 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1857 * @category preference
1859 * @param string $name The key to unset as preference for the specified user
1860 * @param stdClass|int|null $user A moodle user object or id, null means current user
1861 * @throws coding_exception
1862 * @return bool Always true or exception
1864 function unset_user_preference($name, $user = null) {
1867 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1868 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1871 if (is_null($user)) {
1873 } else if (isset($user->id)) {
1874 // $user is valid object
1875 } else if (is_numeric($user)) {
1876 $user = (object)array('id'=>(int)$user);
1878 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1881 check_user_preferences_loaded($user);
1883 if (empty($user->id) or isguestuser($user->id)) {
1884 // no permanent storage for not-logged-in user and guest
1885 unset($user->preference[$name]);
1890 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1892 // delete the preference from cache
1893 unset($user->preference[$name]);
1895 // set reload flag for other sessions
1896 mark_user_preferences_changed($user->id);
1902 * Used to fetch user preference(s)
1904 * If no arguments are supplied this function will return
1905 * all of the current user preferences as an array.
1907 * If a name is specified then this function
1908 * attempts to return that particular preference value. If
1909 * none is found, then the optional value $default is returned,
1912 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1915 * @category preference
1917 * @param string $name Name of the key to use in finding a preference value
1918 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1919 * @param stdClass|int|null $user A moodle user object or id, null means current user
1920 * @throws coding_exception
1921 * @return string|mixed|null A string containing the value of a single preference. An
1922 * array with all of the preferences or null
1924 function get_user_preferences($name = null, $default = null, $user = null) {
1927 if (is_null($name)) {
1929 } else if (is_numeric($name) or $name === '_lastloaded') {
1930 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1933 if (is_null($user)) {
1935 } else if (isset($user->id)) {
1936 // $user is valid object
1937 } else if (is_numeric($user)) {
1938 $user = (object)array('id'=>(int)$user);
1940 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1943 check_user_preferences_loaded($user);
1946 return $user->preference; // All values
1947 } else if (isset($user->preference[$name])) {
1948 return $user->preference[$name]; // The single string value
1950 return $default; // Default value (null if not specified)
1954 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1957 * Given date parts in user time produce a GMT timestamp.
1961 * @param int $year The year part to create timestamp of
1962 * @param int $month The month part to create timestamp of
1963 * @param int $day The day part to create timestamp of
1964 * @param int $hour The hour part to create timestamp of
1965 * @param int $minute The minute part to create timestamp of
1966 * @param int $second The second part to create timestamp of
1967 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1968 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
1969 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1970 * applied only if timezone is 99 or string.
1971 * @return int GMT timestamp
1973 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1975 //save input timezone, required for dst offset check.
1976 $passedtimezone = $timezone;
1978 $timezone = get_user_timezone_offset($timezone);
1980 if (abs($timezone) > 13) { //server time
1981 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1983 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1984 $time = usertime($time, $timezone);
1986 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1987 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1988 $time -= dst_offset_on($time, $passedtimezone);
1997 * Format a date/time (seconds) as weeks, days, hours etc as needed
1999 * Given an amount of time in seconds, returns string
2000 * formatted nicely as weeks, days, hours etc as needed
2008 * @param int $totalsecs Time in seconds
2009 * @param object $str Should be a time object
2010 * @return string A nicely formatted date/time string
2012 function format_time($totalsecs, $str=NULL) {
2014 $totalsecs = abs($totalsecs);
2016 if (!$str) { // Create the str structure the slow way
2017 $str = new stdClass();
2018 $str->day = get_string('day');
2019 $str->days = get_string('days');
2020 $str->hour = get_string('hour');
2021 $str->hours = get_string('hours');
2022 $str->min = get_string('min');
2023 $str->mins = get_string('mins');
2024 $str->sec = get_string('sec');
2025 $str->secs = get_string('secs');
2026 $str->year = get_string('year');
2027 $str->years = get_string('years');
2031 $years = floor($totalsecs/YEARSECS);
2032 $remainder = $totalsecs - ($years*YEARSECS);
2033 $days = floor($remainder/DAYSECS);
2034 $remainder = $totalsecs - ($days*DAYSECS);
2035 $hours = floor($remainder/HOURSECS);
2036 $remainder = $remainder - ($hours*HOURSECS);
2037 $mins = floor($remainder/MINSECS);
2038 $secs = $remainder - ($mins*MINSECS);
2040 $ss = ($secs == 1) ? $str->sec : $str->secs;
2041 $sm = ($mins == 1) ? $str->min : $str->mins;
2042 $sh = ($hours == 1) ? $str->hour : $str->hours;
2043 $sd = ($days == 1) ? $str->day : $str->days;
2044 $sy = ($years == 1) ? $str->year : $str->years;
2052 if ($years) $oyears = $years .' '. $sy;
2053 if ($days) $odays = $days .' '. $sd;
2054 if ($hours) $ohours = $hours .' '. $sh;
2055 if ($mins) $omins = $mins .' '. $sm;
2056 if ($secs) $osecs = $secs .' '. $ss;
2058 if ($years) return trim($oyears .' '. $odays);
2059 if ($days) return trim($odays .' '. $ohours);
2060 if ($hours) return trim($ohours .' '. $omins);
2061 if ($mins) return trim($omins .' '. $osecs);
2062 if ($secs) return $osecs;
2063 return get_string('now');
2067 * Returns a formatted string that represents a date in user time
2069 * Returns a formatted string that represents a date in user time
2070 * <b>WARNING: note that the format is for strftime(), not date().</b>
2071 * Because of a bug in most Windows time libraries, we can't use
2072 * the nicer %e, so we have to use %d which has leading zeroes.
2073 * A lot of the fuss in the function is just getting rid of these leading
2074 * zeroes as efficiently as possible.
2076 * If parameter fixday = true (default), then take off leading
2077 * zero from %d, else maintain it.
2081 * @param int $date the timestamp in UTC, as obtained from the database.
2082 * @param string $format strftime format. You should probably get this using
2083 * get_string('strftime...', 'langconfig');
2084 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2085 * not 99 then daylight saving will not be added.
2086 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2087 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2088 * If false then the leading zero is maintained.
2089 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2090 * @return string the formatted date/time.
2092 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2096 if (empty($format)) {
2097 $format = get_string('strftimedaydatetime', 'langconfig');
2100 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
2102 } else if ($fixday) {
2103 $formatnoday = str_replace('%d', 'DD', $format);
2104 $fixday = ($formatnoday != $format);
2105 $format = $formatnoday;
2108 // Note: This logic about fixing 12-hour time to remove unnecessary leading
2109 // zero is required because on Windows, PHP strftime function does not
2110 // support the correct 'hour without leading zero' parameter (%l).
2111 if (!empty($CFG->nofixhour)) {
2112 // Config.php can force %I not to be fixed.
2114 } else if ($fixhour) {
2115 $formatnohour = str_replace('%I', 'HH', $format);
2116 $fixhour = ($formatnohour != $format);
2117 $format = $formatnohour;
2120 //add daylight saving offset for string timezones only, as we can't get dst for
2121 //float values. if timezone is 99 (user default timezone), then try update dst.
2122 if ((99 == $timezone) || !is_numeric($timezone)) {
2123 $date += dst_offset_on($date, $timezone);
2126 $timezone = get_user_timezone_offset($timezone);
2128 // If we are running under Windows convert to windows encoding and then back to UTF-8
2129 // (because it's impossible to specify UTF-8 to fetch locale info in Win32)
2131 if (abs($timezone) > 13) { /// Server time
2132 $datestring = date_format_string($date, $format, $timezone);
2134 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
2135 $datestring = str_replace('DD', $daystring, $datestring);
2138 $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2139 $datestring = str_replace('HH', $hourstring, $datestring);
2143 $date += (int)($timezone * 3600);
2144 $datestring = date_format_string($date, $format, $timezone);
2146 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
2147 $datestring = str_replace('DD', $daystring, $datestring);
2150 $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2151 $datestring = str_replace('HH', $hourstring, $datestring);
2159 * Returns a formatted date ensuring it is UTF-8.
2161 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2162 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2164 * This function does not do any calculation regarding the user preferences and should
2165 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2166 * to differenciate the use of server time or not (strftime() against gmstrftime()).
2168 * @param int $date the timestamp.
2169 * @param string $format strftime format.
2170 * @param int|float $timezone the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2171 * @return string the formatted date/time.
2174 function date_format_string($date, $format, $tz = 99) {
2176 if (abs($tz) > 13) {
2177 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
2178 $format = textlib::convert($format, 'utf-8', $localewincharset);
2179 $datestring = strftime($format, $date);
2180 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2182 $datestring = strftime($format, $date);
2185 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
2186 $format = textlib::convert($format, 'utf-8', $localewincharset);
2187 $datestring = gmstrftime($format, $date);
2188 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2190 $datestring = gmstrftime($format, $date);
2197 * Given a $time timestamp in GMT (seconds since epoch),
2198 * returns an array that represents the date in user time
2203 * @param int $time Timestamp in GMT
2204 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2205 * dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
2206 * @return array An array that represents the date in user time
2208 function usergetdate($time, $timezone=99) {
2210 //save input timezone, required for dst offset check.
2211 $passedtimezone = $timezone;
2213 $timezone = get_user_timezone_offset($timezone);
2215 if (abs($timezone) > 13) { // Server time
2216 return getdate($time);
2219 //add daylight saving offset for string timezones only, as we can't get dst for
2220 //float values. if timezone is 99 (user default timezone), then try update dst.
2221 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2222 $time += dst_offset_on($time, $passedtimezone);
2225 $time += intval((float)$timezone * HOURSECS);
2227 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2229 //be careful to ensure the returned array matches that produced by getdate() above
2232 $getdate['weekday'],
2239 $getdate['minutes'],
2241 ) = explode('_', $datestring);
2243 // set correct datatype to match with getdate()
2244 $getdate['seconds'] = (int)$getdate['seconds'];
2245 $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
2246 $getdate['year'] = (int)$getdate['year'];
2247 $getdate['mon'] = (int)$getdate['mon'];
2248 $getdate['wday'] = (int)$getdate['wday'];
2249 $getdate['mday'] = (int)$getdate['mday'];
2250 $getdate['hours'] = (int)$getdate['hours'];
2251 $getdate['minutes'] = (int)$getdate['minutes'];
2256 * Given a GMT timestamp (seconds since epoch), offsets it by
2257 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2262 * @param int $date Timestamp in GMT
2263 * @param float|int|string $timezone timezone to calculate GMT time offset before
2264 * calculating user time, 99 is default user timezone
2265 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2268 function usertime($date, $timezone=99) {
2270 $timezone = get_user_timezone_offset($timezone);
2272 if (abs($timezone) > 13) {
2275 return $date - (int)($timezone * HOURSECS);
2279 * Given a time, return the GMT timestamp of the most recent midnight
2280 * for the current user.
2284 * @param int $date Timestamp in GMT
2285 * @param float|int|string $timezone timezone to calculate GMT time offset before
2286 * calculating user midnight time, 99 is default user timezone
2287 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2288 * @return int Returns a GMT timestamp
2290 function usergetmidnight($date, $timezone=99) {
2292 $userdate = usergetdate($date, $timezone);
2294 // Time of midnight of this user's day, in GMT
2295 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2300 * Returns a string that prints the user's timezone
2304 * @param float|int|string $timezone timezone to calculate GMT time offset before
2305 * calculating user timezone, 99 is default user timezone
2306 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2309 function usertimezone($timezone=99) {
2311 $tz = get_user_timezone($timezone);
2313 if (!is_float($tz)) {
2317 if(abs($tz) > 13) { // Server time
2318 return get_string('serverlocaltime');
2321 if($tz == intval($tz)) {
2322 // Don't show .0 for whole hours
2339 * Returns a float which represents the user's timezone difference from GMT in hours
2340 * Checks various settings and picks the most dominant of those which have a value
2344 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2345 * 99 is default user timezone
2346 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2349 function get_user_timezone_offset($tz = 99) {
2353 $tz = get_user_timezone($tz);
2355 if (is_float($tz)) {
2358 $tzrecord = get_timezone_record($tz);
2359 if (empty($tzrecord)) {
2362 return (float)$tzrecord->gmtoff / HOURMINS;
2367 * Returns an int which represents the systems's timezone difference from GMT in seconds
2371 * @param float|int|string $tz timezone for which offset is required.
2372 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2373 * @return int|bool if found, false is timezone 99 or error
2375 function get_timezone_offset($tz) {
2382 if (is_numeric($tz)) {
2383 return intval($tz * 60*60);
2386 if (!$tzrecord = get_timezone_record($tz)) {
2389 return intval($tzrecord->gmtoff * 60);
2393 * Returns a float or a string which denotes the user's timezone
2394 * 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)
2395 * means that for this timezone there are also DST rules to be taken into account
2396 * Checks various settings and picks the most dominant of those which have a value
2400 * @param float|int|string $tz timezone to calculate GMT time offset before
2401 * calculating user timezone, 99 is default user timezone
2402 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2403 * @return float|string
2405 function get_user_timezone($tz = 99) {
2410 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2411 isset($USER->timezone) ? $USER->timezone : 99,
2412 isset($CFG->timezone) ? $CFG->timezone : 99,
2417 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array
2418 while(((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2419 $tz = $next['value'];
2421 return is_numeric($tz) ? (float) $tz : $tz;
2425 * Returns cached timezone record for given $timezonename
2428 * @param string $timezonename name of the timezone
2429 * @return stdClass|bool timezonerecord or false
2431 function get_timezone_record($timezonename) {
2433 static $cache = NULL;
2435 if ($cache === NULL) {
2439 if (isset($cache[$timezonename])) {
2440 return $cache[$timezonename];
2443 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2444 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2448 * Build and store the users Daylight Saving Time (DST) table
2451 * @param int $from_year Start year for the table, defaults to 1971
2452 * @param int $to_year End year for the table, defaults to 2035
2453 * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
2456 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2457 global $CFG, $SESSION, $DB;
2459 $usertz = get_user_timezone($strtimezone);
2461 if (is_float($usertz)) {
2462 // Trivial timezone, no DST
2466 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2467 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2468 unset($SESSION->dst_offsets);
2469 unset($SESSION->dst_range);
2472 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2473 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2474 // This will be the return path most of the time, pretty light computationally
2478 // Reaching here means we either need to extend our table or create it from scratch
2480 // Remember which TZ we calculated these changes for
2481 $SESSION->dst_offsettz = $usertz;
2483 if(empty($SESSION->dst_offsets)) {
2484 // If we 're creating from scratch, put the two guard elements in there
2485 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2487 if(empty($SESSION->dst_range)) {
2488 // If creating from scratch
2489 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2490 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2492 // Fill in the array with the extra years we need to process
2493 $yearstoprocess = array();
2494 for($i = $from; $i <= $to; ++$i) {
2495 $yearstoprocess[] = $i;
2498 // Take note of which years we have processed for future calls
2499 $SESSION->dst_range = array($from, $to);
2502 // If needing to extend the table, do the same
2503 $yearstoprocess = array();
2505 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2506 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2508 if($from < $SESSION->dst_range[0]) {
2509 // Take note of which years we need to process and then note that we have processed them for future calls
2510 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2511 $yearstoprocess[] = $i;
2513 $SESSION->dst_range[0] = $from;
2515 if($to > $SESSION->dst_range[1]) {
2516 // Take note of which years we need to process and then note that we have processed them for future calls
2517 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2518 $yearstoprocess[] = $i;
2520 $SESSION->dst_range[1] = $to;
2524 if(empty($yearstoprocess)) {
2525 // This means that there was a call requesting a SMALLER range than we have already calculated
2529 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2530 // Also, the array is sorted in descending timestamp order!
2534 static $presets_cache = array();
2535 if (!isset($presets_cache[$usertz])) {
2536 $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');
2538 if(empty($presets_cache[$usertz])) {
2542 // Remove ending guard (first element of the array)
2543 reset($SESSION->dst_offsets);
2544 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2546 // Add all required change timestamps
2547 foreach($yearstoprocess as $y) {
2548 // Find the record which is in effect for the year $y
2549 foreach($presets_cache[$usertz] as $year => $preset) {
2555 $changes = dst_changes_for_year($y, $preset);
2557 if($changes === NULL) {
2560 if($changes['dst'] != 0) {
2561 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2563 if($changes['std'] != 0) {
2564 $SESSION->dst_offsets[$changes['std']] = 0;
2568 // Put in a guard element at the top
2569 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2570 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2573 krsort($SESSION->dst_offsets);
2579 * Calculates the required DST change and returns a Timestamp Array
2585 * @param int|string $year Int or String Year to focus on
2586 * @param object $timezone Instatiated Timezone object
2587 * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
2589 function dst_changes_for_year($year, $timezone) {
2591 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2595 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2596 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2598 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2599 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2601 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2602 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2604 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2605 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2606 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2608 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2609 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2611 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2615 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2616 * - Note: Daylight saving only works for string timezones and not for float.
2620 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2621 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2622 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2625 function dst_offset_on($time, $strtimezone = NULL) {
2628 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2632 reset($SESSION->dst_offsets);
2633 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2634 if($from <= $time) {
2639 // This is the normal return path
2640 if($offset !== NULL) {
2644 // Reaching this point means we haven't calculated far enough, do it now:
2645 // Calculate extra DST changes if needed and recurse. The recursion always
2646 // moves toward the stopping condition, so will always end.
2649 // We need a year smaller than $SESSION->dst_range[0]
2650 if($SESSION->dst_range[0] == 1971) {
2653 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2654 return dst_offset_on($time, $strtimezone);
2657 // We need a year larger than $SESSION->dst_range[1]
2658 if($SESSION->dst_range[1] == 2035) {
2661 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2662 return dst_offset_on($time, $strtimezone);
2667 * Calculates when the day appears in specific month
2671 * @param int $startday starting day of the month
2672 * @param int $weekday The day when week starts (normally taken from user preferences)
2673 * @param int $month The month whose day is sought
2674 * @param int $year The year of the month whose day is sought
2677 function find_day_in_month($startday, $weekday, $month, $year) {
2679 $daysinmonth = days_in_month($month, $year);
2681 if($weekday == -1) {
2682 // Don't care about weekday, so return:
2683 // abs($startday) if $startday != -1
2684 // $daysinmonth otherwise
2685 return ($startday == -1) ? $daysinmonth : abs($startday);
2688 // From now on we 're looking for a specific weekday
2690 // Give "end of month" its actual value, since we know it
2691 if($startday == -1) {
2692 $startday = -1 * $daysinmonth;
2695 // Starting from day $startday, the sign is the direction
2699 $startday = abs($startday);
2700 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2702 // This is the last such weekday of the month
2703 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2704 if($lastinmonth > $daysinmonth) {
2708 // Find the first such weekday <= $startday
2709 while($lastinmonth > $startday) {
2713 return $lastinmonth;
2718 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2720 $diff = $weekday - $indexweekday;
2725 // This is the first such weekday of the month equal to or after $startday
2726 $firstfromindex = $startday + $diff;
2728 return $firstfromindex;
2734 * Calculate the number of days in a given month
2738 * @param int $month The month whose day count is sought
2739 * @param int $year The year of the month whose day count is sought
2742 function days_in_month($month, $year) {
2743 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2747 * Calculate the position in the week of a specific calendar day
2751 * @param int $day The day of the date whose position in the week is sought
2752 * @param int $month The month of the date whose position in the week is sought
2753 * @param int $year The year of the date whose position in the week is sought
2756 function dayofweek($day, $month, $year) {
2757 // I wonder if this is any different from
2758 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2759 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2762 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2765 * Returns full login url.
2767 * @return string login url
2769 function get_login_url() {
2772 $url = "$CFG->wwwroot/login/index.php";
2774 if (!empty($CFG->loginhttps)) {
2775 $url = str_replace('http:', 'https:', $url);
2782 * This function checks that the current user is logged in and has the
2783 * required privileges
2785 * This function checks that the current user is logged in, and optionally
2786 * whether they are allowed to be in a particular course and view a particular
2788 * If they are not logged in, then it redirects them to the site login unless
2789 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2790 * case they are automatically logged in as guests.
2791 * If $courseid is given and the user is not enrolled in that course then the
2792 * user is redirected to the course enrolment page.
2793 * If $cm is given and the course module is hidden and the user is not a teacher
2794 * in the course then the user is redirected to the course home page.
2796 * When $cm parameter specified, this function sets page layout to 'module'.
2797 * You need to change it manually later if some other layout needed.
2799 * @package core_access
2802 * @param mixed $courseorid id of the course or course object
2803 * @param bool $autologinguest default true
2804 * @param object $cm course module object
2805 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2806 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2807 * in order to keep redirects working properly. MDL-14495
2808 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2809 * @return mixed Void, exit, and die depending on path
2811 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2812 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2814 // Must not redirect when byteserving already started.
2815 if (!empty($_SERVER['HTTP_RANGE'])) {
2816 $preventredirect = true;
2819 // setup global $COURSE, themes, language and locale
2820 if (!empty($courseorid)) {
2821 if (is_object($courseorid)) {
2822 $course = $courseorid;
2823 } else if ($courseorid == SITEID) {
2824 $course = clone($SITE);
2826 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2829 if ($cm->course != $course->id) {
2830 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2832 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2833 if (!($cm instanceof cm_info)) {
2834 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2835 // db queries so this is not really a performance concern, however it is obviously
2836 // better if you use get_fast_modinfo to get the cm before calling this.
2837 $modinfo = get_fast_modinfo($course);
2838 $cm = $modinfo->get_cm($cm->id);
2840 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2841 $PAGE->set_pagelayout('incourse');
2843 $PAGE->set_course($course); // set's up global $COURSE
2846 // do not touch global $COURSE via $PAGE->set_course(),
2847 // the reasons is we need to be able to call require_login() at any time!!
2850 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2854 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2855 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2856 // risk leading the user back to the AJAX request URL.
2857 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2858 $setwantsurltome = false;
2861 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2862 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2863 if ($setwantsurltome) {
2864 $SESSION->wantsurl = qualified_me();
2866 redirect(get_login_url());
2869 // If the user is not even logged in yet then make sure they are
2870 if (!isloggedin()) {
2871 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2872 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2873 // misconfigured site guest, just redirect to login page
2874 redirect(get_login_url());
2875 exit; // never reached
2877 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2878 complete_user_login($guest);
2879 $USER->autologinguest = true;
2880 $SESSION->lang = $lang;
2882 //NOTE: $USER->site check was obsoleted by session test cookie,
2883 // $USER->confirmed test is in login/index.php
2884 if ($preventredirect) {
2885 throw new require_login_exception('You are not logged in');
2888 if ($setwantsurltome) {
2889 $SESSION->wantsurl = qualified_me();
2891 if (!empty($_SERVER['HTTP_REFERER'])) {
2892 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2894 redirect(get_login_url());
2895 exit; // never reached
2899 // loginas as redirection if needed
2900 if ($course->id != SITEID and session_is_loggedinas()) {
2901 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2902 if ($USER->loginascontext->instanceid != $course->id) {
2903 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2908 // check whether the user should be changing password (but only if it is REALLY them)
2909 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2910 $userauth = get_auth_plugin($USER->auth);
2911 if ($userauth->can_change_password() and !$preventredirect) {
2912 if ($setwantsurltome) {
2913 $SESSION->wantsurl = qualified_me();
2915 if ($changeurl = $userauth->change_password_url()) {
2916 //use plugin custom url
2917 redirect($changeurl);
2919 //use moodle internal method
2920 if (empty($CFG->loginhttps)) {
2921 redirect($CFG->wwwroot .'/login/change_password.php');
2923 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2924 redirect($wwwroot .'/login/change_password.php');
2928 print_error('nopasswordchangeforced', 'auth');
2932 // Check that the user account is properly set up
2933 if (user_not_fully_set_up($USER)) {
2934 if ($preventredirect) {
2935 throw new require_login_exception('User not fully set-up');
2937 if ($setwantsurltome) {
2938 $SESSION->wantsurl = qualified_me();
2940 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2943 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2946 // Do not bother admins with any formalities
2947 if (is_siteadmin()) {
2948 //set accesstime or the user will appear offline which messes up messaging
2949 user_accesstime_log($course->id);
2953 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2954 if (!$USER->policyagreed and !is_siteadmin()) {
2955 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2956 if ($preventredirect) {
2957 throw new require_login_exception('Policy not agreed');
2959 if ($setwantsurltome) {
2960 $SESSION->wantsurl = qualified_me();
2962 redirect($CFG->wwwroot .'/user/policy.php');
2963 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2964 if ($preventredirect) {
2965 throw new require_login_exception('Policy not agreed');
2967 if ($setwantsurltome) {
2968 $SESSION->wantsurl = qualified_me();
2970 redirect($CFG->wwwroot .'/user/policy.php');
2974 // Fetch the system context, the course context, and prefetch its child contexts
2975 $sysctx = context_system::instance();
2976 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2978 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2983 // If the site is currently under maintenance, then print a message
2984 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2985 if ($preventredirect) {
2986 throw new require_login_exception('Maintenance in progress');
2989 print_maintenance_message();
2992 // make sure the course itself is not hidden
2993 if ($course->id == SITEID) {
2994 // frontpage can not be hidden
2996 if (is_role_switched($course->id)) {
2997 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2999 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3000 // originally there was also test of parent category visibility,
3001 // BUT is was very slow in complex queries involving "my courses"
3002 // now it is also possible to simply hide all courses user is not enrolled in :-)
3003 if ($preventredirect) {
3004 throw new require_login_exception('Course is hidden');
3006 // We need to override the navigation URL as the course won't have
3007 // been added to the navigation and thus the navigation will mess up
3008 // when trying to find it.
3009 navigation_node::override_active_url(new moodle_url('/'));
3010 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3015 // is the user enrolled?
3016 if ($course->id == SITEID) {
3017 // everybody is enrolled on the frontpage
3020 if (session_is_loggedinas()) {
3021 // Make sure the REAL person can access this course first
3022 $realuser = session_get_realuser();
3023 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3024 if ($preventredirect) {
3025 throw new require_login_exception('Invalid course login-as access');
3027 echo $OUTPUT->header();
3028 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3034 if (is_role_switched($course->id)) {
3035 // ok, user had to be inside this course before the switch
3038 } else if (is_viewing($coursecontext, $USER)) {
3039 // ok, no need to mess with enrol
3043 if (isset($USER->enrol['enrolled'][$course->id])) {
3044 if ($USER->enrol['enrolled'][$course->id] > time()) {
3046 if (isset($USER->enrol['tempguest'][$course->id])) {
3047 unset($USER->enrol['tempguest'][$course->id]);
3048 remove_temp_course_roles($coursecontext);
3052 unset($USER->enrol['enrolled'][$course->id]);
3055 if (isset($USER->enrol['tempguest'][$course->id])) {
3056 if ($USER->enrol['tempguest'][$course->id] == 0) {
3058 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3062 unset($USER->enrol['tempguest'][$course->id]);
3063 remove_temp_course_roles($coursecontext);
3070 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3071 if ($until !== false) {
3072 // active participants may always access, a timestamp in the future, 0 (always) or false.
3074 $until = ENROL_MAX_TIMESTAMP;
3076 $USER->enrol['enrolled'][$course->id] = $until;
3080 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
3081 $enrols = enrol_get_plugins(true);
3082 // first ask all enabled enrol instances in course if they want to auto enrol user
3083 foreach($instances as $instance) {
3084 if (!isset($enrols[$instance->enrol])) {
3087 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3088 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3089 if ($until !== false) {
3091 $until = ENROL_MAX_TIMESTAMP;
3093 $USER->enrol['enrolled'][$course->id] = $until;
3098 // if not enrolled yet try to gain temporary guest access
3100 foreach($instances as $instance) {
3101 if (!isset($enrols[$instance->enrol])) {
3104 // Get a duration for the guest access, a timestamp in the future or false.
3105 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3106 if ($until !== false and $until > time()) {
3107 $USER->enrol['tempguest'][$course->id] = $until;
3118 if ($preventredirect) {
3119 throw new require_login_exception('Not enrolled');
3121 if ($setwantsurltome) {
3122 $SESSION->wantsurl = qualified_me();
3124 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3128 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
3129 // conditional availability, etc
3130 if ($cm && !$cm->uservisible) {
3131 if ($preventredirect) {
3132 throw new require_login_exception('Activity is hidden');
3134 if ($course->id != SITEID) {
3135 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
3137 $url = new moodle_url('/');
3139 redirect($url, get_string('activityiscurrentlyhidden'));
3142 // Finally access granted, update lastaccess times
3143 user_accesstime_log($course->id);
3148 * This function just makes sure a user is logged out.
3150 * @package core_access
3152 function require_logout() {
3158 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
3160 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
3161 foreach($authsequence as $authname) {
3162 $authplugin = get_auth_plugin($authname);
3163 $authplugin->prelogout_hook();
3167 events_trigger('user_logout', $params);
3168 session_get_instance()->terminate_current();
3173 * Weaker version of require_login()
3175 * This is a weaker version of {@link require_login()} which only requires login
3176 * when called from within a course rather than the site page, unless
3177 * the forcelogin option is turned on.
3178 * @see require_login()
3180 * @package core_access
3183 * @param mixed $courseorid The course object or id in question
3184 * @param bool $autologinguest Allow autologin guests if that is wanted
3185 * @param object $cm Course activity module if known
3186 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3187 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3188 * in order to keep redirects working properly. MDL-14495
3189 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3192 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
3193 global $CFG, $PAGE, $SITE;
3194 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3195 or (!is_object($courseorid) and $courseorid == SITEID);
3196 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3197 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
3198 // db queries so this is not really a performance concern, however it is obviously
3199 // better if you use get_fast_modinfo to get the cm before calling this.
3200 if (is_object($courseorid)) {
3201 $course = $courseorid;
3203 $course = clone($SITE);
3205 $modinfo = get_fast_modinfo($course);
3206 $cm = $modinfo->get_cm($cm->id);
3208 if (!empty($CFG->forcelogin)) {
3209 // login required for both SITE and courses
3210 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3212 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3213 // always login for hidden activities
3214 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3216 } else if ($issite) {
3217 //login for SITE not required
3218 if ($cm and empty($cm->visible)) {
3219 // hidden activities are not accessible without login
3220 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3221 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3222 // not-logged-in users do not have any group membership
3223 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3225 // We still need to instatiate PAGE vars properly so that things
3226 // that rely on it like navigation function correctly.
3227 if (!empty($courseorid)) {
3228 if (is_object($courseorid)) {
3229 $course = $courseorid;
3231 $course = clone($SITE);
3234 if ($cm->course != $course->id) {
3235 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3237 $PAGE->set_cm($cm, $course);
3238 $PAGE->set_pagelayout('incourse');
3240 $PAGE->set_course($course);
3243 // If $PAGE->course, and hence $PAGE->context, have not already been set
3244 // up properly, set them up now.
3245 $PAGE->set_course($PAGE->course);
3247 //TODO: verify conditional activities here
3248 user_accesstime_log(SITEID);
3253 // course login always required
3254 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3259 * Require key login. Function terminates with error if key not found or incorrect.
3265 * @uses NO_MOODLE_COOKIES
3266 * @uses PARAM_ALPHANUM
3267 * @param string $script unique script identifier
3268 * @param int $instance optional instance id
3269 * @return int Instance ID
3271 function require_user_key_login($script, $instance=null) {
3272 global $USER, $SESSION, $CFG, $DB;
3274 if (!NO_MOODLE_COOKIES) {
3275 print_error('sessioncookiesdisable');
3279 @session_write_close();
3281 $keyvalue = required_param('key', PARAM_ALPHANUM);
3283 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3284 print_error('invalidkey');
3287 if (!empty($key->validuntil) and $key->validuntil < time()) {
3288 print_error('expiredkey');
3291 if ($key->iprestriction) {
3292 $remoteaddr = getremoteaddr(null);
3293 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3294 print_error('ipmismatch');
3298 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
3299 print_error('invaliduserid');
3302 /// emulate normal session
3303 enrol_check_plugins($user);
3304 session_set_user($user);
3306 /// note we are not using normal login
3307 if (!defined('USER_KEY_LOGIN')) {
3308 define('USER_KEY_LOGIN', true);
3311 /// return instance id - it might be empty
3312 return $key->instance;
3316 * Creates a new private user access key.
3319 * @param string $script unique target identifier
3320 * @param int $userid
3321 * @param int $instance optional instance id
3322 * @param string $iprestriction optional ip restricted access
3323 * @param timestamp $validuntil key valid only until given data
3324 * @return string access key value
3326 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3329 $key = new stdClass();
3330 $key->script = $script;
3331 $key->userid = $userid;
3332 $key->instance = $instance;
3333 $key->iprestriction = $iprestriction;
3334 $key->validuntil = $validuntil;
3335 $key->timecreated = time();
3337 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
3338 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3340 $key->value = md5($userid.'_'.time().random_string(40));
3342 $DB->insert_record('user_private_key', $key);
3347 * Delete the user's new private user access keys for a particular script.
3350 * @param string $script unique target identifier
3351 * @param int $userid
3354 function delete_user_key($script,$userid) {
3356 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3360 * Gets a private user access key (and creates one if one doesn't exist).
3363 * @param string $script unique target identifier
3364 * @param int $userid
3365 * @param int $instance optional instance id
3366 * @param string $iprestriction optional ip restricted access
3367 * @param timestamp $validuntil key valid only until given data
3368 * @return string access key value
3370 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3373 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3374 'instance'=>$instance, 'iprestriction'=>$iprestriction,
3375 'validuntil'=>$validuntil))) {
3378 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3384 * Modify the user table by setting the currently logged in user's
3385 * last login to now.
3389 * @return bool Always returns true
3391 function update_user_login_times() {
3394 if (isguestuser()) {
3395 // Do not update guest access times/ips for performance.
3401 $user = new stdClass();
3402 $user->id = $USER->id;
3404 // Make sure all users that logged in have some firstaccess.
3405 if ($USER->firstaccess == 0) {
3406 $USER->firstaccess = $user->firstaccess = $now;
3409 // Store the previous current as lastlogin.
3410 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3412 $USER->currentlogin = $user->currentlogin = $now;
3414 // Function user_accesstime_log() may not update immediately, better do it here.
3415 $USER->lastaccess = $user->lastaccess = $now;
3416 $USER->lastip = $user->lastip = getremoteaddr();
3418 $DB->update_record('user', $user);
3423 * Determines if a user has completed setting up their account.
3425 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3428 function user_not_fully_set_up($user) {
3429 if (isguestuser($user)) {
3432 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3436 * Check whether the user has exceeded the bounce threshold
3440 * @param user $user A {@link $USER} object
3441 * @return bool true=>User has exceeded bounce threshold
3443 function over_bounce_threshold($user) {
3446 if (empty($CFG->handlebounces)) {
3450 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3454 // set sensible defaults
3455 if (empty($CFG->minbounces)) {
3456 $CFG->minbounces = 10;
3458 if (empty($CFG->bounceratio)) {
3459 $CFG->bounceratio = .20;
3463 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3464 $bouncecount = $bounce->value;
3466 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3467 $sendcount = $send->value;
3469 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3473 * Used to increment or reset email sent count
3476 * @param user $user object containing an id
3477 * @param bool $reset will reset the count to 0
3480 function set_send_count($user,$reset=false) {
3483 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3487 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3488 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3489 $DB->update_record('user_preferences', $pref);
3491 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3493 $pref = new stdClass();
3494 $pref->name = 'email_send_count';
3496 $pref->userid = $user->id;
3497 $DB->insert_record('user_preferences', $pref, false);
3502 * Increment or reset user's email bounce count
3505 * @param user $user object containing an id
3506 * @param bool $reset will reset the count to 0
3508 function set_bounce_count($user,$reset=false) {
3511 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3512 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3513 $DB->update_record('user_preferences', $pref);
3515 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3517 $pref = new stdClass();
3518 $pref->name = 'email_bounce_count';
3520 $pref->userid = $user->id;
3521 $DB->insert_record('user_preferences', $pref, false);
3526 * Determines if the currently logged in user is in editing mode.
3527 * Note: originally this function had $userid parameter - it was not usable anyway
3529 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3530 * @todo Deprecated function remove when ready
3533 * @uses DEBUG_DEVELOPER
3536 function isediting() {
3538 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3539 return $PAGE->user_is_editing();
3543 * Determines if the logged in user is currently moving an activity
3546 * @param int $courseid The id of the course being tested
3549 function ismoving($courseid) {
3552 if (!empty($USER->activitycopy)) {
3553 return ($USER->activitycopycourse == $courseid);
3559 * Returns a persons full name
3561 * Given an object containing all of the users name
3562 * values, this function returns a string with the
3563 * full name of the person.
3564 * The result may depend on system settings
3565 * or language. 'override' will force both names
3566 * to be used even if system settings specify one.
3570 * @param object $user A {@link $USER} object to get full name of.
3571 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3574 function fullname($user, $override=false) {
3575 global $CFG, $SESSION;
3577 if (!isset($user->firstname) and !isset($user->lastname)) {
3582 if (!empty($CFG->forcefirstname)) {
3583 $user->firstname = $CFG->forcefirstname;
3585 if (!empty($CFG->forcelastname)) {
3586 $user->lastname = $CFG->forcelastname;
3590 if (!empty($SESSION->fullnamedisplay)) {
3591 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3595 // If the fullnamedisplay setting is available, set the template to that.
3596 if (isset($CFG->fullnamedisplay)) {
3597 $template = $CFG->fullnamedisplay;
3599 // If the template is empty, or set to language, or $override is set, return the language string.
3600 if (empty($template) || $template == 'language' || $override) {
3601 return get_string('fullnamedisplay', null, $user);
3604 // Get all of the name fields.
3605 $allnames = get_all_user_name_fields();
3606 $requirednames = array();
3607 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3608 foreach ($allnames as $allname) {
3609 if (strpos($template, $allname) !== false) {
3610 $requirednames[] = $allname;
3611 // If the field is in the template, but not set in the user object, then notify the programmer that it needs to be fixed.
3612 if (!array_key_exists($allname, $user)) {
3613 debugging('You need to update your sql query to include additional name fields in the user object.', DEBUG_DEVELOPER);
3618 $displayname = $template;
3619 // Switch in the actual data into the template.
3620 foreach ($requirednames as $altname) {
3621 if (isset($user->$altname)) {
3622 // Using empty() on the below if statement causes breakages.
3623 if ((string)$user->$altname == '') {
3624 $displayname = str_replace($altname, 'EMPTY', $displayname);
3626 $displayname = str_replace($altname, $user->$altname, $displayname);
3629 $displayname = str_replace($altname, 'EMPTY', $displayname);
3632 // Tidy up any misc. characters (Not perfect, but gets most characters).
3633 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or katakana and parenthesis.
3634 $patterns = array();
3635 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been filled in by a user.
3636 // The special characters are Japanese brackets that are common enough to make special allowance for them (not covered by :punct:).
3637 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3638 // This regular expression is to remove any double spaces in the display name.
3639 $patterns[] = '/\s{2,}/';
3640 foreach ($patterns as $pattern) {
3641 $displayname = preg_replace($pattern, ' ', $displayname);
3644 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3645 $displayname = trim($displayname);
3646 if (empty($displayname)) {
3647 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3648 // people in general feel is a good setting to fall back on.
3649 $displayname = $user->firstname;
3651 return $displayname;
3655 * A centralised location for the all name fields. Returns an array / sql string snippet.
3657 * @param bool $returnsql True for an sql select field snippet.
3658 * @param string $alias table alias to use in front of each field.
3659 * @return array|string All name fields.
3661 function get_all_user_name_fields($returnsql = false, $alias = null) {
3662 $alternatenames = array('firstnamephonetic',
3670 foreach ($alternatenames as $key => $altname) {
3671 $alternatenames[$key] = "$alias.$altname";
3674 $alternatenames = implode(',', $alternatenames);
3676 return $alternatenames;
3680 * Returns an array of values in order of occurance in a provided string.
3681 * The key in the result is the character postion in the string.
3683 * @param array $values Values to be found in the string format
3684 * @param string $stringformat The string which may contain values being searched for.
3685 * @return array An array of values in order according to placement in the string format.
3687 function order_in_string($values, $stringformat) {
3688 $valuearray = array();
3689 foreach ($values as $value) {
3690 $pattern = "/$value\b/";
3691 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3692 if (preg_match($pattern, $stringformat)) {
3693 $replacement = "thing";
3694 // replace the value with something more unique to ensure we get the right position when using strpos().
3695 $newformat = preg_replace($pattern, $replacement, $stringformat);
3696 $position = strpos($newformat, $replacement);
3697 $valuearray[$position] = $value;
3705 * Checks if current user is shown any extra fields when listing users.
3706 * @param object $context Context
3707 * @param array $already Array of fields that we're going to show anyway
3708 * so don't bother listing them
3709 * @return array Array of field names from user table, not including anything
3710 * listed in $already
3712 function get_extra_user_fields($context, $already = array()) {
3715 // Only users with permission get the extra fields
3716 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3720 // Split showuseridentity on comma
3721 if (empty($CFG->showuseridentity)) {
3722 // Explode gives wrong result with empty string
3725 $extra = explode(',', $CFG->showuseridentity);
3728 foreach ($extra as $key => $field) {
3729 if (in_array($field, $already)) {
3730 unset($extra[$key]);
3735 // For consistency, if entries are removed from array, renumber it
3736 // so they are numbered as you would expect
3737 $extra = array_merge($extra);
3743 * If the current user is to be shown extra user fields when listing or
3744 * selecting users, returns a string suitable for including in an SQL select
3745 * clause to retrieve those fields.
3746 * @param object $context Context
3747 * @param string $alias Alias of user table, e.g. 'u' (default none)
3748 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3749 * @param array $already Array of fields that we're going to include anyway
3750 * so don't list them (default none)
3751 * @return string Partial SQL select clause, beginning with comma, for example
3752 * ',u.idnumber,u.department' unless it is blank
3754 function get_extra_user_fields_sql($context, $alias='', $prefix='',
3755 $already = array()) {
3756 $fields = get_extra_user_fields($context, $already);
3758 // Add punctuation for alias
3759 if ($alias !== '') {
3762 foreach ($fields as $field) {
3763 $result .= ', ' . $alias . $field;
3765 $result .= ' AS ' . $prefix . $field;
3772 * Returns the display name of a field in the user table. Works for most fields
3773 * that are commonly displayed to users.
3774 * @param string $field Field name, e.g. 'phone1'
3775 * @return string Text description taken from language file, e.g. 'Phone number'
3777 function get_user_field_name($field) {
3778 // Some fields have language strings which are not the same as field name
3780 case 'phone1' : return get_string('phone');
3781 case 'url' : return get_string('webpage');
3782 case 'icq' : return get_string('icqnumber');
3783 case 'skype' : return get_string('skypeid');
3784 case 'aim' : return get_string('aimid');
3785 case 'yahoo' : return get_string('yahooid');
3786 case 'msn' : return get_string('msnid');
3788 // Otherwise just use the same lang string
3789 return get_string($field);
3793 * Returns whether a given authentication plugin exists.
3796 * @param string $auth Form of authentication to check for. Defaults to the
3797 * global setting in {@link $CFG}.
3798 * @return boolean Whether the plugin is available.
3800 function exists_auth_plugin($auth) {
3803 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3804 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3810 * Checks if a given plugin is in the list of enabled authentication plugins.
3812 * @param string $auth Authentication plugin.
3813 * @return boolean Whether the plugin is enabled.
3815 function is_enabled_auth($auth) {
3820 $enabled = get_enabled_auth_plugins();
3822 return in_array($auth, $enabled);
3826 * Returns an authentication plugin instance.
3829 * @param string $auth name of authentication plugin
3830 * @return auth_plugin_base An instance of the required authentication plugin.
3832 function get_auth_plugin($auth) {
3835 // check the plugin exists first
3836 if (! exists_auth_plugin($auth)) {
3837 print_error('authpluginnotfound', 'debug', '', $auth);
3840 // return auth plugin instance
3841 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3842 $class = "auth_plugin_$auth";
3847 * Returns array of active auth plugins.
3849 * @param bool $fix fix $CFG->auth if needed
3852 function get_enabled_auth_plugins($fix=false) {
3855 $default = array('manual', 'nologin');
3857 if (empty($CFG->auth)) {
3860 $auths = explode(',', $CFG->auth);
3864 $auths = array_unique($auths);
3865 foreach($auths as $k=>$authname) {
3866 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3870 $newconfig = implode(',', $auths);
3871 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3872 set_config('auth', $newconfig);
3876 return (array_merge($default, $auths));
3880 * Returns true if an internal authentication method is being used.
3881 * if method not specified then, global default is assumed
3883 * @param string $auth Form of authentication required
3886 function is_internal_auth($auth) {
3887 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3888 return $authplugin->is_internal();
3892 * Returns true if the user is a 'restored' one
3894 * Used in the login process to inform the user
3895 * and allow him/her to reset the password
3899 * @param string $username username to be checked
3902 function is_restored_user($username) {
3905 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3909 * Returns an array of user fields
3911 * @return array User field/column names
3913 function get_user_fieldnames() {
3916 $fieldarray = $DB->get_columns('user');
3917 unset($fieldarray['id']);
3918 $fieldarray = array_keys($fieldarray);
3924 * Creates a bare-bones user record
3926 * @todo Outline auth types and provide code example
3928 * @param string $username New user's username to add to record
3929 * @param string $password New user's password to add to record
3930 * @param string $auth Form of authentication required
3931 * @return stdClass A complete user object
3933 function create_user_record($username, $password, $auth = 'manual') {
3935 require_once($CFG->dirroot."/user/profile/lib.php");
3936 //just in case check text case
3937 $username = trim(textlib::strtolower($username));
3939 $authplugin = get_auth_plugin($auth);
3940 $customfields = $authplugin->get_custom_user_profile_fields();
3941 $newuser = new stdClass();
3942 if ($newinfo = $authplugin->get_userinfo($username)) {
3943 $newinfo = truncate_userinfo($newinfo);
3944 foreach ($newinfo as $key => $value){
3945 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3946 $newuser->$key = $value;
3951 if (!empty($newuser->email)) {
3952 if (email_is_not_allowed($newuser->email)) {
3953 unset($newuser->email);
3957 if (!isset($newuser->city)) {
3958 $newuser->city = '';
3961 $newuser->auth = $auth;
3962 $newuser->username = $username;
3965 // user CFG lang for user if $newuser->lang is empty
3966 // or $user->lang is not an installed language
3967 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3968 $newuser->lang = $CFG->lang;
3970 $newuser->confirmed = 1;
3971 $newuser->lastip = getremoteaddr();
3972 $newuser->timecreated = time();
3973 $newuser->timemodified = $newuser->timecreated;
3974 $newuser->mnethostid = $CFG->mnet_localhost_id;
3976 $newuser->id = $DB->insert_record('user', $newuser);
3978 // Save user profile data.
3979 profile_save_data($newuser);
3981 $user = get_complete_user_data('id', $newuser->id);
3982 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3983 set_user_preference('auth_forcepasswordchange', 1, $user);
3985 // Set the password.
3986 update_internal_user_password($user, $password);
3988 // fetch full user record for the event, the complete user data contains too much info
3989 // and we want to be consistent with other places that trigger this event
3990 events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
3996 * Will update a local user record from an external source.
3997 * (MNET users can not be updated using this method!)
3999 * @param string $username user's username to update the record
4000 * @return stdClass A complete user object
4002 function update_user_record($username) {
4004 require_once($CFG->dirroot."/user/profile/lib.php");
4005 $username = trim(textlib::strtolower($username)); /// just in case check text case
4007 $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
4009 $userauth = get_auth_plugin($oldinfo->auth);
4011 if ($newinfo = $userauth->get_userinfo($username)) {
4012 $newinfo = truncate_userinfo($newinfo);
4013 $customfields = $userauth->get_custom_user_profile_fields();
4015 foreach ($newinfo as $key => $value){
4016 $key = strtolower($key);
4017 $iscustom = in_array($key, $customfields);
4018 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4019 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4020 // unknown or must not be changed
4023 $confval = $userauth->config->{'field_updatelocal_' . $key};
4024 $lockval = $userauth->config->{'field_lock_' . $key};
4025 if (empty($confval) || empty($lockval)) {
4028 if ($confval === 'onlogin') {
4029 // MDL-4207 Don't overwrite modified user profile values with
4030 // empty LDAP values when 'unlocked if empty' is set. The purpose
4031 // of the setting 'unlocked if empty' is to allow the user to fill
4032 // in a value for the selected field _if LDAP is giving
4033 // nothing_ for this field. Thus it makes sense to let this value
4034 // stand in until LDAP is giving a value for this field.
4035 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4036 if ($iscustom || (in_array($key, $userauth->userfields) &&
4037 ((string)$oldinfo->$key !== (string)$value))) {
4038 $newuser[$key] = (string)$value;
4044 $newuser['id'] = $oldinfo->id;
4045 $newuser['timemodified'] = time();
4046 $DB->update_record('user', $newuser);
4048 // Save user profile data.
4049 profile_save_data((object) $newuser);
4051 // fetch full user record for the event, the complete user data contains too much info
4052 // and we want to be consistent with other places that trigger this event
4053 events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id)));
4057 return get_complete_user_data('id', $oldinfo->id);
4061 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
4062 * which may have large fields
4064 * @todo Add vartype handling to ensure $info is an array
4066 * @param array $info Array of user properties to truncate if needed
4067 * @return array The now truncated information that was passed in
4069 function truncate_userinfo($info) {
4070 // define the limits
4080 'institution' => 40,
4088 // apply where needed
4089 foreach (array_keys($info) as $key) {
4090 if (!empty($limit[$key])) {
4091 $info[$key] = trim(textlib::substr($info[$key],0, $limit[$key]));
4099 * Marks user deleted in internal user database and notifies the auth plugin.
4100 * Also unenrols user from all roles and does other cleanup.
4102 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4104 * @param stdClass $user full user object before delete
4105 * @return boolean success
4106 * @throws coding_exception if invalid $user parameter detected
4108 function delete_user(stdClass $user) {
4110 require_once($CFG->libdir.'/grouplib.php');
4111 require_once($CFG->libdir.'/gradelib.php');
4112 require_once($CFG->dirroot.'/message/lib.php');
4113 require_once($CFG->dirroot.'/tag/lib.php');
4115 // Make sure nobody sends bogus record type as parameter.
4116 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4117 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4120 // Better not trust the parameter and fetch the latest info,
4121 // this will be very expensive anyway.
4122 if (!$user = $DB->get_record('user', array('id'=>$user->id))) {
4123 debugging('Attempt to delete unknown user account.');
4127 // There must be always exactly one guest record,
4128 // originally the guest account was identified by username only,
4129 // now we use $CFG->siteguest for performance reasons.
4130 if ($user->username === 'guest' or isguestuser($user)) {
4131 debugging('Guest user account can not be deleted.');
4135 // Admin can be theoretically from different auth plugin,
4136 // but we want to prevent deletion of internal accoutns only,
4137 // if anything goes wrong ppl may force somebody to be admin via
4138 // config.php setting $CFG->siteadmins.
4139 if ($user->auth === 'manual' and is_siteadmin($user)) {
4140 debugging('Local administrator accounts can not be deleted.');
4144 // delete all grades - backup is kept in grade_grades_history table
4145 grade_user_delete($user->id);
4147 //move unread messages from this user to read
4148 message_move_userfrom_unread2read($user->id);
4150 // TODO: remove from cohorts using standard API here
4153 tag_set('user', $user->id, array());
4155 // unconditionally unenrol from all courses
4156 enrol_user_delete($user);
4158 // unenrol from all roles in all contexts
4159 role_unassign_all(array('userid'=>$user->id)); // this might be slow but it is really needed - modules might do some extra cleanup!
4161 //now do a brute force cleanup
4163 // remove from all cohorts
4164 $DB->delete_records('cohort_members', array('userid'=>$user->id));
4166 // remove from all groups
4167 $DB->delete_records('groups_members', array('userid'=>$user->id));
4169 // brute force unenrol from all courses
4170 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
4172 // purge user preferences
4173 $DB->delete_records('user_preferences', array('userid'=>$user->id));
4175 // purge user extra profile info
4176 $DB->delete_records('user_info_data', array('userid'=>$user->id));
4178 // last course access not necessary either
4179 $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
4181 // remove all user tokens
4182 $DB->delete_records('external_tokens', array('userid'=>$user->id));
4184 // unauthorise the user for all services
4185 $DB->delete_records('external_services_users', array('userid'=>$user->id));
4187 // Remove users private keys.
4188 $DB->delete_records('user_private_key', array('userid' => $user->id));
4190 // force logout - may fail if file based sessions used, sorry
4191 session_kill_user($user->id);
4193 // now do a final accesslib cleanup - removes all role assignments in user context and context itself
4194 delete_context(CONTEXT_USER, $user->id);
4196 // workaround for bulk deletes of users with the same email address
4197 $delname = "$user->email.".time();
4198 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
4202 // mark internal user record as "deleted"
4203 $updateuser = new stdClass();
4204 $updateuser->id = $user->id;
4205 $updateuser->deleted = 1;
4206 $updateuser->username = $delname; // Remember it just in case
4207 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
4208 $updateuser->idnumber = ''; // Clear this field to free it up
4209 $updateuser->picture = 0;
4210 $updateuser->timemodified = time();
4212 $DB->update_record('user', $updateuser);
4213 // Add this action to log
4214 add_to_log(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
4217 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4218 // should know about this updated property persisted to the user's table.
4219 $user->timemodified = $updateuser->timemodified;
4221 // notify auth plugin - do not block the delete even when plugin fails
4222 $authplugin = get_auth_plugin($user->auth);
4223 $authplugin->user_delete($user);
4225 // any plugin that needs to cleanup should register this event
4226 events_trigger('user_deleted', $user);
4232 * Retrieve the guest user object
4236 * @return user A {@link $USER} object
4238 function guest_user() {
4241 if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
4242 $newuser->confirmed = 1;
4243 $newuser->lang = $CFG->lang;
4244 $newuser->lastip = getremoteaddr();
4251 * Authenticates a user against the chosen authentication mechanism
4253 * Given a username and password, this function looks them
4254 * up using the currently selected authentication mechanism,
4255 * and if the authentication is successful, it returns a
4256 * valid $user object from the 'user' table.
4258 * Uses auth_ functions from the currently active auth module
4260 * After authenticate_user_login() returns success, you will need to
4261 * log that the user has logged in, and call complete_user_login() to set
4264 * Note: this function works only with non-mnet accounts!
4266 * @param string $username User's username
4267 * @param string $password User's password
4268 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4269 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4270 * @return stdClass|false A {@link $USER} object or false if error
4272 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4274 require_once("$CFG->libdir/authlib.php");
4276 $authsenabled = get_enabled_auth_plugins();
4278 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4279 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
4280 if (!empty($user->suspended)) {
4281 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4282 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4283 $failurereason = AUTH_LOGIN_SUSPENDED;
4286 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4287 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4288 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4289 $failurereason = AUTH_LOGIN_SUSPENDED; // Legacy way to suspend user.
4292 $auths = array($auth);
4295 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4296 if ($DB->get_field('user', 'id', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>1))) {
4297 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4298 $failurereason = AUTH_LOGIN_NOUSER;
4302 // Do not try to authenticate non-existent accounts when user creation is not disabled.
4303 if (!empty($CFG->authpreventaccountcreation)) {
4304 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4305 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".$_SERVER['HTTP_USER_AGENT']);
4306 $failurereason = AUTH_LOGIN_NOUSER;
4310 // User does not exist
4311 $auths = $authsenabled;
4312 $user = new stdClass();
4316 if ($ignorelockout) {
4317 // Some other mechanism protects against brute force password guessing,
4318 // for example login form might include reCAPTCHA or this function
4319 // is called from a SSO script.
4321 } else if ($user->id) {
4322 // Verify login lockout after other ways that may prevent user login.