a0fae10295d4e412566139d07e7af540e5bdc287
[moodle.git] / lib / moodlelib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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.
13 //
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/>.
17 /**
18  * moodlelib.php - Moodle main library
19  *
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
24  *
25  * @package    core
26  * @subpackage lib
27  * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
28  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29  */
31 defined('MOODLE_INTERNAL') || die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
36 /**
37  * Time constant - the number of seconds in a year
38  */
39 define('YEARSECS', 31536000);
41 /**
42  * Time constant - the number of seconds in a week
43  */
44 define('WEEKSECS', 604800);
46 /**
47  * Time constant - the number of seconds in a day
48  */
49 define('DAYSECS', 86400);
51 /**
52  * Time constant - the number of seconds in an hour
53  */
54 define('HOURSECS', 3600);
56 /**
57  * Time constant - the number of seconds in a minute
58  */
59 define('MINSECS', 60);
61 /**
62  * Time constant - the number of minutes in a day
63  */
64 define('DAYMINS', 1440);
66 /**
67  * Time constant - the number of minutes in an hour
68  */
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.
74 /**
75  * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
76  */
77 define('PARAM_ALPHA',    'alpha');
79 /**
80  * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81  * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
82  */
83 define('PARAM_ALPHAEXT', 'alphaext');
85 /**
86  * PARAM_ALPHANUM - expected numbers and letters only.
87  */
88 define('PARAM_ALPHANUM', 'alphanum');
90 /**
91  * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
92  */
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
95 /**
96  * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
97  */
98 define('PARAM_AUTH',  'auth');
100 /**
101  * PARAM_BASE64 - Base 64 encoded format
102  */
103 define('PARAM_BASE64',   'base64');
105 /**
106  * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
107  */
108 define('PARAM_BOOL',     'bool');
110 /**
111  * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112  * checked against the list of capabilities in the database.
113  */
114 define('PARAM_CAPABILITY',   'capability');
116 /**
117  * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118  * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119  * the input (required/optional_param or formslib) and then sanitse the HTML
120  * using format_text on output. This is for the rare cases when you want to
121  * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
122  */
123 define('PARAM_CLEANHTML', 'cleanhtml');
125 /**
126  * PARAM_EMAIL - an email address following the RFC
127  */
128 define('PARAM_EMAIL',   'email');
130 /**
131  * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
132  */
133 define('PARAM_FILE',   'file');
135 /**
136  * PARAM_FLOAT - a real/floating point number.
137  *
138  * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139  * It does not work for languages that use , as a decimal separator.
140  * Instead, do something like
141  *     $rawvalue = required_param('name', PARAM_RAW);
142  *     // ... other code including require_login, which sets current lang ...
143  *     $realvalue = unformat_float($rawvalue);
144  *     // ... then use $realvalue
145  */
146 define('PARAM_FLOAT',  'float');
148 /**
149  * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
150  */
151 define('PARAM_HOST',     'host');
153 /**
154  * PARAM_INT - integers only, use when expecting only numbers.
155  */
156 define('PARAM_INT',      'int');
158 /**
159  * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
160  */
161 define('PARAM_LANG',  'lang');
163 /**
164  * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165  * others! Implies PARAM_URL!)
166  */
167 define('PARAM_LOCALURL', 'localurl');
169 /**
170  * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
171  */
172 define('PARAM_NOTAGS',   'notags');
174 /**
175  * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176  * traversals note: the leading slash is not removed, window drive letter is not allowed
177  */
178 define('PARAM_PATH',     'path');
180 /**
181  * PARAM_PEM - Privacy Enhanced Mail format
182  */
183 define('PARAM_PEM',      'pem');
185 /**
186  * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
187  */
188 define('PARAM_PERMISSION',   'permission');
190 /**
191  * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
192  */
193 define('PARAM_RAW', 'raw');
195 /**
196  * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
197  */
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
200 /**
201  * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
202  */
203 define('PARAM_SAFEDIR',  'safedir');
205 /**
206  * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
207  */
208 define('PARAM_SAFEPATH',  'safepath');
210 /**
211  * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9.  Numbers and comma only.
212  */
213 define('PARAM_SEQUENCE',  'sequence');
215 /**
216  * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
217  */
218 define('PARAM_TAG',   'tag');
220 /**
221  * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
222  */
223 define('PARAM_TAGLIST',   'taglist');
225 /**
226  * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
227  */
228 define('PARAM_TEXT',  'text');
230 /**
231  * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
232  */
233 define('PARAM_THEME',  'theme');
235 /**
236  * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237  * http://localhost.localdomain/ is ok.
238  */
239 define('PARAM_URL',      'url');
241 /**
242  * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243  * accounts, do NOT use when syncing with external systems!!
244  */
245 define('PARAM_USERNAME',    'username');
247 /**
248  * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
249  */
250 define('PARAM_STRINGID',    'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
253 /**
254  * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255  * It was one of the first types, that is why it is abused so much ;-)
256  * @deprecated since 2.0
257  */
258 define('PARAM_CLEAN',    'clean');
260 /**
261  * PARAM_INTEGER - deprecated alias for PARAM_INT
262  * @deprecated since 2.0
263  */
264 define('PARAM_INTEGER',  'int');
266 /**
267  * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268  * @deprecated since 2.0
269  */
270 define('PARAM_NUMBER',  'float');
272 /**
273  * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274  * NOTE: originally alias for PARAM_APLHA
275  * @deprecated since 2.0
276  */
277 define('PARAM_ACTION',   'alphanumext');
279 /**
280  * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281  * NOTE: originally alias for PARAM_APLHA
282  * @deprecated since 2.0
283  */
284 define('PARAM_FORMAT',   'alphanumext');
286 /**
287  * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288  * @deprecated since 2.0
289  */
290 define('PARAM_MULTILANG',  'text');
292 /**
293  * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294  * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295  * America/Port-au-Prince)
296  */
297 define('PARAM_TIMEZONE', 'timezone');
299 /**
300  * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
301  */
302 define('PARAM_CLEANFILE', 'file');
304 /**
305  * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306  * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308  * NOTE: numbers and underscores are strongly discouraged in plugin names!
309  */
310 define('PARAM_COMPONENT', 'component');
312 /**
313  * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314  * It is usually used together with context id and component.
315  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
316  */
317 define('PARAM_AREA', 'area');
319 /**
320  * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
321  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322  * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
323  */
324 define('PARAM_PLUGIN', 'plugin');
327 // Web Services.
329 /**
330  * VALUE_REQUIRED - if the parameter is not supplied, there is an error
331  */
332 define('VALUE_REQUIRED', 1);
334 /**
335  * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
336  */
337 define('VALUE_OPTIONAL', 2);
339 /**
340  * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
341  */
342 define('VALUE_DEFAULT', 0);
344 /**
345  * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
346  */
347 define('NULL_NOT_ALLOWED', false);
349 /**
350  * NULL_ALLOWED - the parameter can be set to null in the database
351  */
352 define('NULL_ALLOWED', true);
354 // Page types.
356 /**
357  * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
358  */
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
374 // Tag constants.
375 /**
376  * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377  * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378  * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
379  *
380  * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
381  */
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True if module supports outcomes */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
417 /** True if module supports groupmembersonly */
418 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
420 /** Type of module */
421 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
422 /** True if module supports intro editor */
423 define('FEATURE_MOD_INTRO', 'mod_intro');
424 /** True if module has default completion */
425 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
427 define('FEATURE_COMMENT', 'comment');
429 define('FEATURE_RATE', 'rate');
430 /** True if module supports backup/restore of moodle2 format */
431 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
433 /** True if module can show description on course main page */
434 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
436 /** Unspecified module archetype */
437 define('MOD_ARCHETYPE_OTHER', 0);
438 /** Resource-like type module */
439 define('MOD_ARCHETYPE_RESOURCE', 1);
440 /** Assignment module archetype */
441 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
442 /** System (not user-addable) module archetype */
443 define('MOD_ARCHETYPE_SYSTEM', 3);
445 /**
446  * Security token used for allowing access
447  * from external application such as web services.
448  * Scripts do not use any session, performance is relatively
449  * low because we need to load access info in each request.
450  * Scripts are executed in parallel.
451  */
452 define('EXTERNAL_TOKEN_PERMANENT', 0);
454 /**
455  * Security token used for allowing access
456  * of embedded applications, the code is executed in the
457  * active user session. Token is invalidated after user logs out.
458  * Scripts are executed serially - normal session locking is used.
459  */
460 define('EXTERNAL_TOKEN_EMBEDDED', 1);
462 /**
463  * The home page should be the site home
464  */
465 define('HOMEPAGE_SITE', 0);
466 /**
467  * The home page should be the users my page
468  */
469 define('HOMEPAGE_MY', 1);
470 /**
471  * The home page can be chosen by the user
472  */
473 define('HOMEPAGE_USER', 2);
475 /**
476  * Hub directory url (should be moodle.org)
477  */
478 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
481 /**
482  * Moodle.org url (should be moodle.org)
483  */
484 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
486 /**
487  * Moodle mobile app service name
488  */
489 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
491 /**
492  * Indicates the user has the capabilities required to ignore activity and course file size restrictions
493  */
494 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
496 /**
497  * Course display settings: display all sections on one page.
498  */
499 define('COURSE_DISPLAY_SINGLEPAGE', 0);
500 /**
501  * Course display settings: split pages into a page per section.
502  */
503 define('COURSE_DISPLAY_MULTIPAGE', 1);
505 /**
506  * Authentication constant: String used in password field when password is not stored.
507  */
508 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
510 // PARAMETER HANDLING.
512 /**
513  * Returns a particular value for the named variable, taken from
514  * POST or GET.  If the parameter doesn't exist then an error is
515  * thrown because we require this variable.
516  *
517  * This function should be used to initialise all required values
518  * in a script that are based on parameters.  Usually it will be
519  * used like this:
520  *    $id = required_param('id', PARAM_INT);
521  *
522  * Please note the $type parameter is now required and the value can not be array.
523  *
524  * @param string $parname the name of the page parameter we want
525  * @param string $type expected type of parameter
526  * @return mixed
527  * @throws coding_exception
528  */
529 function required_param($parname, $type) {
530     if (func_num_args() != 2 or empty($parname) or empty($type)) {
531         throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
532     }
533     // POST has precedence.
534     if (isset($_POST[$parname])) {
535         $param = $_POST[$parname];
536     } else if (isset($_GET[$parname])) {
537         $param = $_GET[$parname];
538     } else {
539         print_error('missingparam', '', '', $parname);
540     }
542     if (is_array($param)) {
543         debugging('Invalid array parameter detected in required_param(): '.$parname);
544         // TODO: switch to fatal error in Moodle 2.3.
545         return required_param_array($parname, $type);
546     }
548     return clean_param($param, $type);
551 /**
552  * Returns a particular array value for the named variable, taken from
553  * POST or GET.  If the parameter doesn't exist then an error is
554  * thrown because we require this variable.
555  *
556  * This function should be used to initialise all required values
557  * in a script that are based on parameters.  Usually it will be
558  * used like this:
559  *    $ids = required_param_array('ids', PARAM_INT);
560  *
561  *  Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
562  *
563  * @param string $parname the name of the page parameter we want
564  * @param string $type expected type of parameter
565  * @return array
566  * @throws coding_exception
567  */
568 function required_param_array($parname, $type) {
569     if (func_num_args() != 2 or empty($parname) or empty($type)) {
570         throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
571     }
572     // POST has precedence.
573     if (isset($_POST[$parname])) {
574         $param = $_POST[$parname];
575     } else if (isset($_GET[$parname])) {
576         $param = $_GET[$parname];
577     } else {
578         print_error('missingparam', '', '', $parname);
579     }
580     if (!is_array($param)) {
581         print_error('missingparam', '', '', $parname);
582     }
584     $result = array();
585     foreach ($param as $key => $value) {
586         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
587             debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
588             continue;
589         }
590         $result[$key] = clean_param($value, $type);
591     }
593     return $result;
596 /**
597  * Returns a particular value for the named variable, taken from
598  * POST or GET, otherwise returning a given default.
599  *
600  * This function should be used to initialise all optional values
601  * in a script that are based on parameters.  Usually it will be
602  * used like this:
603  *    $name = optional_param('name', 'Fred', PARAM_TEXT);
604  *
605  * Please note the $type parameter is now required and the value can not be array.
606  *
607  * @param string $parname the name of the page parameter we want
608  * @param mixed  $default the default value to return if nothing is found
609  * @param string $type expected type of parameter
610  * @return mixed
611  * @throws coding_exception
612  */
613 function optional_param($parname, $default, $type) {
614     if (func_num_args() != 3 or empty($parname) or empty($type)) {
615         throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
616     }
617     if (!isset($default)) {
618         $default = null;
619     }
621     // POST has precedence.
622     if (isset($_POST[$parname])) {
623         $param = $_POST[$parname];
624     } else if (isset($_GET[$parname])) {
625         $param = $_GET[$parname];
626     } else {
627         return $default;
628     }
630     if (is_array($param)) {
631         debugging('Invalid array parameter detected in required_param(): '.$parname);
632         // TODO: switch to $default in Moodle 2.3.
633         return optional_param_array($parname, $default, $type);
634     }
636     return clean_param($param, $type);
639 /**
640  * Returns a particular array value for the named variable, taken from
641  * POST or GET, otherwise returning a given default.
642  *
643  * This function should be used to initialise all optional values
644  * in a script that are based on parameters.  Usually it will be
645  * used like this:
646  *    $ids = optional_param('id', array(), PARAM_INT);
647  *
648  * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
649  *
650  * @param string $parname the name of the page parameter we want
651  * @param mixed $default the default value to return if nothing is found
652  * @param string $type expected type of parameter
653  * @return array
654  * @throws coding_exception
655  */
656 function optional_param_array($parname, $default, $type) {
657     if (func_num_args() != 3 or empty($parname) or empty($type)) {
658         throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
659     }
661     // POST has precedence.
662     if (isset($_POST[$parname])) {
663         $param = $_POST[$parname];
664     } else if (isset($_GET[$parname])) {
665         $param = $_GET[$parname];
666     } else {
667         return $default;
668     }
669     if (!is_array($param)) {
670         debugging('optional_param_array() expects array parameters only: '.$parname);
671         return $default;
672     }
674     $result = array();
675     foreach ($param as $key => $value) {
676         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
677             debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
678             continue;
679         }
680         $result[$key] = clean_param($value, $type);
681     }
683     return $result;
686 /**
687  * Strict validation of parameter values, the values are only converted
688  * to requested PHP type. Internally it is using clean_param, the values
689  * before and after cleaning must be equal - otherwise
690  * an invalid_parameter_exception is thrown.
691  * Objects and classes are not accepted.
692  *
693  * @param mixed $param
694  * @param string $type PARAM_ constant
695  * @param bool $allownull are nulls valid value?
696  * @param string $debuginfo optional debug information
697  * @return mixed the $param value converted to PHP type
698  * @throws invalid_parameter_exception if $param is not of given type
699  */
700 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
701     if (is_null($param)) {
702         if ($allownull == NULL_ALLOWED) {
703             return null;
704         } else {
705             throw new invalid_parameter_exception($debuginfo);
706         }
707     }
708     if (is_array($param) or is_object($param)) {
709         throw new invalid_parameter_exception($debuginfo);
710     }
712     $cleaned = clean_param($param, $type);
714     if ($type == PARAM_FLOAT) {
715         // Do not detect precision loss here.
716         if (is_float($param) or is_int($param)) {
717             // These always fit.
718         } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
719             throw new invalid_parameter_exception($debuginfo);
720         }
721     } else if ((string)$param !== (string)$cleaned) {
722         // Conversion to string is usually lossless.
723         throw new invalid_parameter_exception($debuginfo);
724     }
726     return $cleaned;
729 /**
730  * Makes sure array contains only the allowed types, this function does not validate array key names!
731  *
732  * <code>
733  * $options = clean_param($options, PARAM_INT);
734  * </code>
735  *
736  * @param array $param the variable array we are cleaning
737  * @param string $type expected format of param after cleaning.
738  * @param bool $recursive clean recursive arrays
739  * @return array
740  * @throws coding_exception
741  */
742 function clean_param_array(array $param = null, $type, $recursive = false) {
743     // Convert null to empty array.
744     $param = (array)$param;
745     foreach ($param as $key => $value) {
746         if (is_array($value)) {
747             if ($recursive) {
748                 $param[$key] = clean_param_array($value, $type, true);
749             } else {
750                 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
751             }
752         } else {
753             $param[$key] = clean_param($value, $type);
754         }
755     }
756     return $param;
759 /**
760  * Used by {@link optional_param()} and {@link required_param()} to
761  * clean the variables and/or cast to specific types, based on
762  * an options field.
763  * <code>
764  * $course->format = clean_param($course->format, PARAM_ALPHA);
765  * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
766  * </code>
767  *
768  * @param mixed $param the variable we are cleaning
769  * @param string $type expected format of param after cleaning.
770  * @return mixed
771  * @throws coding_exception
772  */
773 function clean_param($param, $type) {
774     global $CFG;
776     if (is_array($param)) {
777         throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
778     } else if (is_object($param)) {
779         if (method_exists($param, '__toString')) {
780             $param = $param->__toString();
781         } else {
782             throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
783         }
784     }
786     switch ($type) {
787         case PARAM_RAW:
788             // No cleaning at all.
789             $param = fix_utf8($param);
790             return $param;
792         case PARAM_RAW_TRIMMED:
793             // No cleaning, but strip leading and trailing whitespace.
794             $param = fix_utf8($param);
795             return trim($param);
797         case PARAM_CLEAN:
798             // General HTML cleaning, try to use more specific type if possible this is deprecated!
799             // Please use more specific type instead.
800             if (is_numeric($param)) {
801                 return $param;
802             }
803             $param = fix_utf8($param);
804             // Sweep for scripts, etc.
805             return clean_text($param);
807         case PARAM_CLEANHTML:
808             // Clean html fragment.
809             $param = fix_utf8($param);
810             // Sweep for scripts, etc.
811             $param = clean_text($param, FORMAT_HTML);
812             return trim($param);
814         case PARAM_INT:
815             // Convert to integer.
816             return (int)$param;
818         case PARAM_FLOAT:
819             // Convert to float.
820             return (float)$param;
822         case PARAM_ALPHA:
823             // Remove everything not `a-z`.
824             return preg_replace('/[^a-zA-Z]/i', '', $param);
826         case PARAM_ALPHAEXT:
827             // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
828             return preg_replace('/[^a-zA-Z_-]/i', '', $param);
830         case PARAM_ALPHANUM:
831             // Remove everything not `a-zA-Z0-9`.
832             return preg_replace('/[^A-Za-z0-9]/i', '', $param);
834         case PARAM_ALPHANUMEXT:
835             // Remove everything not `a-zA-Z0-9_-`.
836             return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
838         case PARAM_SEQUENCE:
839             // Remove everything not `0-9,`.
840             return preg_replace('/[^0-9,]/i', '', $param);
842         case PARAM_BOOL:
843             // Convert to 1 or 0.
844             $tempstr = strtolower($param);
845             if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
846                 $param = 1;
847             } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
848                 $param = 0;
849             } else {
850                 $param = empty($param) ? 0 : 1;
851             }
852             return $param;
854         case PARAM_NOTAGS:
855             // Strip all tags.
856             $param = fix_utf8($param);
857             return strip_tags($param);
859         case PARAM_TEXT:
860             // Leave only tags needed for multilang.
861             $param = fix_utf8($param);
862             // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
863             // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
864             do {
865                 if (strpos($param, '</lang>') !== false) {
866                     // Old and future mutilang syntax.
867                     $param = strip_tags($param, '<lang>');
868                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
869                         break;
870                     }
871                     $open = false;
872                     foreach ($matches[0] as $match) {
873                         if ($match === '</lang>') {
874                             if ($open) {
875                                 $open = false;
876                                 continue;
877                             } else {
878                                 break 2;
879                             }
880                         }
881                         if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
882                             break 2;
883                         } else {
884                             $open = true;
885                         }
886                     }
887                     if ($open) {
888                         break;
889                     }
890                     return $param;
892                 } else if (strpos($param, '</span>') !== false) {
893                     // Current problematic multilang syntax.
894                     $param = strip_tags($param, '<span>');
895                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
896                         break;
897                     }
898                     $open = false;
899                     foreach ($matches[0] as $match) {
900                         if ($match === '</span>') {
901                             if ($open) {
902                                 $open = false;
903                                 continue;
904                             } else {
905                                 break 2;
906                             }
907                         }
908                         if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
909                             break 2;
910                         } else {
911                             $open = true;
912                         }
913                     }
914                     if ($open) {
915                         break;
916                     }
917                     return $param;
918                 }
919             } while (false);
920             // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
921             return strip_tags($param);
923         case PARAM_COMPONENT:
924             // We do not want any guessing here, either the name is correct or not
925             // please note only normalised component names are accepted.
926             if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
927                 return '';
928             }
929             if (strpos($param, '__') !== false) {
930                 return '';
931             }
932             if (strpos($param, 'mod_') === 0) {
933                 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
934                 if (substr_count($param, '_') != 1) {
935                     return '';
936                 }
937             }
938             return $param;
940         case PARAM_PLUGIN:
941         case PARAM_AREA:
942             // We do not want any guessing here, either the name is correct or not.
943             if (!is_valid_plugin_name($param)) {
944                 return '';
945             }
946             return $param;
948         case PARAM_SAFEDIR:
949             // Remove everything not a-zA-Z0-9_- .
950             return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
952         case PARAM_SAFEPATH:
953             // Remove everything not a-zA-Z0-9/_- .
954             return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
956         case PARAM_FILE:
957             // Strip all suspicious characters from filename.
958             $param = fix_utf8($param);
959             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
960             if ($param === '.' || $param === '..') {
961                 $param = '';
962             }
963             return $param;
965         case PARAM_PATH:
966             // Strip all suspicious characters from file path.
967             $param = fix_utf8($param);
968             $param = str_replace('\\', '/', $param);
970             // Explode the path and clean each element using the PARAM_FILE rules.
971             $breadcrumb = explode('/', $param);
972             foreach ($breadcrumb as $key => $crumb) {
973                 if ($crumb === '.' && $key === 0) {
974                     // Special condition to allow for relative current path such as ./currentdirfile.txt.
975                 } else {
976                     $crumb = clean_param($crumb, PARAM_FILE);
977                 }
978                 $breadcrumb[$key] = $crumb;
979             }
980             $param = implode('/', $breadcrumb);
982             // Remove multiple current path (./././) and multiple slashes (///).
983             $param = preg_replace('~//+~', '/', $param);
984             $param = preg_replace('~/(\./)+~', '/', $param);
985             return $param;
987         case PARAM_HOST:
988             // Allow FQDN or IPv4 dotted quad.
989             $param = preg_replace('/[^\.\d\w-]/', '', $param );
990             // Match ipv4 dotted quad.
991             if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
992                 // Confirm values are ok.
993                 if ( $match[0] > 255
994                      || $match[1] > 255
995                      || $match[3] > 255
996                      || $match[4] > 255 ) {
997                     // Hmmm, what kind of dotted quad is this?
998                     $param = '';
999                 }
1000             } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1001                        && !preg_match('/^[\.-]/',  $param) // No leading dots/hyphens.
1002                        && !preg_match('/[\.-]$/',  $param) // No trailing dots/hyphens.
1003                        ) {
1004                 // All is ok - $param is respected.
1005             } else {
1006                 // All is not ok...
1007                 $param='';
1008             }
1009             return $param;
1011         case PARAM_URL:          // Allow safe ftp, http, mailto urls.
1012             $param = fix_utf8($param);
1013             include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1014             if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1015                 // All is ok, param is respected.
1016             } else {
1017                 // Not really ok.
1018                 $param ='';
1019             }
1020             return $param;
1022         case PARAM_LOCALURL:
1023             // Allow http absolute, root relative and relative URLs within wwwroot.
1024             $param = clean_param($param, PARAM_URL);
1025             if (!empty($param)) {
1026                 if (preg_match(':^/:', $param)) {
1027                     // Root-relative, ok!
1028                 } else if (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i', $param)) {
1029                     // Absolute, and matches our wwwroot.
1030                 } else {
1031                     // Relative - let's make sure there are no tricks.
1032                     if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1033                         // Looks ok.
1034                     } else {
1035                         $param = '';
1036                     }
1037                 }
1038             }
1039             return $param;
1041         case PARAM_PEM:
1042             $param = trim($param);
1043             // PEM formatted strings may contain letters/numbers and the symbols:
1044             //   forward slash: /
1045             //   plus sign:     +
1046             //   equal sign:    =
1047             //   , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1048             if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1049                 list($wholething, $body) = $matches;
1050                 unset($wholething, $matches);
1051                 $b64 = clean_param($body, PARAM_BASE64);
1052                 if (!empty($b64)) {
1053                     return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1054                 } else {
1055                     return '';
1056                 }
1057             }
1058             return '';
1060         case PARAM_BASE64:
1061             if (!empty($param)) {
1062                 // PEM formatted strings may contain letters/numbers and the symbols
1063                 //   forward slash: /
1064                 //   plus sign:     +
1065                 //   equal sign:    =.
1066                 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1067                     return '';
1068                 }
1069                 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1070                 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1071                 // than (or equal to) 64 characters long.
1072                 for ($i=0, $j=count($lines); $i < $j; $i++) {
1073                     if ($i + 1 == $j) {
1074                         if (64 < strlen($lines[$i])) {
1075                             return '';
1076                         }
1077                         continue;
1078                     }
1080                     if (64 != strlen($lines[$i])) {
1081                         return '';
1082                     }
1083                 }
1084                 return implode("\n", $lines);
1085             } else {
1086                 return '';
1087             }
1089         case PARAM_TAG:
1090             $param = fix_utf8($param);
1091             // Please note it is not safe to use the tag name directly anywhere,
1092             // it must be processed with s(), urlencode() before embedding anywhere.
1093             // Remove some nasties.
1094             $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1095             // Convert many whitespace chars into one.
1096             $param = preg_replace('/\s+/', ' ', $param);
1097             $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1098             return $param;
1100         case PARAM_TAGLIST:
1101             $param = fix_utf8($param);
1102             $tags = explode(',', $param);
1103             $result = array();
1104             foreach ($tags as $tag) {
1105                 $res = clean_param($tag, PARAM_TAG);
1106                 if ($res !== '') {
1107                     $result[] = $res;
1108                 }
1109             }
1110             if ($result) {
1111                 return implode(',', $result);
1112             } else {
1113                 return '';
1114             }
1116         case PARAM_CAPABILITY:
1117             if (get_capability_info($param)) {
1118                 return $param;
1119             } else {
1120                 return '';
1121             }
1123         case PARAM_PERMISSION:
1124             $param = (int)$param;
1125             if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1126                 return $param;
1127             } else {
1128                 return CAP_INHERIT;
1129             }
1131         case PARAM_AUTH:
1132             $param = clean_param($param, PARAM_PLUGIN);
1133             if (empty($param)) {
1134                 return '';
1135             } else if (exists_auth_plugin($param)) {
1136                 return $param;
1137             } else {
1138                 return '';
1139             }
1141         case PARAM_LANG:
1142             $param = clean_param($param, PARAM_SAFEDIR);
1143             if (get_string_manager()->translation_exists($param)) {
1144                 return $param;
1145             } else {
1146                 // Specified language is not installed or param malformed.
1147                 return '';
1148             }
1150         case PARAM_THEME:
1151             $param = clean_param($param, PARAM_PLUGIN);
1152             if (empty($param)) {
1153                 return '';
1154             } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1155                 return $param;
1156             } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1157                 return $param;
1158             } else {
1159                 // Specified theme is not installed.
1160                 return '';
1161             }
1163         case PARAM_USERNAME:
1164             $param = fix_utf8($param);
1165             $param = str_replace(" " , "", $param);
1166             // Convert uppercase to lowercase MDL-16919.
1167             $param = core_text::strtolower($param);
1168             if (empty($CFG->extendedusernamechars)) {
1169                 // Regular expression, eliminate all chars EXCEPT:
1170                 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1171                 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1172             }
1173             return $param;
1175         case PARAM_EMAIL:
1176             $param = fix_utf8($param);
1177             if (validate_email($param)) {
1178                 return $param;
1179             } else {
1180                 return '';
1181             }
1183         case PARAM_STRINGID:
1184             if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1185                 return $param;
1186             } else {
1187                 return '';
1188             }
1190         case PARAM_TIMEZONE:
1191             // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1192             $param = fix_utf8($param);
1193             $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1194             if (preg_match($timezonepattern, $param)) {
1195                 return $param;
1196             } else {
1197                 return '';
1198             }
1200         default:
1201             // Doh! throw error, switched parameters in optional_param or another serious problem.
1202             print_error("unknownparamtype", '', '', $type);
1203     }
1206 /**
1207  * Makes sure the data is using valid utf8, invalid characters are discarded.
1208  *
1209  * Note: this function is not intended for full objects with methods and private properties.
1210  *
1211  * @param mixed $value
1212  * @return mixed with proper utf-8 encoding
1213  */
1214 function fix_utf8($value) {
1215     if (is_null($value) or $value === '') {
1216         return $value;
1218     } else if (is_string($value)) {
1219         if ((string)(int)$value === $value) {
1220             // Shortcut.
1221             return $value;
1222         }
1223         // No null bytes expected in our data, so let's remove it.
1224         $value = str_replace("\0", '', $value);
1226         // Lower error reporting because glibc throws bogus notices.
1227         $olderror = error_reporting();
1228         if ($olderror & E_NOTICE) {
1229             error_reporting($olderror ^ E_NOTICE);
1230         }
1232         // Note: this duplicates min_fix_utf8() intentionally.
1233         static $buggyiconv = null;
1234         if ($buggyiconv === null) {
1235             $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1236         }
1238         if ($buggyiconv) {
1239             if (function_exists('mb_convert_encoding')) {
1240                 $subst = mb_substitute_character();
1241                 mb_substitute_character('');
1242                 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1243                 mb_substitute_character($subst);
1245             } else {
1246                 // Warn admins on admin/index.php page.
1247                 $result = $value;
1248             }
1250         } else {
1251             $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1252         }
1254         if ($olderror & E_NOTICE) {
1255             error_reporting($olderror);
1256         }
1258         return $result;
1260     } else if (is_array($value)) {
1261         foreach ($value as $k => $v) {
1262             $value[$k] = fix_utf8($v);
1263         }
1264         return $value;
1266     } else if (is_object($value)) {
1267         // Do not modify original.
1268         $value = clone($value);
1269         foreach ($value as $k => $v) {
1270             $value->$k = fix_utf8($v);
1271         }
1272         return $value;
1274     } else {
1275         // This is some other type, no utf-8 here.
1276         return $value;
1277     }
1280 /**
1281  * Return true if given value is integer or string with integer value
1282  *
1283  * @param mixed $value String or Int
1284  * @return bool true if number, false if not
1285  */
1286 function is_number($value) {
1287     if (is_int($value)) {
1288         return true;
1289     } else if (is_string($value)) {
1290         return ((string)(int)$value) === $value;
1291     } else {
1292         return false;
1293     }
1296 /**
1297  * Returns host part from url.
1298  *
1299  * @param string $url full url
1300  * @return string host, null if not found
1301  */
1302 function get_host_from_url($url) {
1303     preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1304     if ($matches) {
1305         return $matches[1];
1306     }
1307     return null;
1310 /**
1311  * Tests whether anything was returned by text editor
1312  *
1313  * This function is useful for testing whether something you got back from
1314  * the HTML editor actually contains anything. Sometimes the HTML editor
1315  * appear to be empty, but actually you get back a <br> tag or something.
1316  *
1317  * @param string $string a string containing HTML.
1318  * @return boolean does the string contain any actual content - that is text,
1319  * images, objects, etc.
1320  */
1321 function html_is_blank($string) {
1322     return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1325 /**
1326  * Set a key in global configuration
1327  *
1328  * Set a key/value pair in both this session's {@link $CFG} global variable
1329  * and in the 'config' database table for future sessions.
1330  *
1331  * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1332  * In that case it doesn't affect $CFG.
1333  *
1334  * A NULL value will delete the entry.
1335  *
1336  * @param string $name the key to set
1337  * @param string $value the value to set (without magic quotes)
1338  * @param string $plugin (optional) the plugin scope, default null
1339  * @return bool true or exception
1340  */
1341 function set_config($name, $value, $plugin=null) {
1342     global $CFG, $DB;
1344     if (empty($plugin)) {
1345         if (!array_key_exists($name, $CFG->config_php_settings)) {
1346             // So it's defined for this invocation at least.
1347             if (is_null($value)) {
1348                 unset($CFG->$name);
1349             } else {
1350                 // Settings from db are always strings.
1351                 $CFG->$name = (string)$value;
1352             }
1353         }
1355         if ($DB->get_field('config', 'name', array('name' => $name))) {
1356             if ($value === null) {
1357                 $DB->delete_records('config', array('name' => $name));
1358             } else {
1359                 $DB->set_field('config', 'value', $value, array('name' => $name));
1360             }
1361         } else {
1362             if ($value !== null) {
1363                 $config = new stdClass();
1364                 $config->name  = $name;
1365                 $config->value = $value;
1366                 $DB->insert_record('config', $config, false);
1367             }
1368         }
1369         if ($name === 'siteidentifier') {
1370             cache_helper::update_site_identifier($value);
1371         }
1372         cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1373     } else {
1374         // Plugin scope.
1375         if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1376             if ($value===null) {
1377                 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1378             } else {
1379                 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1380             }
1381         } else {
1382             if ($value !== null) {
1383                 $config = new stdClass();
1384                 $config->plugin = $plugin;
1385                 $config->name   = $name;
1386                 $config->value  = $value;
1387                 $DB->insert_record('config_plugins', $config, false);
1388             }
1389         }
1390         cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1391     }
1393     return true;
1396 /**
1397  * Get configuration values from the global config table
1398  * or the config_plugins table.
1399  *
1400  * If called with one parameter, it will load all the config
1401  * variables for one plugin, and return them as an object.
1402  *
1403  * If called with 2 parameters it will return a string single
1404  * value or false if the value is not found.
1405  *
1406  * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1407  *     that we need only fetch it once per request.
1408  * @param string $plugin full component name
1409  * @param string $name default null
1410  * @return mixed hash-like object or single value, return false no config found
1411  * @throws dml_exception
1412  */
1413 function get_config($plugin, $name = null) {
1414     global $CFG, $DB;
1416     static $siteidentifier = null;
1418     if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1419         $forced =& $CFG->config_php_settings;
1420         $iscore = true;
1421         $plugin = 'core';
1422     } else {
1423         if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1424             $forced =& $CFG->forced_plugin_settings[$plugin];
1425         } else {
1426             $forced = array();
1427         }
1428         $iscore = false;
1429     }
1431     if ($siteidentifier === null) {
1432         try {
1433             // This may fail during installation.
1434             // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1435             // install the database.
1436             $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1437         } catch (dml_exception $ex) {
1438             // Set siteidentifier to false. We don't want to trip this continually.
1439             $siteidentifier = false;
1440             throw $ex;
1441         }
1442     }
1444     if (!empty($name)) {
1445         if (array_key_exists($name, $forced)) {
1446             return (string)$forced[$name];
1447         } else if ($name === 'siteidentifier' && $plugin == 'core') {
1448             return $siteidentifier;
1449         }
1450     }
1452     $cache = cache::make('core', 'config');
1453     $result = $cache->get($plugin);
1454     if ($result === false) {
1455         // The user is after a recordset.
1456         if (!$iscore) {
1457             $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1458         } else {
1459             // This part is not really used any more, but anyway...
1460             $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1461         }
1462         $cache->set($plugin, $result);
1463     }
1465     if (!empty($name)) {
1466         if (array_key_exists($name, $result)) {
1467             return $result[$name];
1468         }
1469         return false;
1470     }
1472     if ($plugin === 'core') {
1473         $result['siteidentifier'] = $siteidentifier;
1474     }
1476     foreach ($forced as $key => $value) {
1477         if (is_null($value) or is_array($value) or is_object($value)) {
1478             // We do not want any extra mess here, just real settings that could be saved in db.
1479             unset($result[$key]);
1480         } else {
1481             // Convert to string as if it went through the DB.
1482             $result[$key] = (string)$value;
1483         }
1484     }
1486     return (object)$result;
1489 /**
1490  * Removes a key from global configuration.
1491  *
1492  * @param string $name the key to set
1493  * @param string $plugin (optional) the plugin scope
1494  * @return boolean whether the operation succeeded.
1495  */
1496 function unset_config($name, $plugin=null) {
1497     global $CFG, $DB;
1499     if (empty($plugin)) {
1500         unset($CFG->$name);
1501         $DB->delete_records('config', array('name' => $name));
1502         cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1503     } else {
1504         $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1505         cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1506     }
1508     return true;
1511 /**
1512  * Remove all the config variables for a given plugin.
1513  *
1514  * NOTE: this function is called from lib/db/upgrade.php
1515  *
1516  * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1517  * @return boolean whether the operation succeeded.
1518  */
1519 function unset_all_config_for_plugin($plugin) {
1520     global $DB;
1521     // Delete from the obvious config_plugins first.
1522     $DB->delete_records('config_plugins', array('plugin' => $plugin));
1523     // Next delete any suspect settings from config.
1524     $like = $DB->sql_like('name', '?', true, true, false, '|');
1525     $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1526     $DB->delete_records_select('config', $like, $params);
1527     // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1528     cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1530     return true;
1533 /**
1534  * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1535  *
1536  * All users are verified if they still have the necessary capability.
1537  *
1538  * @param string $value the value of the config setting.
1539  * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1540  * @param bool $includeadmins include administrators.
1541  * @return array of user objects.
1542  */
1543 function get_users_from_config($value, $capability, $includeadmins = true) {
1544     if (empty($value) or $value === '$@NONE@$') {
1545         return array();
1546     }
1548     // We have to make sure that users still have the necessary capability,
1549     // it should be faster to fetch them all first and then test if they are present
1550     // instead of validating them one-by-one.
1551     $users = get_users_by_capability(context_system::instance(), $capability);
1552     if ($includeadmins) {
1553         $admins = get_admins();
1554         foreach ($admins as $admin) {
1555             $users[$admin->id] = $admin;
1556         }
1557     }
1559     if ($value === '$@ALL@$') {
1560         return $users;
1561     }
1563     $result = array(); // Result in correct order.
1564     $allowed = explode(',', $value);
1565     foreach ($allowed as $uid) {
1566         if (isset($users[$uid])) {
1567             $user = $users[$uid];
1568             $result[$user->id] = $user;
1569         }
1570     }
1572     return $result;
1576 /**
1577  * Invalidates browser caches and cached data in temp.
1578  *
1579  * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1580  * {@link phpunit_util::reset_dataroot()}
1581  *
1582  * @return void
1583  */
1584 function purge_all_caches() {
1585     global $CFG;
1587     reset_text_filters_cache();
1588     js_reset_all_caches();
1589     theme_reset_all_caches();
1590     get_string_manager()->reset_caches();
1591     core_text::reset_caches();
1593     cache_helper::purge_all();
1595     // Purge all other caches: rss, simplepie, etc.
1596     remove_dir($CFG->cachedir.'', true);
1598     // Make sure cache dir is writable, throws exception if not.
1599     make_cache_directory('');
1601     // This is the only place where we purge local caches, we are only adding files there.
1602     // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1603     remove_dir($CFG->localcachedir, true);
1604     set_config('localcachedirpurged', time());
1605     make_localcache_directory('', true);
1608 /**
1609  * Get volatile flags
1610  *
1611  * @param string $type
1612  * @param int $changedsince default null
1613  * @return array records array
1614  */
1615 function get_cache_flags($type, $changedsince = null) {
1616     global $DB;
1618     $params = array('type' => $type, 'expiry' => time());
1619     $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1620     if ($changedsince !== null) {
1621         $params['changedsince'] = $changedsince;
1622         $sqlwhere .= " AND timemodified > :changedsince";
1623     }
1624     $cf = array();
1625     if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1626         foreach ($flags as $flag) {
1627             $cf[$flag->name] = $flag->value;
1628         }
1629     }
1630     return $cf;
1633 /**
1634  * Get volatile flags
1635  *
1636  * @param string $type
1637  * @param string $name
1638  * @param int $changedsince default null
1639  * @return string|false The cache flag value or false
1640  */
1641 function get_cache_flag($type, $name, $changedsince=null) {
1642     global $DB;
1644     $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1646     $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1647     if ($changedsince !== null) {
1648         $params['changedsince'] = $changedsince;
1649         $sqlwhere .= " AND timemodified > :changedsince";
1650     }
1652     return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1655 /**
1656  * Set a volatile flag
1657  *
1658  * @param string $type the "type" namespace for the key
1659  * @param string $name the key to set
1660  * @param string $value the value to set (without magic quotes) - null will remove the flag
1661  * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1662  * @return bool Always returns true
1663  */
1664 function set_cache_flag($type, $name, $value, $expiry = null) {
1665     global $DB;
1667     $timemodified = time();
1668     if ($expiry === null || $expiry < $timemodified) {
1669         $expiry = $timemodified + 24 * 60 * 60;
1670     } else {
1671         $expiry = (int)$expiry;
1672     }
1674     if ($value === null) {
1675         unset_cache_flag($type, $name);
1676         return true;
1677     }
1679     if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1680         // This is a potential problem in DEBUG_DEVELOPER.
1681         if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1682             return true; // No need to update.
1683         }
1684         $f->value        = $value;
1685         $f->expiry       = $expiry;
1686         $f->timemodified = $timemodified;
1687         $DB->update_record('cache_flags', $f);
1688     } else {
1689         $f = new stdClass();
1690         $f->flagtype     = $type;
1691         $f->name         = $name;
1692         $f->value        = $value;
1693         $f->expiry       = $expiry;
1694         $f->timemodified = $timemodified;
1695         $DB->insert_record('cache_flags', $f);
1696     }
1697     return true;
1700 /**
1701  * Removes a single volatile flag
1702  *
1703  * @param string $type the "type" namespace for the key
1704  * @param string $name the key to set
1705  * @return bool
1706  */
1707 function unset_cache_flag($type, $name) {
1708     global $DB;
1709     $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1710     return true;
1713 /**
1714  * Garbage-collect volatile flags
1715  *
1716  * @return bool Always returns true
1717  */
1718 function gc_cache_flags() {
1719     global $DB;
1720     $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1721     return true;
1724 // USER PREFERENCE API.
1726 /**
1727  * Refresh user preference cache. This is used most often for $USER
1728  * object that is stored in session, but it also helps with performance in cron script.
1729  *
1730  * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1731  *
1732  * @package  core
1733  * @category preference
1734  * @access   public
1735  * @param    stdClass         $user          User object. Preferences are preloaded into 'preference' property
1736  * @param    int              $cachelifetime Cache life time on the current page (in seconds)
1737  * @throws   coding_exception
1738  * @return   null
1739  */
1740 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1741     global $DB;
1742     // Static cache, we need to check on each page load, not only every 2 minutes.
1743     static $loadedusers = array();
1745     if (!isset($user->id)) {
1746         throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1747     }
1749     if (empty($user->id) or isguestuser($user->id)) {
1750         // No permanent storage for not-logged-in users and guest.
1751         if (!isset($user->preference)) {
1752             $user->preference = array();
1753         }
1754         return;
1755     }
1757     $timenow = time();
1759     if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1760         // Already loaded at least once on this page. Are we up to date?
1761         if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1762             // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1763             return;
1765         } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1766             // No change since the lastcheck on this page.
1767             $user->preference['_lastloaded'] = $timenow;
1768             return;
1769         }
1770     }
1772     // OK, so we have to reload all preferences.
1773     $loadedusers[$user->id] = true;
1774     $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1775     $user->preference['_lastloaded'] = $timenow;
1778 /**
1779  * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1780  *
1781  * NOTE: internal function, do not call from other code.
1782  *
1783  * @package core
1784  * @access private
1785  * @param integer $userid the user whose prefs were changed.
1786  */
1787 function mark_user_preferences_changed($userid) {
1788     global $CFG;
1790     if (empty($userid) or isguestuser($userid)) {
1791         // No cache flags for guest and not-logged-in users.
1792         return;
1793     }
1795     set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1798 /**
1799  * Sets a preference for the specified user.
1800  *
1801  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1802  *
1803  * @package  core
1804  * @category preference
1805  * @access   public
1806  * @param    string            $name  The key to set as preference for the specified user
1807  * @param    string            $value The value to set for the $name key in the specified user's
1808  *                                    record, null means delete current value.
1809  * @param    stdClass|int|null $user  A moodle user object or id, null means current user
1810  * @throws   coding_exception
1811  * @return   bool                     Always true or exception
1812  */
1813 function set_user_preference($name, $value, $user = null) {
1814     global $USER, $DB;
1816     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1817         throw new coding_exception('Invalid preference name in set_user_preference() call');
1818     }
1820     if (is_null($value)) {
1821         // Null means delete current.
1822         return unset_user_preference($name, $user);
1823     } else if (is_object($value)) {
1824         throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1825     } else if (is_array($value)) {
1826         throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1827     }
1828     // Value column maximum length is 1333 characters.
1829     $value = (string)$value;
1830     if (core_text::strlen($value) > 1333) {
1831         throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1832     }
1834     if (is_null($user)) {
1835         $user = $USER;
1836     } else if (isset($user->id)) {
1837         // It is a valid object.
1838     } else if (is_numeric($user)) {
1839         $user = (object)array('id' => (int)$user);
1840     } else {
1841         throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1842     }
1844     check_user_preferences_loaded($user);
1846     if (empty($user->id) or isguestuser($user->id)) {
1847         // No permanent storage for not-logged-in users and guest.
1848         $user->preference[$name] = $value;
1849         return true;
1850     }
1852     if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1853         if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1854             // Preference already set to this value.
1855             return true;
1856         }
1857         $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1859     } else {
1860         $preference = new stdClass();
1861         $preference->userid = $user->id;
1862         $preference->name   = $name;
1863         $preference->value  = $value;
1864         $DB->insert_record('user_preferences', $preference);
1865     }
1867     // Update value in cache.
1868     $user->preference[$name] = $value;
1870     // Set reload flag for other sessions.
1871     mark_user_preferences_changed($user->id);
1873     return true;
1876 /**
1877  * Sets a whole array of preferences for the current user
1878  *
1879  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1880  *
1881  * @package  core
1882  * @category preference
1883  * @access   public
1884  * @param    array             $prefarray An array of key/value pairs to be set
1885  * @param    stdClass|int|null $user      A moodle user object or id, null means current user
1886  * @return   bool                         Always true or exception
1887  */
1888 function set_user_preferences(array $prefarray, $user = null) {
1889     foreach ($prefarray as $name => $value) {
1890         set_user_preference($name, $value, $user);
1891     }
1892     return true;
1895 /**
1896  * Unsets a preference completely by deleting it from the database
1897  *
1898  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1899  *
1900  * @package  core
1901  * @category preference
1902  * @access   public
1903  * @param    string            $name The key to unset as preference for the specified user
1904  * @param    stdClass|int|null $user A moodle user object or id, null means current user
1905  * @throws   coding_exception
1906  * @return   bool                    Always true or exception
1907  */
1908 function unset_user_preference($name, $user = null) {
1909     global $USER, $DB;
1911     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1912         throw new coding_exception('Invalid preference name in unset_user_preference() call');
1913     }
1915     if (is_null($user)) {
1916         $user = $USER;
1917     } else if (isset($user->id)) {
1918         // It is a valid object.
1919     } else if (is_numeric($user)) {
1920         $user = (object)array('id' => (int)$user);
1921     } else {
1922         throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1923     }
1925     check_user_preferences_loaded($user);
1927     if (empty($user->id) or isguestuser($user->id)) {
1928         // No permanent storage for not-logged-in user and guest.
1929         unset($user->preference[$name]);
1930         return true;
1931     }
1933     // Delete from DB.
1934     $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1936     // Delete the preference from cache.
1937     unset($user->preference[$name]);
1939     // Set reload flag for other sessions.
1940     mark_user_preferences_changed($user->id);
1942     return true;
1945 /**
1946  * Used to fetch user preference(s)
1947  *
1948  * If no arguments are supplied this function will return
1949  * all of the current user preferences as an array.
1950  *
1951  * If a name is specified then this function
1952  * attempts to return that particular preference value.  If
1953  * none is found, then the optional value $default is returned,
1954  * otherwise null.
1955  *
1956  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1957  *
1958  * @package  core
1959  * @category preference
1960  * @access   public
1961  * @param    string            $name    Name of the key to use in finding a preference value
1962  * @param    mixed|null        $default Value to be returned if the $name key is not set in the user preferences
1963  * @param    stdClass|int|null $user    A moodle user object or id, null means current user
1964  * @throws   coding_exception
1965  * @return   string|mixed|null          A string containing the value of a single preference. An
1966  *                                      array with all of the preferences or null
1967  */
1968 function get_user_preferences($name = null, $default = null, $user = null) {
1969     global $USER;
1971     if (is_null($name)) {
1972         // All prefs.
1973     } else if (is_numeric($name) or $name === '_lastloaded') {
1974         throw new coding_exception('Invalid preference name in get_user_preferences() call');
1975     }
1977     if (is_null($user)) {
1978         $user = $USER;
1979     } else if (isset($user->id)) {
1980         // Is a valid object.
1981     } else if (is_numeric($user)) {
1982         $user = (object)array('id' => (int)$user);
1983     } else {
1984         throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1985     }
1987     check_user_preferences_loaded($user);
1989     if (empty($name)) {
1990         // All values.
1991         return $user->preference;
1992     } else if (isset($user->preference[$name])) {
1993         // The single string value.
1994         return $user->preference[$name];
1995     } else {
1996         // Default value (null if not specified).
1997         return $default;
1998     }
2001 // FUNCTIONS FOR HANDLING TIME.
2003 /**
2004  * Given date parts in user time produce a GMT timestamp.
2005  *
2006  * @package core
2007  * @category time
2008  * @param int $year The year part to create timestamp of
2009  * @param int $month The month part to create timestamp of
2010  * @param int $day The day part to create timestamp of
2011  * @param int $hour The hour part to create timestamp of
2012  * @param int $minute The minute part to create timestamp of
2013  * @param int $second The second part to create timestamp of
2014  * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2015  *             if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2016  * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2017  *             applied only if timezone is 99 or string.
2018  * @return int GMT timestamp
2019  */
2020 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2022     // Save input timezone, required for dst offset check.
2023     $passedtimezone = $timezone;
2025     $timezone = get_user_timezone_offset($timezone);
2027     if (abs($timezone) > 13) {
2028         // Server time.
2029         $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2030     } else {
2031         $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2032         $time = usertime($time, $timezone);
2034         // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
2035         if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
2036             $time -= dst_offset_on($time, $passedtimezone);
2037         }
2038     }
2040     return $time;
2044 /**
2045  * Format a date/time (seconds) as weeks, days, hours etc as needed
2046  *
2047  * Given an amount of time in seconds, returns string
2048  * formatted nicely as weeks, days, hours etc as needed
2049  *
2050  * @package core
2051  * @category time
2052  * @uses MINSECS
2053  * @uses HOURSECS
2054  * @uses DAYSECS
2055  * @uses YEARSECS
2056  * @param int $totalsecs Time in seconds
2057  * @param stdClass $str Should be a time object
2058  * @return string A nicely formatted date/time string
2059  */
2060 function format_time($totalsecs, $str = null) {
2062     $totalsecs = abs($totalsecs);
2064     if (!$str) {
2065         // Create the str structure the slow way.
2066         $str = new stdClass();
2067         $str->day   = get_string('day');
2068         $str->days  = get_string('days');
2069         $str->hour  = get_string('hour');
2070         $str->hours = get_string('hours');
2071         $str->min   = get_string('min');
2072         $str->mins  = get_string('mins');
2073         $str->sec   = get_string('sec');
2074         $str->secs  = get_string('secs');
2075         $str->year  = get_string('year');
2076         $str->years = get_string('years');
2077     }
2079     $years     = floor($totalsecs/YEARSECS);
2080     $remainder = $totalsecs - ($years*YEARSECS);
2081     $days      = floor($remainder/DAYSECS);
2082     $remainder = $totalsecs - ($days*DAYSECS);
2083     $hours     = floor($remainder/HOURSECS);
2084     $remainder = $remainder - ($hours*HOURSECS);
2085     $mins      = floor($remainder/MINSECS);
2086     $secs      = $remainder - ($mins*MINSECS);
2088     $ss = ($secs == 1)  ? $str->sec  : $str->secs;
2089     $sm = ($mins == 1)  ? $str->min  : $str->mins;
2090     $sh = ($hours == 1) ? $str->hour : $str->hours;
2091     $sd = ($days == 1)  ? $str->day  : $str->days;
2092     $sy = ($years == 1)  ? $str->year  : $str->years;
2094     $oyears = '';
2095     $odays = '';
2096     $ohours = '';
2097     $omins = '';
2098     $osecs = '';
2100     if ($years) {
2101         $oyears  = $years .' '. $sy;
2102     }
2103     if ($days) {
2104         $odays  = $days .' '. $sd;
2105     }
2106     if ($hours) {
2107         $ohours = $hours .' '. $sh;
2108     }
2109     if ($mins) {
2110         $omins  = $mins .' '. $sm;
2111     }
2112     if ($secs) {
2113         $osecs  = $secs .' '. $ss;
2114     }
2116     if ($years) {
2117         return trim($oyears .' '. $odays);
2118     }
2119     if ($days) {
2120         return trim($odays .' '. $ohours);
2121     }
2122     if ($hours) {
2123         return trim($ohours .' '. $omins);
2124     }
2125     if ($mins) {
2126         return trim($omins .' '. $osecs);
2127     }
2128     if ($secs) {
2129         return $osecs;
2130     }
2131     return get_string('now');
2134 /**
2135  * Returns a formatted string that represents a date in user time
2136  *
2137  * Returns a formatted string that represents a date in user time
2138  * <b>WARNING: note that the format is for strftime(), not date().</b>
2139  * Because of a bug in most Windows time libraries, we can't use
2140  * the nicer %e, so we have to use %d which has leading zeroes.
2141  * A lot of the fuss in the function is just getting rid of these leading
2142  * zeroes as efficiently as possible.
2143  *
2144  * If parameter fixday = true (default), then take off leading
2145  * zero from %d, else maintain it.
2146  *
2147  * @package core
2148  * @category time
2149  * @param int $date the timestamp in UTC, as obtained from the database.
2150  * @param string $format strftime format. You should probably get this using
2151  *        get_string('strftime...', 'langconfig');
2152  * @param int|float|string  $timezone by default, uses the user's time zone. if numeric and
2153  *        not 99 then daylight saving will not be added.
2154  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2155  * @param bool $fixday If true (default) then the leading zero from %d is removed.
2156  *        If false then the leading zero is maintained.
2157  * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2158  * @return string the formatted date/time.
2159  */
2160 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2162     global $CFG;
2164     if (empty($format)) {
2165         $format = get_string('strftimedaydatetime', 'langconfig');
2166     }
2168     if (!empty($CFG->nofixday)) {
2169         // Config.php can force %d not to be fixed.
2170         $fixday = false;
2171     } else if ($fixday) {
2172         $formatnoday = str_replace('%d', 'DD', $format);
2173         $fixday = ($formatnoday != $format);
2174         $format = $formatnoday;
2175     }
2177     // Note: This logic about fixing 12-hour time to remove unnecessary leading
2178     // zero is required because on Windows, PHP strftime function does not
2179     // support the correct 'hour without leading zero' parameter (%l).
2180     if (!empty($CFG->nofixhour)) {
2181         // Config.php can force %I not to be fixed.
2182         $fixhour = false;
2183     } else if ($fixhour) {
2184         $formatnohour = str_replace('%I', 'HH', $format);
2185         $fixhour = ($formatnohour != $format);
2186         $format = $formatnohour;
2187     }
2189     // Add daylight saving offset for string timezones only, as we can't get dst for
2190     // float values. if timezone is 99 (user default timezone), then try update dst.
2191     if ((99 == $timezone) || !is_numeric($timezone)) {
2192         $date += dst_offset_on($date, $timezone);
2193     }
2195     $timezone = get_user_timezone_offset($timezone);
2197     // If we are running under Windows convert to windows encoding and then back to UTF-8
2198     // (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2200     if (abs($timezone) > 13) {
2201         // Server time.
2202         $datestring = date_format_string($date, $format, $timezone);
2203         if ($fixday) {
2204             $daystring  = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
2205             $datestring = str_replace('DD', $daystring, $datestring);
2206         }
2207         if ($fixhour) {
2208             $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2209             $datestring = str_replace('HH', $hourstring, $datestring);
2210         }
2212     } else {
2213         $date += (int)($timezone * 3600);
2214         $datestring = date_format_string($date, $format, $timezone);
2215         if ($fixday) {
2216             $daystring  = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
2217             $datestring = str_replace('DD', $daystring, $datestring);
2218         }
2219         if ($fixhour) {
2220             $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2221             $datestring = str_replace('HH', $hourstring, $datestring);
2222         }
2223     }
2225     return $datestring;
2228 /**
2229  * Returns a formatted date ensuring it is UTF-8.
2230  *
2231  * If we are running under Windows convert to Windows encoding and then back to UTF-8
2232  * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2233  *
2234  * This function does not do any calculation regarding the user preferences and should
2235  * therefore receive the final date timestamp, format and timezone. Timezone being only used
2236  * to differentiate the use of server time or not (strftime() against gmstrftime()).
2237  *
2238  * @param int $date the timestamp.
2239  * @param string $format strftime format.
2240  * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2241  * @return string the formatted date/time.
2242  * @since 2.3.3
2243  */
2244 function date_format_string($date, $format, $tz = 99) {
2245     global $CFG;
2246     if (abs($tz) > 13) {
2247         if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
2248             $format = core_text::convert($format, 'utf-8', $localewincharset);
2249             $datestring = strftime($format, $date);
2250             $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2251         } else {
2252             $datestring = strftime($format, $date);
2253         }
2254     } else {
2255         if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
2256             $format = core_text::convert($format, 'utf-8', $localewincharset);
2257             $datestring = gmstrftime($format, $date);
2258             $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2259         } else {
2260             $datestring = gmstrftime($format, $date);
2261         }
2262     }
2263     return $datestring;
2266 /**
2267  * Given a $time timestamp in GMT (seconds since epoch),
2268  * returns an array that represents the date in user time
2269  *
2270  * @package core
2271  * @category time
2272  * @uses HOURSECS
2273  * @param int $time Timestamp in GMT
2274  * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2275  *        dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
2276  * @return array An array that represents the date in user time
2277  */
2278 function usergetdate($time, $timezone=99) {
2280     // Save input timezone, required for dst offset check.
2281     $passedtimezone = $timezone;
2283     $timezone = get_user_timezone_offset($timezone);
2285     if (abs($timezone) > 13) {
2286         // Server time.
2287         return getdate($time);
2288     }
2290     // Add daylight saving offset for string timezones only, as we can't get dst for
2291     // float values. if timezone is 99 (user default timezone), then try update dst.
2292     if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2293         $time += dst_offset_on($time, $passedtimezone);
2294     }
2296     $time += intval((float)$timezone * HOURSECS);
2298     $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2300     // Be careful to ensure the returned array matches that produced by getdate() above.
2301     list(
2302         $getdate['month'],
2303         $getdate['weekday'],
2304         $getdate['yday'],
2305         $getdate['year'],
2306         $getdate['mon'],
2307         $getdate['wday'],
2308         $getdate['mday'],
2309         $getdate['hours'],
2310         $getdate['minutes'],
2311         $getdate['seconds']
2312     ) = explode('_', $datestring);
2314     // Set correct datatype to match with getdate().
2315     $getdate['seconds'] = (int)$getdate['seconds'];
2316     $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
2317     $getdate['year'] = (int)$getdate['year'];
2318     $getdate['mon'] = (int)$getdate['mon'];
2319     $getdate['wday'] = (int)$getdate['wday'];
2320     $getdate['mday'] = (int)$getdate['mday'];
2321     $getdate['hours'] = (int)$getdate['hours'];
2322     $getdate['minutes']  = (int)$getdate['minutes'];
2323     return $getdate;
2326 /**
2327  * Given a GMT timestamp (seconds since epoch), offsets it by
2328  * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2329  *
2330  * @package core
2331  * @category time
2332  * @uses HOURSECS
2333  * @param int $date Timestamp in GMT
2334  * @param float|int|string $timezone timezone to calculate GMT time offset before
2335  *        calculating user time, 99 is default user timezone
2336  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2337  * @return int
2338  */
2339 function usertime($date, $timezone=99) {
2341     $timezone = get_user_timezone_offset($timezone);
2343     if (abs($timezone) > 13) {
2344         return $date;
2345     }
2346     return $date - (int)($timezone * HOURSECS);
2349 /**
2350  * Given a time, return the GMT timestamp of the most recent midnight
2351  * for the current user.
2352  *
2353  * @package core
2354  * @category time
2355  * @param int $date Timestamp in GMT
2356  * @param float|int|string $timezone timezone to calculate GMT time offset before
2357  *        calculating user midnight time, 99 is default user timezone
2358  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2359  * @return int Returns a GMT timestamp
2360  */
2361 function usergetmidnight($date, $timezone=99) {
2363     $userdate = usergetdate($date, $timezone);
2365     // Time of midnight of this user's day, in GMT.
2366     return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2370 /**
2371  * Returns a string that prints the user's timezone
2372  *
2373  * @package core
2374  * @category time
2375  * @param float|int|string $timezone timezone to calculate GMT time offset before
2376  *        calculating user timezone, 99 is default user timezone
2377  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2378  * @return string
2379  */
2380 function usertimezone($timezone=99) {
2382     $tz = get_user_timezone($timezone);
2384     if (!is_float($tz)) {
2385         return $tz;
2386     }
2388     if (abs($tz) > 13) {
2389         // Server time.
2390         return get_string('serverlocaltime');
2391     }
2393     if ($tz == intval($tz)) {
2394         // Don't show .0 for whole hours.
2395         $tz = intval($tz);
2396     }
2398     if ($tz == 0) {
2399         return 'UTC';
2400     } else if ($tz > 0) {
2401         return 'UTC+'.$tz;
2402     } else {
2403         return 'UTC'.$tz;
2404     }
2408 /**
2409  * Returns a float which represents the user's timezone difference from GMT in hours
2410  * Checks various settings and picks the most dominant of those which have a value
2411  *
2412  * @package core
2413  * @category time
2414  * @param float|int|string $tz timezone to calculate GMT time offset for user,
2415  *        99 is default user timezone
2416  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2417  * @return float
2418  */
2419 function get_user_timezone_offset($tz = 99) {
2420     $tz = get_user_timezone($tz);
2422     if (is_float($tz)) {
2423         return $tz;
2424     } else {
2425         $tzrecord = get_timezone_record($tz);
2426         if (empty($tzrecord)) {
2427             return 99.0;
2428         }
2429         return (float)$tzrecord->gmtoff / HOURMINS;
2430     }
2433 /**
2434  * Returns an int which represents the systems's timezone difference from GMT in seconds
2435  *
2436  * @package core
2437  * @category time
2438  * @param float|int|string $tz timezone for which offset is required.
2439  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2440  * @return int|bool if found, false is timezone 99 or error
2441  */
2442 function get_timezone_offset($tz) {
2443     if ($tz == 99) {
2444         return false;
2445     }
2447     if (is_numeric($tz)) {
2448         return intval($tz * 60*60);
2449     }
2451     if (!$tzrecord = get_timezone_record($tz)) {
2452         return false;
2453     }
2454     return intval($tzrecord->gmtoff * 60);
2457 /**
2458  * Returns a float or a string which denotes the user's timezone
2459  * 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)
2460  * means that for this timezone there are also DST rules to be taken into account
2461  * Checks various settings and picks the most dominant of those which have a value
2462  *
2463  * @package core
2464  * @category time
2465  * @param float|int|string $tz timezone to calculate GMT time offset before
2466  *        calculating user timezone, 99 is default user timezone
2467  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2468  * @return float|string
2469  */
2470 function get_user_timezone($tz = 99) {
2471     global $USER, $CFG;
2473     $timezones = array(
2474         $tz,
2475         isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2476         isset($USER->timezone) ? $USER->timezone : 99,
2477         isset($CFG->timezone) ? $CFG->timezone : 99,
2478         );
2480     $tz = 99;
2482     // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2483     while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2484         $tz = $next['value'];
2485     }
2486     return is_numeric($tz) ? (float) $tz : $tz;
2489 /**
2490  * Returns cached timezone record for given $timezonename
2491  *
2492  * @package core
2493  * @param string $timezonename name of the timezone
2494  * @return stdClass|bool timezonerecord or false
2495  */
2496 function get_timezone_record($timezonename) {
2497     global $DB;
2498     static $cache = null;
2500     if ($cache === null) {
2501         $cache = array();
2502     }
2504     if (isset($cache[$timezonename])) {
2505         return $cache[$timezonename];
2506     }
2508     return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2509                                                         WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2512 /**
2513  * Build and store the users Daylight Saving Time (DST) table
2514  *
2515  * @package core
2516  * @param int $fromyear Start year for the table, defaults to 1971
2517  * @param int $toyear End year for the table, defaults to 2035
2518  * @param int|float|string $strtimezone timezone to check if dst should be applied.
2519  * @return bool
2520  */
2521 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2522     global $SESSION, $DB;
2524     $usertz = get_user_timezone($strtimezone);
2526     if (is_float($usertz)) {
2527         // Trivial timezone, no DST.
2528         return false;
2529     }
2531     if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2532         // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
2533         unset($SESSION->dst_offsets);
2534         unset($SESSION->dst_range);
2535     }
2537     if (!empty($SESSION->dst_offsets) && empty($fromyear) && empty($toyear)) {
2538         // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
2539         // This will be the return path most of the time, pretty light computationally.
2540         return true;
2541     }
2543     // Reaching here means we either need to extend our table or create it from scratch.
2545     // Remember which TZ we calculated these changes for.
2546     $SESSION->dst_offsettz = $usertz;
2548     if (empty($SESSION->dst_offsets)) {
2549         // If we 're creating from scratch, put the two guard elements in there.
2550         $SESSION->dst_offsets = array(1 => null, 0 => null);
2551     }
2552     if (empty($SESSION->dst_range)) {
2553         // If creating from scratch.
2554         $from = max((empty($fromyear) ? intval(date('Y')) - 3 : $fromyear), 1971);
2555         $to   = min((empty($toyear)   ? intval(date('Y')) + 3 : $toyear),   2035);
2557         // Fill in the array with the extra years we need to process.
2558         $yearstoprocess = array();
2559         for ($i = $from; $i <= $to; ++$i) {
2560             $yearstoprocess[] = $i;
2561         }
2563         // Take note of which years we have processed for future calls.
2564         $SESSION->dst_range = array($from, $to);
2565     } else {
2566         // If needing to extend the table, do the same.
2567         $yearstoprocess = array();
2569         $from = max((empty($fromyear) ? $SESSION->dst_range[0] : $fromyear), 1971);
2570         $to   = min((empty($toyear)   ? $SESSION->dst_range[1] : $toyear),   2035);
2572         if ($from < $SESSION->dst_range[0]) {
2573             // Take note of which years we need to process and then note that we have processed them for future calls.
2574             for ($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2575                 $yearstoprocess[] = $i;
2576             }
2577             $SESSION->dst_range[0] = $from;
2578         }
2579         if ($to > $SESSION->dst_range[1]) {
2580             // Take note of which years we need to process and then note that we have processed them for future calls.
2581             for ($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2582                 $yearstoprocess[] = $i;
2583             }
2584             $SESSION->dst_range[1] = $to;
2585         }
2586     }
2588     if (empty($yearstoprocess)) {
2589         // This means that there was a call requesting a SMALLER range than we have already calculated.
2590         return true;
2591     }
2593     // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2594     // Also, the array is sorted in descending timestamp order!
2596     // Get DB data.
2598     static $presetscache = array();
2599     if (!isset($presetscache[$usertz])) {
2600         $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
2601             'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
2602             'std_startday, std_weekday, std_skipweeks, std_time');
2603     }
2604     if (empty($presetscache[$usertz])) {
2605         return false;
2606     }
2608     // Remove ending guard (first element of the array).
2609     reset($SESSION->dst_offsets);
2610     unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2612     // Add all required change timestamps.
2613     foreach ($yearstoprocess as $y) {
2614         // Find the record which is in effect for the year $y.
2615         foreach ($presetscache[$usertz] as $year => $preset) {
2616             if ($year <= $y) {
2617                 break;
2618             }
2619         }
2621         $changes = dst_changes_for_year($y, $preset);
2623         if ($changes === null) {
2624             continue;
2625         }
2626         if ($changes['dst'] != 0) {
2627             $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2628         }
2629         if ($changes['std'] != 0) {
2630             $SESSION->dst_offsets[$changes['std']] = 0;
2631         }
2632     }
2634     // Put in a guard element at the top.
2635     $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2636     $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = null; // DAYSECS is arbitrary, any "small" number will do.
2638     // Sort again.
2639     krsort($SESSION->dst_offsets);
2641     return true;
2644 /**
2645  * Calculates the required DST change and returns a Timestamp Array
2646  *
2647  * @package core
2648  * @category time
2649  * @uses HOURSECS
2650  * @uses MINSECS
2651  * @param int|string $year Int or String Year to focus on
2652  * @param object $timezone Instatiated Timezone object
2653  * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
2654  */
2655 function dst_changes_for_year($year, $timezone) {
2657     if ($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 &&
2658         $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2659         return null;
2660     }
2662     $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2663     $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2665     list($dsthour, $dstmin) = explode(':', $timezone->dst_time);
2666     list($stdhour, $stdmin) = explode(':', $timezone->std_time);
2668     $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2669     $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2671     // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2672     // This has the advantage of being able to have negative values for hour, i.e. for timezones
2673     // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2675     $timedst += $dsthour * HOURSECS + $dstmin * MINSECS;
2676     $timestd += $stdhour * HOURSECS + $stdmin * MINSECS;
2678     return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2681 /**
2682  * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2683  * - Note: Daylight saving only works for string timezones and not for float.
2684  *
2685  * @package core
2686  * @category time
2687  * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2688  * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2689  *        then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2690  * @return int
2691  */
2692 function dst_offset_on($time, $strtimezone = null) {
2693     global $SESSION;
2695     if (!calculate_user_dst_table(null, null, $strtimezone) || empty($SESSION->dst_offsets)) {
2696         return 0;
2697     }
2699     reset($SESSION->dst_offsets);
2700     while (list($from, $offset) = each($SESSION->dst_offsets)) {
2701         if ($from <= $time) {
2702             break;
2703         }
2704     }
2706     // This is the normal return path.
2707     if ($offset !== null) {
2708         return $offset;
2709     }
2711     // Reaching this point means we haven't calculated far enough, do it now:
2712     // Calculate extra DST changes if needed and recurse. The recursion always
2713     // moves toward the stopping condition, so will always end.
2715     if ($from == 0) {
2716         // We need a year smaller than $SESSION->dst_range[0].
2717         if ($SESSION->dst_range[0] == 1971) {
2718             return 0;
2719         }
2720         calculate_user_dst_table($SESSION->dst_range[0] - 5, null, $strtimezone);
2721         return dst_offset_on($time, $strtimezone);
2722     } else {
2723         // We need a year larger than $SESSION->dst_range[1].
2724         if ($SESSION->dst_range[1] == 2035) {
2725             return 0;
2726         }
2727         calculate_user_dst_table(null, $SESSION->dst_range[1] + 5, $strtimezone);
2728         return dst_offset_on($time, $strtimezone);
2729     }
2732 /**
2733  * Calculates when the day appears in specific month
2734  *
2735  * @package core
2736  * @category time
2737  * @param int $startday starting day of the month
2738  * @param int $weekday The day when week starts (normally taken from user preferences)
2739  * @param int $month The month whose day is sought
2740  * @param int $year The year of the month whose day is sought
2741  * @return int
2742  */
2743 function find_day_in_month($startday, $weekday, $month, $year) {
2745     $daysinmonth = days_in_month($month, $year);
2747     if ($weekday == -1) {
2748         // Don't care about weekday, so return:
2749         //    abs($startday) if $startday != -1
2750         //    $daysinmonth otherwise.
2751         return ($startday == -1) ? $daysinmonth : abs($startday);
2752     }
2754     // From now on we 're looking for a specific weekday.
2756     // Give "end of month" its actual value, since we know it.
2757     if ($startday == -1) {
2758         $startday = -1 * $daysinmonth;
2759     }
2761     // Starting from day $startday, the sign is the direction.
2763     if ($startday < 1) {
2765         $startday = abs($startday);
2766         $lastmonthweekday  = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2768         // This is the last such weekday of the month.
2769         $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2770         if ($lastinmonth > $daysinmonth) {
2771             $lastinmonth -= 7;
2772         }
2774         // Find the first such weekday <= $startday.
2775         while ($lastinmonth > $startday) {
2776             $lastinmonth -= 7;
2777         }
2779         return $lastinmonth;
2781     } else {
2783         $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2785         $diff = $weekday - $indexweekday;
2786         if ($diff < 0) {
2787             $diff += 7;
2788         }
2790         // This is the first such weekday of the month equal to or after $startday.
2791         $firstfromindex = $startday + $diff;
2793         return $firstfromindex;
2795     }
2798 /**
2799  * Calculate the number of days in a given month
2800  *
2801  * @package core
2802  * @category time
2803  * @param int $month The month whose day count is sought
2804  * @param int $year The year of the month whose day count is sought
2805  * @return int
2806  */
2807 function days_in_month($month, $year) {
2808     return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2811 /**
2812  * Calculate the position in the week of a specific calendar day
2813  *
2814  * @package core
2815  * @category time
2816  * @param int $day The day of the date whose position in the week is sought
2817  * @param int $month The month of the date whose position in the week is sought
2818  * @param int $year The year of the date whose position in the week is sought
2819  * @return int
2820  */
2821 function dayofweek($day, $month, $year) {
2822     // I wonder if this is any different from strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));.
2823     return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2826 // USER AUTHENTICATION AND LOGIN.
2828 /**
2829  * Returns full login url.
2830  *
2831  * @return string login url
2832  */
2833 function get_login_url() {
2834     global $CFG;
2836     $url = "$CFG->wwwroot/login/index.php";
2838     if (!empty($CFG->loginhttps)) {
2839         $url = str_replace('http:', 'https:', $url);
2840     }
2842     return $url;
2845 /**
2846  * This function checks that the current user is logged in and has the
2847  * required privileges
2848  *
2849  * This function checks that the current user is logged in, and optionally
2850  * whether they are allowed to be in a particular course and view a particular
2851  * course module.
2852  * If they are not logged in, then it redirects them to the site login unless
2853  * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2854  * case they are automatically logged in as guests.
2855  * If $courseid is given and the user is not enrolled in that course then the
2856  * user is redirected to the course enrolment page.
2857  * If $cm is given and the course module is hidden and the user is not a teacher
2858  * in the course then the user is redirected to the course home page.
2859  *
2860  * When $cm parameter specified, this function sets page layout to 'module'.
2861  * You need to change it manually later if some other layout needed.
2862  *
2863  * @package    core_access
2864  * @category   access
2865  *
2866  * @param mixed $courseorid id of the course or course object
2867  * @param bool $autologinguest default true
2868  * @param object $cm course module object
2869  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2870  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2871  *             in order to keep redirects working properly. MDL-14495
2872  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2873  * @return mixed Void, exit, and die depending on path
2874  * @throws coding_exception
2875  * @throws require_login_exception
2876  */
2877 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2878     global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2880     // Must not redirect when byteserving already started.
2881     if (!empty($_SERVER['HTTP_RANGE'])) {
2882         $preventredirect = true;
2883     }
2885     // Setup global $COURSE, themes, language and locale.
2886     if (!empty($courseorid)) {
2887         if (is_object($courseorid)) {
2888             $course = $courseorid;
2889         } else if ($courseorid == SITEID) {
2890             $course = clone($SITE);
2891         } else {
2892             $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2893         }
2894         if ($cm) {
2895             if ($cm->course != $course->id) {
2896                 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2897             }
2898             // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2899             if (!($cm instanceof cm_info)) {
2900                 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2901                 // db queries so this is not really a performance concern, however it is obviously
2902                 // better if you use get_fast_modinfo to get the cm before calling this.
2903                 $modinfo = get_fast_modinfo($course);
2904                 $cm = $modinfo->get_cm($cm->id);
2905             }
2906             $PAGE->set_cm($cm, $course); // Set's up global $COURSE.
2907             $PAGE->set_pagelayout('incourse');
2908         } else {
2909             $PAGE->set_course($course); // Set's up global $COURSE.
2910         }
2911     } else {
2912         // Do not touch global $COURSE via $PAGE->set_course(),
2913         // the reasons is we need to be able to call require_login() at any time!!
2914         $course = $SITE;
2915         if ($cm) {
2916             throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2917         }
2918     }
2920     // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2921     // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2922     // risk leading the user back to the AJAX request URL.
2923     if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2924         $setwantsurltome = false;
2925     }
2927     // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2928     if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2929         if ($setwantsurltome) {
2930             $SESSION->wantsurl = qualified_me();
2931         }
2932         redirect(get_login_url());
2933     }
2935     // If the user is not even logged in yet then make sure they are.
2936     if (!isloggedin()) {
2937         if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2938             if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2939                 // Misconfigured site guest, just redirect to login page.
2940                 redirect(get_login_url());
2941                 exit; // Never reached.
2942             }
2943             $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2944             complete_user_login($guest);
2945             $USER->autologinguest = true;
2946             $SESSION->lang = $lang;
2947         } else {
2948             // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2949             if ($preventredirect) {
2950                 throw new require_login_exception('You are not logged in');
2951             }
2953             if ($setwantsurltome) {
2954                 $SESSION->wantsurl = qualified_me();
2955             }
2956             if (!empty($_SERVER['HTTP_REFERER'])) {
2957                 $SESSION->fromurl  = $_SERVER['HTTP_REFERER'];
2958             }
2959             redirect(get_login_url());
2960             exit; // Never reached.
2961         }
2962     }
2964     // Loginas as redirection if needed.
2965     if ($course->id != SITEID and session_is_loggedinas()) {
2966         if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2967             if ($USER->loginascontext->instanceid != $course->id) {
2968                 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2969             }
2970         }
2971     }
2973     // Check whether the user should be changing password (but only if it is REALLY them).
2974     if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2975         $userauth = get_auth_plugin($USER->auth);
2976         if ($userauth->can_change_password() and !$preventredirect) {
2977             if ($setwantsurltome) {
2978                 $SESSION->wantsurl = qualified_me();
2979             }
2980             if ($changeurl = $userauth->change_password_url()) {
2981                 // Use plugin custom url.
2982                 redirect($changeurl);
2983             } else {
2984                 // Use moodle internal method.
2985                 if (empty($CFG->loginhttps)) {
2986                     redirect($CFG->wwwroot .'/login/change_password.php');
2987                 } else {
2988                     $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2989                     redirect($wwwroot .'/login/change_password.php');
2990                 }
2991             }
2992         } else {
2993             print_error('nopasswordchangeforced', 'auth');
2994         }
2995     }
2997     // Check that the user account is properly set up.
2998     if (user_not_fully_set_up($USER)) {
2999         if ($preventredirect) {
3000             throw new require_login_exception('User not fully set-up');
3001         }
3002         if ($setwantsurltome) {
3003             $SESSION->wantsurl = qualified_me();
3004         }
3005         redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
3006     }
3008     // Make sure the USER has a sesskey set up. Used for CSRF protection.
3009     sesskey();
3011     // Do not bother admins with any formalities.
3012     if (is_siteadmin()) {
3013         // Set accesstime or the user will appear offline which messes up messaging.
3014         user_accesstime_log($course->id);
3015         return;
3016     }
3018     // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
3019     if (!$USER->policyagreed and !is_siteadmin()) {
3020         if (!empty($CFG->sitepolicy) and !isguestuser()) {
3021             if ($preventredirect) {
3022                 throw new require_login_exception('Policy not agreed');
3023             }
3024             if ($setwantsurltome) {
3025                 $SESSION->wantsurl = qualified_me();
3026             }
3027             redirect($CFG->wwwroot .'/user/policy.php');
3028         } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
3029             if ($preventredirect) {
3030                 throw new require_login_exception('Policy not agreed');
3031             }
3032             if ($setwantsurltome) {
3033                 $SESSION->wantsurl = qualified_me();
3034             }
3035             redirect($CFG->wwwroot .'/user/policy.php');
3036         }
3037     }
3039     // Fetch the system context, the course context, and prefetch its child contexts.
3040     $sysctx = context_system::instance();
3041     $coursecontext = context_course::instance($course->id, MUST_EXIST);
3042     if ($cm) {
3043         $cmcontext = context_module::instance($cm->id, MUST_EXIST);
3044     } else {
3045         $cmcontext = null;
3046     }
3048     // If the site is currently under maintenance, then print a message.
3049     if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
3050         if ($preventredirect) {
3051             throw new require_login_exception('Maintenance in progress');
3052         }
3054         print_maintenance_message();
3055     }
3057     // Make sure the course itself is not hidden.
3058     if ($course->id == SITEID) {
3059         // Frontpage can not be hidden.
3060     } else {
3061         if (is_role_switched($course->id)) {
3062             // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3063         } else {
3064             if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3065                 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3066                 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3067                 if ($preventredirect) {
3068                     throw new require_login_exception('Course is hidden');
3069                 }
3070                 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3071                 // the navigation will mess up when trying to find it.
3072                 navigation_node::override_active_url(new moodle_url('/'));
3073                 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3074             }
3075         }
3076     }
3078     // Is the user enrolled?
3079     if ($course->id == SITEID) {
3080         // Everybody is enrolled on the frontpage.
3081     } else {
3082         if (session_is_loggedinas()) {
3083             // Make sure the REAL person can access this course first.
3084             $realuser = session_get_realuser();
3085             if (!is_enrolled($coursecontext, $realuser->id, '', true) and
3086                 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3087                 if ($preventredirect) {
3088                     throw new require_login_exception('Invalid course login-as access');
3089                 }
3090                 echo $OUTPUT->header();
3091                 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3092             }
3093         }
3095         $access = false;
3097         if (is_role_switched($course->id)) {
3098             // Ok, user had to be inside this course before the switch.
3099             $access = true;
3101         } else if (is_viewing($coursecontext, $USER)) {
3102             // Ok, no need to mess with enrol.
3103             $access = true;
3105         } else {
3106             if (isset($USER->enrol['enrolled'][$course->id])) {
3107                 if ($USER->enrol['enrolled'][$course->id] > time()) {
3108                     $access = true;
3109                     if (isset($USER->enrol['tempguest'][$course->id])) {
3110                         unset($USER->enrol['tempguest'][$course->id]);
3111                         remove_temp_course_roles($coursecontext);
3112                     }
3113                 } else {
3114                     // Expired.
3115                     unset($USER->enrol['enrolled'][$course->id]);
3116                 }
3117             }
3118             if (isset($USER->enrol['tempguest'][$course->id])) {
3119                 if ($USER->enrol['tempguest'][$course->id] == 0) {
3120                     $access = true;
3121                 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3122                     $access = true;
3123                 } else {
3124                     // Expired.
3125                     unset($USER->enrol['tempguest'][$course->id]);
3126                     remove_temp_course_roles($coursecontext);
3127                 }
3128             }
3130             if (!$access) {
3131                 // Cache not ok.
3132                 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3133                 if ($until !== false) {
3134                     // Active participants may always access, a timestamp in the future, 0 (always) or false.
3135                     if ($until == 0) {
3136                         $until = ENROL_MAX_TIMESTAMP;
3137                     }
3138                     $USER->enrol['enrolled'][$course->id] = $until;
3139                     $access = true;
3141                 } else {
3142                     $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3143                     $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3144                     $enrols = enrol_get_plugins(true);
3145                     // First ask all enabled enrol instances in course if they want to auto enrol user.
3146                     foreach ($instances as $instance) {
3147                         if (!isset($enrols[$instance->enrol])) {
3148                             continue;
3149                         }
3150                         // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3151                         $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3152                         if ($until !== false) {
3153                             if ($until == 0) {
3154                                 $until = ENROL_MAX_TIMESTAMP;
3155                             }
3156                             $USER->enrol['enrolled'][$course->id] = $until;
3157                             $access = true;
3158                             break;
3159                         }
3160                     }
3161                     // If not enrolled yet try to gain temporary guest access.
3162                     if (!$access) {
3163                         foreach ($instances as $instance) {
3164                             if (!isset($enrols[$instance->enrol])) {
3165                                 continue;
3166                             }
3167                             // Get a duration for the guest access, a timestamp in the future or false.
3168                             $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3169                             if ($until !== false and $until > time()) {
3170                                 $USER->enrol['tempguest'][$course->id] = $until;
3171                                 $access = true;
3172                                 break;
3173                             }
3174                         }
3175                     }
3176                 }
3177             }
3178         }
3180         if (!$access) {
3181             if ($preventredirect) {
3182                 throw new require_login_exception('Not enrolled');
3183             }
3184             if ($setwantsurltome) {
3185                 $SESSION->wantsurl = qualified_me();
3186             }
3187             redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3188         }
3189     }
3191     // Check visibility of activity to current user; includes visible flag, groupmembersonly, conditional availability, etc.
3192     if ($cm && !$cm->uservisible) {
3193         if ($preventredirect) {
3194             throw new require_login_exception('Activity is hidden');
3195         }
3196         if ($course->id != SITEID) {
3197             $url = new moodle_url('/course/view.php', array('id' => $course->id));
3198         } else {
3199             $url = new moodle_url('/');
3200         }
3201         redirect($url, get_string('activityiscurrentlyhidden'));
3202     }
3204     // Finally access granted, update lastaccess times.
3205     user_accesstime_log($course->id);
3209 /**
3210  * This function just makes sure a user is logged out.
3211  *
3212  * @package    core_access
3213  * @category   access
3214  */
3215 function require_logout() {
3216     global $USER;
3218     if (isloggedin()) {
3219         $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
3220         foreach ($authsequence as $authname) {
3221             $authplugin = get_auth_plugin($authname);
3222             $authplugin->prelogout_hook();
3223         }
3224     }
3226     $event = \core\event\user_loggedout::create(
3227             array(
3228                 'objectid' => $USER->id,
3229                 'context' => context_user::instance($USER->id)
3230                 )
3231             );
3232     $event->trigger();
3234     session_get_instance()->terminate_current();
3235     unset($GLOBALS['USER']);
3238 /**
3239  * Weaker version of require_login()
3240  *
3241  * This is a weaker version of {@link require_login()} which only requires login
3242  * when called from within a course rather than the site page, unless
3243  * the forcelogin option is turned on.
3244  * @see require_login()
3245  *
3246  * @package    core_access
3247  * @category   access
3248  *
3249  * @param mixed $courseorid The course object or id in question
3250  * @param bool $autologinguest Allow autologin guests if that is wanted
3251  * @param object $cm Course activity module if known
3252  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3253  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3254  *             in order to keep redirects working properly. MDL-14495
3255  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3256  * @return void
3257  * @throws coding_exception
3258  */
3259 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3260     global $CFG, $PAGE, $SITE;
3261     $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3262           or (!is_object($courseorid) and $courseorid == SITEID);
3263     if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3264         // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3265         // db queries so this is not really a performance concern, however it is obviously
3266         // better if you use get_fast_modinfo to get the cm before calling this.
3267         if (is_object($courseorid)) {
3268             $course = $courseorid;
3269         } else {
3270             $course = clone($SITE);
3271         }
3272         $modinfo = get_fast_modinfo($course);
3273         $cm = $modinfo->get_cm($cm->id);
3274     }
3275     if (!empty($CFG->forcelogin)) {
3276         // Login required for both SITE and courses.
3277         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3279     } else if ($issite && !empty($cm) and !$cm->uservisible) {
3280         // Always login for hidden activities.
3281         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3283     } else if ($issite) {
3284         // Login for SITE not required.
3285         if ($cm and empty($cm->visible)) {
3286             // Hidden activities are not accessible without login.
3287             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3288         } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3289             // Not-logged-in users do not have any group membership.
3290             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3291         } else {
3292             // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3293             if (!empty($courseorid)) {
3294                 if (is_object($courseorid)) {
3295                     $course = $courseorid;
3296                 } else {
3297                     $course = clone($SITE);
3298                 }
3299                 if ($cm) {
3300                     if ($cm->course != $course->id) {
3301                         throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3302                     }
3303                     $PAGE->set_cm($cm, $course);
3304                     $PAGE->set_pagelayout('incourse');
3305                 } else {
3306                     $PAGE->set_course($course);
3307                 }
3308             } else {
3309                 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3310                 $PAGE->set_course($PAGE->course);
3311             }
3312             // TODO: verify conditional activities here.
3313             user_accesstime_log(SITEID);
3314             return;
3315         }
3317     } else {
3318         // Course login always required.
3319         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3320     }
3323 /**
3324  * Require key login. Function terminates with error if key not found or incorrect.
3325  *
3326  * @uses NO_MOODLE_COOKIES
3327  * @uses PARAM_ALPHANUM
3328  * @param string $script unique script identifier
3329  * @param int $instance optional instance id
3330  * @return int Instance ID
3331  */
3332 function require_user_key_login($script, $instance=null) {
3333     global $DB;
3335     if (!NO_MOODLE_COOKIES) {
3336         print_error('sessioncookiesdisable');
3337     }
3339     // Extra safety.
3340     @session_write_close();
3342     $keyvalue = required_param('key', PARAM_ALPHANUM);
3344     if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3345         print_error('invalidkey');
3346     }
3348     if (!empty($key->validuntil) and $key->validuntil < time()) {
3349         print_error('expiredkey');
3350     }
3352     if ($key->iprestriction) {
3353         $remoteaddr = getremoteaddr(null);
3354         if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3355             print_error('ipmismatch');
3356         }
3357     }
3359     if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3360         print_error('invaliduserid');
3361     }
3363     // Emulate normal session.
3364     enrol_check_plugins($user);
3365     session_set_user($user);
3367     // Note we are not using normal login.
3368     if (!defined('USER_KEY_LOGIN')) {
3369         define('USER_KEY_LOGIN', true);
3370     }
3372     // Return instance id - it might be empty.
3373     return $key->instance;
3376 /**
3377  * Creates a new private user access key.
3378  *
3379  * @param string $script unique target identifier
3380  * @param int $userid
3381  * @param int $instance optional instance id
3382  * @param string $iprestriction optional ip restricted access
3383  * @param timestamp $validuntil key valid only until given data
3384  * @return string access key value
3385  */
3386 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3387     global $DB;
3389     $key = new stdClass();
3390     $key->script        = $script;
3391     $key->userid        = $userid;
3392     $key->instance      = $instance;
3393     $key->iprestriction = $iprestriction;
3394     $key->validuntil    = $validuntil;
3395     $key->timecreated   = time();
3397     // Something long and unique.
3398     $key->value         = md5($userid.'_'.time().random_string(40));
3399     while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3400         // Must be unique.
3401         $key->value     = md5($userid.'_'.time().random_string(40));
3402     }
3403     $DB->insert_record('user_private_key', $key);
3404     return $key->value;
3407 /**
3408  * Delete the user's new private user access keys for a particular script.
3409  *
3410  * @param string $script unique target identifier
3411  * @param int $userid
3412  * @return void
3413  */
3414 function delete_user_key($script, $userid) {
3415     global $DB;
3416     $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3419 /**
3420  * Gets a private user access key (and creates one if one doesn't exist).
3421  *
3422  * @param string $script unique target identifier
3423  * @param int $userid
3424  * @param int $instance optional instance id
3425  * @param string $iprestriction optional ip restricted access
3426  * @param timestamp $validuntil key valid only until given data
3427  * @return string access key value
3428  */
3429 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3430     global $DB;
3432     if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3433                                                          'instance' => $instance, 'iprestriction' => $iprestriction,
3434                                                          'validuntil' => $validuntil))) {
3435         return $key->value;
3436     } else {
3437         return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3438     }
3442 /**
3443  * Modify the user table by setting the currently logged in user's last login to now.
3444  *
3445  * @return bool Always returns true
3446  */
3447 function update_user_login_times() {
3448     global $USER, $DB, $CFG;
3450     require_once($CFG->dirroot.'/user/lib.php');
3452     if (isguestuser()) {
3453         // Do not update guest access times/ips for performance.
3454         return true;
3455     }
3457     $now = time();
3459     $user = new stdClass();
3460     $user->id = $USER->id;
3462     // Make sure all users that logged in have some firstaccess.
3463     if ($USER->firstaccess == 0) {
3464         $USER->firstaccess = $user->firstaccess = $now;
3465     }
3467     // Store the previous current as lastlogin.
3468     $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3470     $USER->currentlogin = $user->currentlogin = $now;
3472     // Function user_accesstime_log() may not update immediately, better do it here.
3473     $USER->lastaccess = $user->lastaccess = $now;
3474     $USER->lastip = $user->lastip = getremoteaddr();
3476     user_update_user($user, false);
3477     return true;
3480 /**
3481  * Determines if a user has completed setting up their account.
3482  *
3483  * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3484  * @return bool
3485  */
3486 function user_not_fully_set_up($user) {
3487     if (isguestuser($user)) {
3488         return false;
3489     }
3490     return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3493 /**
3494  * Check whether the user has exceeded the bounce threshold
3495  *
3496  * @param stdClass $user A {@link $USER} object
3497  * @return bool true => User has exceeded bounce threshold
3498  */
3499 function over_bounce_threshold($user) {
3500     global $CFG, $DB;
3502     if (empty($CFG->handlebounces)) {
3503         return false;
3504     }
3506     if (empty($user->id)) {
3507         // No real (DB) user, nothing to do here.
3508         return false;
3509     }
3511     // Set sensible defaults.
3512     if (empty($CFG->minbounces)) {
3513         $CFG->minbounces = 10;
3514     }
3515     if (empty($CFG->bounceratio)) {
3516         $CFG->bounceratio = .20;
3517     }
3518     $bouncecount = 0;
3519     $sendcount = 0;
3520     if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3521         $bouncecount = $bounce->value;
3522     }
3523     if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3524         $sendcount = $send->value;
3525     }
3526     return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3529 /**
3530  * Used to increment or reset email sent count
3531  *
3532  * @param stdClass $user object containing an id
3533  * @param bool $reset will reset the count to 0
3534  * @return void
3535  */
3536 function set_send_count($user, $reset=false) {
3537     global $DB;
3539     if (empty($user->id)) {
3540         // No real (DB) user, nothing to do here.
3541         return;
3542     }
3544     if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3545         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3546         $DB->update_record('user_preferences', $pref);
3547     } else if (!empty($reset)) {
3548         // If it's not there and we're resetting, don't bother. Make a new one.
3549         $pref = new stdClass();
3550         $pref->name   = 'email_send_count';
3551         $pref->value  = 1;
3552         $pref->userid = $user->id;
3553         $DB->insert_record('user_preferences', $pref, false);
3554     }
3557 /**
3558  * Increment or reset user's email bounce count
3559  *
3560  * @param stdClass $user object containing an id
3561  * @param bool $reset will reset the count to 0
3562  */
3563 function set_bounce_count($user, $reset=false) {
3564     global $DB;
3566     if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3567         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3568         $DB->update_record('user_preferences', $pref);
3569     } else if (!empty($reset)) {
3570         // If it's not there and we're resetting, don't bother. Make a new one.
3571         $pref = new stdClass();
3572         $pref->name   = 'email_bounce_count';
3573         $pref->value  = 1;
3574         $pref->userid = $user->id;
3575         $DB->insert_record('user_preferences', $pref, false);
3576     }
3579 /**
3580  * Determines if the logged in user is currently moving an activity
3581  *
3582  * @param int $courseid The id of the course being tested
3583  * @return bool
3584  */
3585 function ismoving($courseid) {
3586     global $USER;
3588     if (!empty($USER->activitycopy)) {
3589         return ($USER->activitycopycourse == $courseid);
3590     }
3591     return false;
3594 /**
3595  * Returns a persons full name
3596  *
3597  * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3598  * The result may depend on system settings or language.  'override' will force both names to be used even if system settings
3599  * specify one.
3600  *
3601  * @param stdClass $user A {@link $USER} object to get full name of.
3602  * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3603  * @return string
3604  */
3605 function fullname($user, $override=false) {
3606     global $CFG, $SESSION;
3608     if (!isset($user->firstname) and !isset($user->lastname)) {
3609         return '';
3610     }
3612     if (!$override) {
3613         if (!empty($CFG->forcefirstname)) {
3614             $user->firstname = $CFG->forcefirstname;
3615         }
3616         if (!empty($CFG->forcelastname)) {
3617             $user->lastname = $CFG->forcelastname;
3618         }
3619     }
3621     if (!empty($SESSION->fullnamedisplay)) {
3622         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3623     }
3625     $template = null;
3626     // If the fullnamedisplay setting is available, set the template to that.
3627     if (isset($CFG->fullnamedisplay)) {
3628         $template = $CFG->fullnamedisplay;
3629     }
3630     // If the template is empty, or set to language, or $override is set, return the language string.
3631     if (empty($template) || $template == 'language' || $override) {
3632         return get_string('fullnamedisplay', null, $user);
3633     }
3635     // Get all of the name fields.
3636     $allnames = get_all_user_name_fields();
3637     $requirednames = array();
3638     // With each name, see if it is in the display name template, and add it to the required names array if it is.
3639     foreach ($allnames as $allname) {
3640         if (strpos($template, $allname) !== false) {
3641             $requirednames[] = $allname;
3642             // If the field is in the template but not set in the user object then notify the programmer that it needs to be fixed.
3643             if (!array_key_exists($allname, $user)) {
3644                 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3645             }
3646         }
3647     }
3649     $displayname = $template;
3650     // Switch in the actual data into the template.
3651     foreach ($requirednames as $altname) {
3652         if (isset($user->$altname)) {
3653             // Using empty() on the below if statement causes breakages.
3654             if ((string)$user->$altname == '') {
3655                 $displayname = str_replace($altname, 'EMPTY', $displayname);
3656             } else {
3657                 $displayname = str_replace($altname, $user->$altname, $displayname);
3658             }
3659         } else {
3660             $displayname = str_replace($altname, 'EMPTY', $displayname);
3661         }
3662     }
3663     // Tidy up any misc. characters (Not perfect, but gets most characters).
3664     // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3665     // katakana and parenthesis.
3666     $patterns = array();
3667     // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3668     // filled in by a user.
3669     // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3670     $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3671     // This regular expression is to remove any double spaces in the display name.
3672     $patterns[] = '/\s{2,}/';
3673     foreach ($patterns as $pattern) {
3674         $displayname = preg_replace($pattern, ' ', $displayname);
3675     }
3677     // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3678     $displayname = trim($displayname);
3679     if (empty($displayname)) {
3680         // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3681         // people in general feel is a good setting to fall back on.
3682         $displayname = $user->firstname;
3683     }
3684     return $displayname;
3687 /**
3688  * A centralised location for the all name fields. Returns an array / sql string snippet.
3689  *
3690  * @param bool $returnsql True for an sql select field snippet.
3691  * @param string $alias table alias to use in front of each field.
3692  * @return array|string All name fields.
3693  */
3694 function get_all_user_name_fields($returnsql = false, $alias = null) {
3695     $alternatenames = array('firstnamephonetic',
3696                             'lastnamephonetic',
3697                             'middlename',
3698                             'alternatename',
3699                             'firstname',
3700                             'lastname');
3701     if ($returnsql) {
3702         if ($alias) {
3703             foreach ($alternatenames as $key => $altname) {
3704                 $alternatenames[$key] = "$alias.$altname";
3705             }
3706         }
3707         $alternatenames = implode(',', $alternatenames);
3708     }
3709     return $alternatenames;
3712 /**
3713  * Returns an array of values in order of occurance in a provided string.
3714  * The key in the result is the character postion in the string.
3715  *
3716  * @param array $values Values to be found in the string format
3717  * @param string $stringformat The string which may contain values being searched for.
3718  * @return array An array of values in order according to placement in the string format.
3719  */
3720 function order_in_string($values, $stringformat) {
3721     $valuearray = array();
3722     foreach ($values as $value) {
3723         $pattern = "/$value\b/";
3724         // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3725         if (preg_match($pattern, $stringformat)) {
3726             $replacement = "thing";
3727             // Replace the value with something more unique to ensure we get the right position when using strpos().
3728             $newformat = preg_replace($pattern, $replacement, $stringformat);
3729             $position = strpos($newformat, $replacement);
3730             $valuearray[$position] = $value;
3731         }
3732     }
3733     ksort($valuearray);
3734     return $valuearray;
3737 /**
3738  * Checks if current user is shown any extra fields when listing users.
3739  *
3740  * @param object $context Context
3741  * @param array $already Array of fields that we're going to show anyway
3742  *   so don't bother listing them
3743  * @return array Array of field names from user table, not including anything
3744  *   listed in $already
3745  */
3746 function get_extra_user_fields($context, $already = array()) {
3747     global $CFG;
3749     // Only users with permission get the extra fields.
3750     if (!has_capability('moodle/site:viewuseridentity', $context)) {
3751         return array();
3752     }
3754     // Split showuseridentity on comma.
3755     if (empty($CFG->showuseridentity)) {
3756         // Explode gives wrong result with empty string.
3757         $extra = array();
3758     } else {
3759         $extra =  explode(',', $CFG->showuseridentity);
3760     }
3761     $renumber = false;
3762     foreach ($extra as $key => $field) {
3763         if (in_array($field, $already)) {
3764             unset($extra[$key]);
3765             $renumber = true;
3766         }
3767     }
3768     if ($renumber) {
3769         // For consistency, if entries are removed from array, renumber it
3770         // so they are numbered as you would expect.
3771         $extra = array_merge($extra);
3772     }
3773     return $extra;
3776 /**
3777  * If the current user is to be shown extra user fields when listing or
3778  * selecting users, returns a string suitable for including in an SQL select
3779  * clause to retrieve those fields.
3780  *
3781  * @param context $context Context
3782  * @param string $alias Alias of user table, e.g. 'u' (default none)
3783  * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3784  * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3785  * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3786  */
3787 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3788     $fields = get_extra_user_fields($context, $already);
3789     $result = '';
3790     // Add punctuation for alias.
3791     if ($alias !== '') {
3792         $alias .= '.';
3793     }
3794     foreach ($fields as $field) {
3795         $result .= ', ' . $alias . $field;
3796         if ($prefix) {
3797             $result .= ' AS ' . $prefix . $field;
3798         }
3799     }
3800     return $result;
3803 /**
3804  * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3805  * @param string $field Field name, e.g. 'phone1'
3806  * @return string Text description taken from language file, e.g. 'Phone number'
3807  */
3808 function get_user_field_name($field) {
3809     // Some fields have language strings which are not the same as field name.
3810     switch ($field) {
3811         case 'phone1' : {
3812             return get_string('phone');
3813         }
3814         case 'url' : {
3815             return get_string('webpage');
3816         }
3817         case 'icq' : {
3818             return get_string('icqnumber');
3819         }
3820         case 'skype' : {
3821             return get_string('skypeid');
3822         }
3823         case 'aim' : {
3824             return get_string('aimid');
3825         }
3826         case 'yahoo' : {
3827             return get_string('yahooid');
3828         }
3829         case 'msn' : {
3830             return get_string('msnid');
3831         }
3832     }
3833     // Otherwise just use the same lang string.
3834     return get_string($field);
3837 /**
3838  * Returns whether a given authentication plugin exists.
3839  *
3840  * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3841  * @return boolean Whether the plugin is available.
3842  */
3843 function exists_auth_plugin($auth) {
3844     global $CFG;
3846     if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3847         return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3848     }
3849     return false;
3852 /**
3853  * Checks if a given plugin is in the list of enabled authentication plugins.
3854  *
3855  * @param string $auth Authentication plugin.
3856  * @return boolean Whether the plugin is enabled.
3857  */
3858 function is_enabled_auth($auth) {
3859     if (empty($auth)) {
3860         return false;
3861     }
3863     $enabled = get_enabled_auth_plugins();
3865     return in_array($auth, $enabled);
3868 /**
3869  * Returns an authentication plugin instance.
3870  *
3871  * @param string $auth name of authentication plugin
3872  * @return auth_plugin_base An instance of the required authentication plugin.
3873  */
3874 function get_auth_plugin($auth) {
3875     global $CFG;
3877     // Check the plugin exists first.
3878     if (! exists_auth_plugin($auth)) {
3879         print_error('authpluginnotfound', 'debug', '', $auth);
3880     }
3882     // Return auth plugin instance.
3883     require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3884     $class = "auth_plugin_$auth";
3885     return new $class;
3888 /**
3889  * Returns array of active auth plugins.
3890  *
3891  * @param bool $fix fix $CFG->auth if needed
3892  * @return array
3893  */
3894 function get_enabled_auth_plugins($fix=false) {
3895     global $CFG;
3897     $default = array('manual', 'nologin');
3899     if (empty($CFG->auth)) {
3900         $auths = array();
3901     } else {
3902         $auths = explode(',', $CFG->auth);
3903     }
3905     if ($fix) {
3906         $auths = array_unique($auths);
3907         foreach ($auths as $k => $authname) {
3908             if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3909                 unset($auths[$k]);
3910             }
3911         }
3912         $newconfig = implode(',', $auths);
3913         if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3914             set_config('auth', $newconfig);
3915         }
3916     }
3918     return (array_merge($default, $auths));
3921 /**
3922  * Returns true if an internal authentication method is being used.
3923  * if method not specified then, global default is assumed
3924  *
3925  * @param string $auth Form of authentication required
3926  * @return bool
3927  */
3928 function is_internal_auth($auth) {
3929     // Throws error if bad $auth.
3930     $authplugin = get_auth_plugin($auth);
3931     return $authplugin->is_internal();
3934 /**
3935  * Returns true if the user is a 'restored' one.
3936  *
3937  * Used in the login process to inform the user and allow him/her to reset the password
3938  *
3939  * @param string $username username to be checked
3940  * @return bool
3941  */
3942 function is_restored_user($username) {
3943     global $CFG, $DB;
3945     return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3948 /**
3949  * Returns an array of user fields
3950  *
3951  * @return array User field/column names
3952  */
3953 function get_user_fieldnames() {
3954     global $DB;
3956     $fieldarray = $DB->get_columns('user');
3957     unset($fieldarray['id']);
3958     $fieldarray = array_keys($fieldarray);
3960     return $fieldarray;
3963 /**
3964  * Creates a bare-bones user record
3965  *
3966  * @todo Outline auth types and provide code example
3967  *
3968  * @param string $username New user's username to add to record
3969  * @param string $password New user's password to add to record
3970  * @param string $auth Form of authentication required
3971  * @return stdClass A complete user object
3972  */
3973 function create_user_record($username, $password, $auth = 'manual') {
3974     global $CFG, $DB;
3975     require_once($CFG->dirroot.'/user/profile/lib.php');
3976     require_once($CFG->dirroot.'/user/lib.php');
3978     // Just in case check text case.
3979     $username = trim(core_text::strtolower($username));
3981     $authplugin = get_auth_plugin($auth);
3982     $customfields = $authplugin->get_custom_user_profile_fields();
3983     $newuser = new stdClass();
3984     if ($newinfo = $authplugin->get_userinfo($username)) {
3985         $newinfo = truncate_userinfo($newinfo);
3986         foreach ($newinfo as $key => $value) {
3987             if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3988                 $newuser->$key = $value;
3989             }
3990         }
3991     }
3993     if (!empty($newuser->email)) {
3994         if (email_is_not_allowed($newuser->email)) {
3995             unset($newuser->email);
3996         }
3997     }
3999     if (!isset($newuser->city)) {
4000         $newuser->city = '';
4001     }
4003     $newuser->auth = $auth;
4004     $newuser->username = $username;
4006     // Fix for MDL-8480
4007     // user CFG lang for user if $newuser->lang is empty
4008     // or $user->lang is not an installed language.
4009     if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
4010         $newuser->lang = $CFG->lang;
4011     }
4012     $newuser->confirmed = 1;
4013     $newuser->lastip = getremoteaddr();
4014     $newuser->timecreated = time();
4015     $newuser->timemodified = $newuser->timecreated;
4016     $newuser->mnethostid = $CFG->mnet_localhost_id;
4018     $newuser->id = user_create_user($newuser, false);
4020     // Save user profile data.
4021     profile_save_data($newuser);
4023     $user = get_complete_user_data('id', $newuser->id);
4024     if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
4025         set_user_preference('auth_forcepasswordchange', 1, $user);
4026     }
4027     // Set the password.
4028     update_internal_user_password($user, $password);
4030     return $user;
4033 /**
4034  * Will update a local user record from an external source (MNET users can not be updated using this method!).
4035  *
4036  * @param string $username user's username to update the record
4037  * @return stdClass A complete user object
4038  */
4039 function update_user_record($username) {
4040     global $DB, $CFG;
4041     require_once($CFG->dirroot."/user/profile/lib.php");
4042     require_once($CFG->dirroot.'/user/lib.php');
4043     // Just in case check text case.
4044     $username = trim(core_text::strtolower($username));
4046     $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
4047     $newuser = array();
4048     $userauth = get_auth_plugin($oldinfo->auth);
4050     if ($newinfo = $userauth->get_userinfo($username)) {
4051         $newinfo = truncate_userinfo($newinfo);
4052         $customfields = $userauth->get_custom_user_profile_fields();
4054         foreach ($newinfo as $key => $value) {
4055             $key = strtolower($key);
4056             $iscustom = in_array($key, $customfields);
4057             if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4058                     or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4059                 // Unknown or must not be changed.
4060                 continue;
4061             }
4062             $confval = $userauth->config->{'field_updatelocal_' . $key};
4063             $lockval = $userauth->config->{'field_lock_' . $key};
4064             if (empty($confval) || empty($lockval)) {
4065                 continue;
4066             }
4067             if ($confval === 'onlogin') {
4068                 // MDL-4207 Don't overwrite modified user profile values with
4069                 // empty LDAP values when 'unlocked if empty' is set. The purpose
4070                 // of the setting 'unlocked if empty' is to allow the user to fill
4071                 // in a value for the selected field _if LDAP is giving
4072                 // nothing_ for this field. Thus it makes sense to let this value
4073                 // stand in until LDAP is giving a value for this field.
4074                 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4075                     if ($iscustom || (in_array($key, $userauth->userfields) &&
4076                             ((string)$oldinfo->$key !== (string)$value))) {
4077                         $newuser[$key] = (string)$value;
4078                     }
4079                 }
4080             }
4081         }
4082         if ($newuser) {
4083             $newuser['id'] = $oldinfo->id;
4084             $newuser['timemodified'] = time();
4085             user_update_user((object) $newuser, false);
4087             // Save user profile data.
4088             profile_save_data((object) $newuser);
4089         }
4090     }
4092     return get_complete_user_data('id', $oldinfo->id);
4095 /**
4096  * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4097  *
4098  * @param array $info Array of user properties to truncate if needed
4099  * @return array The now truncated information that was passed in
4100  */
4101 function truncate_userinfo(array $info) {
4102     // Define the limits.
4103     $limit = array(
4104         'username'    => 100,
4105         'idnumber'    => 255,
4106         'firstname'   => 100,
4107         'lastname'    => 100,
4108         'email'       => 100,
4109         'icq'         =>  15,
4110         'phone1'      =>  20,
4111         'phone2'      =>  20,
4112         'institution' =>  40,
4113         'department'  =>  30,
4114         'address'     =>  70,
4115         'city'        => 120,
4116         'country'     =>   2,
4117         'url'         => 255,
4118     );
4120     // Apply where needed.
4121     foreach (array_keys($info) as $key) {
4122         if (!empty($limit[$key])) {
4123             $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4124         }
4125     }
4127     return $info;
4130 /**
4131  * Marks user deleted in internal user database and notifies the auth plugin.
4132  * Also unenrols user from all roles and does other cleanup.
4133  *
4134  * Any plugin that needs to purge user data should register the 'user_deleted' event.
4135  *
4136  * @param stdClass $user full user object before delete
4137  * @return boolean success
4138  * @throws coding_exception if invalid $user parameter detected
4139  */
4140 function delete_user(stdClass $user) {
4141     global $CFG, $DB;
4142     require_once($CFG->libdir.'/grouplib.php');
4143     require_once($CFG->libdir.'/gradelib.php');
4144     require_once($CFG->dirroot.'/message/lib.php');
4145     require_once($CFG->dirroot.'/tag/lib.php');
4146     require_once($CFG->dirroot.'/user/lib.php');
4148     // Make sure nobody sends bogus record type as parameter.
4149     if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4150         throw new coding_exception('Invalid $user parameter in delete_user() detected');
4151     }
4153     // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4154     if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4155         debugging('Attempt to delete unknown user account.');
4156         return false;
4157     }
4159     // There must be always exactly one guest record, originally the guest account was identified by username only,
4160     // now we use $CFG->siteguest for performance reasons.
4161     if ($user->username === 'guest' or isguestuser($user)) {
4162         debugging('Guest user account can not be deleted.');
4163         return false;
4164     }
4166     // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4167     // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4168     if ($user->auth === 'manual' and is_siteadmin($user)) {
4169         debugging('Local administrator accounts can not be deleted.');
4170         return false;
4171     }
4173     // Keep a copy of user context, we need it for event.
4174     $usercontext = context_user::instance($user->id);
4176     // Delete all grades - backup is kept in grade_grades_history table.
4177     grade_user_delete($user->id);
4179     // Move unread messages from this user to read.
4180     message_move_userfrom_unread2read($user->id);
4182     // TODO: remove from cohorts using standard API here.
4184     // Remove user tags.
4185     tag_set('user', $user->id, array());
4187     // Unconditionally unenrol from all courses.
4188     enrol_user_delete($user);
4190     // Unenrol from all roles in all contexts.
4191     // This might be slow but it is really needed - modules might do some extra cleanup!
4192     role_unassign_all(array('userid' => $user->id));
4194     // Now do a brute force cleanup.
4196     // Remove from all cohorts.
4197     $DB->delete_records('cohort_members', array('userid' => $user->id));
4199     // Remove from all groups.
4200     $DB->delete_records('groups_members', array('userid' => $user->id));
4202     // Brute force unenrol from all courses.
4203     $DB->delete_records('user_enrolments', array('userid' => $user->id));
4205     // Purge user preferences.
4206     $DB->delete_records('user_preferences', array('userid' => $user->id));
4208     // Purge user extra profile info.
4209     $DB->delete_records('user_info_data', array('userid' => $user->id));
4211     // Last course access not necessary either.
4212     $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4213     // Remove all user tokens.
4214     $DB->delete_records('external_tokens', array('userid' => $user->id));
4216     // Unauthorise the user for all services.
4217     $DB->delete_records('external_services_users', array('userid' => $user->id));
4219     // Remove users private keys.
4220     $DB->delete_records('user_private_key', array('userid' => $user->id));
4222     // Force logout - may fail if file based sessions used, sorry.
4223     session_kill_user($user->id);
4225     // Workaround for bulk deletes of users with the same email address.
4226     $delname = "$user->email.".time();
4227     while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4228         $delname++;
4229     }
4231     // Mark internal user record as "deleted".
4232     $updateuser = new stdClass();
4233     $updateuser->id           = $user->id;
4234     $updateuser->deleted      = 1;
4235     $updateuser->username     = $delname;            // Remember it just in case.
4236     $updateuser->email        = md5($user->username);// Store hash of username, useful importing/restoring users.
4237     $updateuser->idnumber     = '';                  // Clear this field to free it up.
4238     $updateuser->picture      = 0;
4239     $updateuser->timemodified = time();
4241     user_update_user($updateuser, false);
4243     // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4244     context_helper::delete_instance(CONTEXT_USER, $user->id);
4246     // Any plugin that needs to cleanup should register this event.
4247     // Trigger event.
4248     $event = \core\event\user_deleted::create(
4249             array(
4250                 'objectid' => $user->id,
4251                 'context' => $usercontext,
4252                 'other' => array('user' => (array)clone $user)
4253                 )
4254             );
4255     $event->add_record_snapshot('user', $updateuser);
4256     $event->trigger();
4258     // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4259     // should know about this updated property persisted to the user's table.
4260     $user->timemodified = $updateuser->timemodified;
4262     // Notify auth plugin - do not block the delete even when plugin fails.
4263     $authplugin = get_auth_plugin($user->auth);
4264     $authplugin->user_delete($user);
4266     return true;
4269 /**
4270  * Retrieve the guest user object.
4271  *
4272  * @return stdClass A {@link $USER} object
4273  */
4274 function guest_user() {
4275     global $CFG, $DB;
4277     if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4278         $newuser->confirmed = 1;
4279         $newuser->lang = $CFG->lang;
4280         $newuser->lastip = getremoteaddr();
4281     }
4283     return $newuser;
4286 /**
4287  * Authenticates a user against the chosen authentication mechanism
4288  *
4289  * Given a username and password, this function looks them
4290  * up using the currently selected authentication mechanism,
4291  * and if the authentication is successful, it returns a
4292  * valid $user object from the 'user' table.
4293  *
4294  * Uses auth_ functions from the currently active auth module
4295  *
4296  * After authenticate_user_login() returns success, you will need to
4297  * log that the user has logged in, and call complete_user_login() to set
4298  * the session up.
4299  *
4300  * Note: this function works only with non-mnet accounts!
4301  *
4302  * @param string $username  User's username
4303  * @param string $password  User's password
4304  * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4305  * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4306  * @return stdClass|false A {@link $USER} object or false if error
4307  */
4308 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4309     global $CFG, $DB;
4310     require_once("$CFG->libdir/authlib.php");
4312     $authsenabled = get_enabled_auth_plugins();
4314     if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4315         // Use manual if auth not set.
4316         $auth = empty($user->auth) ? 'manual' : $user->auth;
4317         if (!empty($user->suspended)) {
4318             add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4319             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Suspended Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
4320             $failurereason = AUTH_LOGIN_SUSPENDED;
4321             return false;
4322         }
4323         if ($auth=='nologin' or !is_enabled_auth($auth)) {
4324             add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4325             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Disabled Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
4326             // Legacy way to suspend user.
4327             $failurereason = AUTH_LOGIN_SUSPENDED;
4328             return false;
4329         }