Merge branch 'MDL-68125-regression' of https://github.com/brendanheywood/moodle
[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 receiving
119  * the input (required/optional_param or formslib) and then sanitise 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  * Use PARAM_LOCALISEDFLOAT instead.
141  */
142 define('PARAM_FLOAT',  'float');
144 /**
145  * PARAM_LOCALISEDFLOAT - a localised real/floating point number.
146  * This is preferred over PARAM_FLOAT for numbers typed in by the user.
147  * Cleans localised numbers to computer readable numbers; false for invalid numbers.
148  */
149 define('PARAM_LOCALISEDFLOAT',  'localisedfloat');
151 /**
152  * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
153  */
154 define('PARAM_HOST',     'host');
156 /**
157  * PARAM_INT - integers only, use when expecting only numbers.
158  */
159 define('PARAM_INT',      'int');
161 /**
162  * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
163  */
164 define('PARAM_LANG',  'lang');
166 /**
167  * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
168  * others! Implies PARAM_URL!)
169  */
170 define('PARAM_LOCALURL', 'localurl');
172 /**
173  * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
174  */
175 define('PARAM_NOTAGS',   'notags');
177 /**
178  * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
179  * traversals note: the leading slash is not removed, window drive letter is not allowed
180  */
181 define('PARAM_PATH',     'path');
183 /**
184  * PARAM_PEM - Privacy Enhanced Mail format
185  */
186 define('PARAM_PEM',      'pem');
188 /**
189  * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
190  */
191 define('PARAM_PERMISSION',   'permission');
193 /**
194  * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
195  */
196 define('PARAM_RAW', 'raw');
198 /**
199  * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
200  */
201 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
203 /**
204  * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
205  */
206 define('PARAM_SAFEDIR',  'safedir');
208 /**
209  * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
210  */
211 define('PARAM_SAFEPATH',  'safepath');
213 /**
214  * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9.  Numbers and comma only.
215  */
216 define('PARAM_SEQUENCE',  'sequence');
218 /**
219  * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
220  */
221 define('PARAM_TAG',   'tag');
223 /**
224  * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
225  */
226 define('PARAM_TAGLIST',   'taglist');
228 /**
229  * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
230  */
231 define('PARAM_TEXT',  'text');
233 /**
234  * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
235  */
236 define('PARAM_THEME',  'theme');
238 /**
239  * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
240  * http://localhost.localdomain/ is ok.
241  */
242 define('PARAM_URL',      'url');
244 /**
245  * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
246  * accounts, do NOT use when syncing with external systems!!
247  */
248 define('PARAM_USERNAME',    'username');
250 /**
251  * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
252  */
253 define('PARAM_STRINGID',    'stringid');
255 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
256 /**
257  * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
258  * It was one of the first types, that is why it is abused so much ;-)
259  * @deprecated since 2.0
260  */
261 define('PARAM_CLEAN',    'clean');
263 /**
264  * PARAM_INTEGER - deprecated alias for PARAM_INT
265  * @deprecated since 2.0
266  */
267 define('PARAM_INTEGER',  'int');
269 /**
270  * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
271  * @deprecated since 2.0
272  */
273 define('PARAM_NUMBER',  'float');
275 /**
276  * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
277  * NOTE: originally alias for PARAM_APLHA
278  * @deprecated since 2.0
279  */
280 define('PARAM_ACTION',   'alphanumext');
282 /**
283  * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
284  * NOTE: originally alias for PARAM_APLHA
285  * @deprecated since 2.0
286  */
287 define('PARAM_FORMAT',   'alphanumext');
289 /**
290  * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
291  * @deprecated since 2.0
292  */
293 define('PARAM_MULTILANG',  'text');
295 /**
296  * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
297  * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
298  * America/Port-au-Prince)
299  */
300 define('PARAM_TIMEZONE', 'timezone');
302 /**
303  * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
304  */
305 define('PARAM_CLEANFILE', 'file');
307 /**
308  * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
309  * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
310  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
311  * NOTE: numbers and underscores are strongly discouraged in plugin names!
312  */
313 define('PARAM_COMPONENT', 'component');
315 /**
316  * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
317  * It is usually used together with context id and component.
318  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
319  */
320 define('PARAM_AREA', 'area');
322 /**
323  * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
324  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
325  * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
326  */
327 define('PARAM_PLUGIN', 'plugin');
330 // Web Services.
332 /**
333  * VALUE_REQUIRED - if the parameter is not supplied, there is an error
334  */
335 define('VALUE_REQUIRED', 1);
337 /**
338  * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
339  */
340 define('VALUE_OPTIONAL', 2);
342 /**
343  * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
344  */
345 define('VALUE_DEFAULT', 0);
347 /**
348  * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
349  */
350 define('NULL_NOT_ALLOWED', false);
352 /**
353  * NULL_ALLOWED - the parameter can be set to null in the database
354  */
355 define('NULL_ALLOWED', true);
357 // Page types.
359 /**
360  * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
361  */
362 define('PAGE_COURSE_VIEW', 'course-view');
364 /** Get remote addr constant */
365 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
366 /** Get remote addr constant */
367 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
369 // Blog access level constant declaration.
370 define ('BLOG_USER_LEVEL', 1);
371 define ('BLOG_GROUP_LEVEL', 2);
372 define ('BLOG_COURSE_LEVEL', 3);
373 define ('BLOG_SITE_LEVEL', 4);
374 define ('BLOG_GLOBAL_LEVEL', 5);
377 // Tag constants.
378 /**
379  * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
380  * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
381  * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
382  *
383  * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
384  */
385 define('TAG_MAX_LENGTH', 50);
387 // Password policy constants.
388 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
389 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
390 define ('PASSWORD_DIGITS', '0123456789');
391 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
393 // Feature constants.
394 // Used for plugin_supports() to report features that are, or are not, supported by a module.
396 /** True if module can provide a grade */
397 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
398 /** True if module supports outcomes */
399 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
400 /** True if module supports advanced grading methods */
401 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
402 /** True if module controls the grade visibility over the gradebook */
403 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
404 /** True if module supports plagiarism plugins */
405 define('FEATURE_PLAGIARISM', 'plagiarism');
407 /** True if module has code to track whether somebody viewed it */
408 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
409 /** True if module has custom completion rules */
410 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
412 /** True if module has no 'view' page (like label) */
413 define('FEATURE_NO_VIEW_LINK', 'viewlink');
414 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
415 define('FEATURE_IDNUMBER', 'idnumber');
416 /** True if module supports groups */
417 define('FEATURE_GROUPS', 'groups');
418 /** True if module supports groupings */
419 define('FEATURE_GROUPINGS', 'groupings');
420 /**
421  * True if module supports groupmembersonly (which no longer exists)
422  * @deprecated Since Moodle 2.8
423  */
424 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
426 /** Type of module */
427 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
428 /** True if module supports intro editor */
429 define('FEATURE_MOD_INTRO', 'mod_intro');
430 /** True if module has default completion */
431 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
433 define('FEATURE_COMMENT', 'comment');
435 define('FEATURE_RATE', 'rate');
436 /** True if module supports backup/restore of moodle2 format */
437 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
439 /** True if module can show description on course main page */
440 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
442 /** True if module uses the question bank */
443 define('FEATURE_USES_QUESTIONS', 'usesquestions');
445 /**
446  * Maximum filename char size
447  */
448 define('MAX_FILENAME_SIZE', 100);
450 /** Unspecified module archetype */
451 define('MOD_ARCHETYPE_OTHER', 0);
452 /** Resource-like type module */
453 define('MOD_ARCHETYPE_RESOURCE', 1);
454 /** Assignment module archetype */
455 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
456 /** System (not user-addable) module archetype */
457 define('MOD_ARCHETYPE_SYSTEM', 3);
459 /**
460  * Security token used for allowing access
461  * from external application such as web services.
462  * Scripts do not use any session, performance is relatively
463  * low because we need to load access info in each request.
464  * Scripts are executed in parallel.
465  */
466 define('EXTERNAL_TOKEN_PERMANENT', 0);
468 /**
469  * Security token used for allowing access
470  * of embedded applications, the code is executed in the
471  * active user session. Token is invalidated after user logs out.
472  * Scripts are executed serially - normal session locking is used.
473  */
474 define('EXTERNAL_TOKEN_EMBEDDED', 1);
476 /**
477  * The home page should be the site home
478  */
479 define('HOMEPAGE_SITE', 0);
480 /**
481  * The home page should be the users my page
482  */
483 define('HOMEPAGE_MY', 1);
484 /**
485  * The home page can be chosen by the user
486  */
487 define('HOMEPAGE_USER', 2);
489 /**
490  * URL of the Moodle sites registration portal.
491  */
492 defined('HUB_MOODLEORGHUBURL') || define('HUB_MOODLEORGHUBURL', 'https://stats.moodle.org');
494 /**
495  * Moodle mobile app service name
496  */
497 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
499 /**
500  * Indicates the user has the capabilities required to ignore activity and course file size restrictions
501  */
502 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
504 /**
505  * Course display settings: display all sections on one page.
506  */
507 define('COURSE_DISPLAY_SINGLEPAGE', 0);
508 /**
509  * Course display settings: split pages into a page per section.
510  */
511 define('COURSE_DISPLAY_MULTIPAGE', 1);
513 /**
514  * Authentication constant: String used in password field when password is not stored.
515  */
516 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
518 /**
519  * Email from header to never include via information.
520  */
521 define('EMAIL_VIA_NEVER', 0);
523 /**
524  * Email from header to always include via information.
525  */
526 define('EMAIL_VIA_ALWAYS', 1);
528 /**
529  * Email from header to only include via information if the address is no-reply.
530  */
531 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
533 // PARAMETER HANDLING.
535 /**
536  * Returns a particular value for the named variable, taken from
537  * POST or GET.  If the parameter doesn't exist then an error is
538  * thrown because we require this variable.
539  *
540  * This function should be used to initialise all required values
541  * in a script that are based on parameters.  Usually it will be
542  * used like this:
543  *    $id = required_param('id', PARAM_INT);
544  *
545  * Please note the $type parameter is now required and the value can not be array.
546  *
547  * @param string $parname the name of the page parameter we want
548  * @param string $type expected type of parameter
549  * @return mixed
550  * @throws coding_exception
551  */
552 function required_param($parname, $type) {
553     if (func_num_args() != 2 or empty($parname) or empty($type)) {
554         throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
555     }
556     // POST has precedence.
557     if (isset($_POST[$parname])) {
558         $param = $_POST[$parname];
559     } else if (isset($_GET[$parname])) {
560         $param = $_GET[$parname];
561     } else {
562         print_error('missingparam', '', '', $parname);
563     }
565     if (is_array($param)) {
566         debugging('Invalid array parameter detected in required_param(): '.$parname);
567         // TODO: switch to fatal error in Moodle 2.3.
568         return required_param_array($parname, $type);
569     }
571     return clean_param($param, $type);
574 /**
575  * Returns a particular array value for the named variable, taken from
576  * POST or GET.  If the parameter doesn't exist then an error is
577  * thrown because we require this variable.
578  *
579  * This function should be used to initialise all required values
580  * in a script that are based on parameters.  Usually it will be
581  * used like this:
582  *    $ids = required_param_array('ids', PARAM_INT);
583  *
584  *  Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
585  *
586  * @param string $parname the name of the page parameter we want
587  * @param string $type expected type of parameter
588  * @return array
589  * @throws coding_exception
590  */
591 function required_param_array($parname, $type) {
592     if (func_num_args() != 2 or empty($parname) or empty($type)) {
593         throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
594     }
595     // POST has precedence.
596     if (isset($_POST[$parname])) {
597         $param = $_POST[$parname];
598     } else if (isset($_GET[$parname])) {
599         $param = $_GET[$parname];
600     } else {
601         print_error('missingparam', '', '', $parname);
602     }
603     if (!is_array($param)) {
604         print_error('missingparam', '', '', $parname);
605     }
607     $result = array();
608     foreach ($param as $key => $value) {
609         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
610             debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
611             continue;
612         }
613         $result[$key] = clean_param($value, $type);
614     }
616     return $result;
619 /**
620  * Returns a particular value for the named variable, taken from
621  * POST or GET, otherwise returning a given default.
622  *
623  * This function should be used to initialise all optional values
624  * in a script that are based on parameters.  Usually it will be
625  * used like this:
626  *    $name = optional_param('name', 'Fred', PARAM_TEXT);
627  *
628  * Please note the $type parameter is now required and the value can not be array.
629  *
630  * @param string $parname the name of the page parameter we want
631  * @param mixed  $default the default value to return if nothing is found
632  * @param string $type expected type of parameter
633  * @return mixed
634  * @throws coding_exception
635  */
636 function optional_param($parname, $default, $type) {
637     if (func_num_args() != 3 or empty($parname) or empty($type)) {
638         throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
639     }
641     // POST has precedence.
642     if (isset($_POST[$parname])) {
643         $param = $_POST[$parname];
644     } else if (isset($_GET[$parname])) {
645         $param = $_GET[$parname];
646     } else {
647         return $default;
648     }
650     if (is_array($param)) {
651         debugging('Invalid array parameter detected in required_param(): '.$parname);
652         // TODO: switch to $default in Moodle 2.3.
653         return optional_param_array($parname, $default, $type);
654     }
656     return clean_param($param, $type);
659 /**
660  * Returns a particular array value for the named variable, taken from
661  * POST or GET, otherwise returning a given default.
662  *
663  * This function should be used to initialise all optional values
664  * in a script that are based on parameters.  Usually it will be
665  * used like this:
666  *    $ids = optional_param('id', array(), PARAM_INT);
667  *
668  * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
669  *
670  * @param string $parname the name of the page parameter we want
671  * @param mixed $default the default value to return if nothing is found
672  * @param string $type expected type of parameter
673  * @return array
674  * @throws coding_exception
675  */
676 function optional_param_array($parname, $default, $type) {
677     if (func_num_args() != 3 or empty($parname) or empty($type)) {
678         throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
679     }
681     // POST has precedence.
682     if (isset($_POST[$parname])) {
683         $param = $_POST[$parname];
684     } else if (isset($_GET[$parname])) {
685         $param = $_GET[$parname];
686     } else {
687         return $default;
688     }
689     if (!is_array($param)) {
690         debugging('optional_param_array() expects array parameters only: '.$parname);
691         return $default;
692     }
694     $result = array();
695     foreach ($param as $key => $value) {
696         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
697             debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
698             continue;
699         }
700         $result[$key] = clean_param($value, $type);
701     }
703     return $result;
706 /**
707  * Strict validation of parameter values, the values are only converted
708  * to requested PHP type. Internally it is using clean_param, the values
709  * before and after cleaning must be equal - otherwise
710  * an invalid_parameter_exception is thrown.
711  * Objects and classes are not accepted.
712  *
713  * @param mixed $param
714  * @param string $type PARAM_ constant
715  * @param bool $allownull are nulls valid value?
716  * @param string $debuginfo optional debug information
717  * @return mixed the $param value converted to PHP type
718  * @throws invalid_parameter_exception if $param is not of given type
719  */
720 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
721     if (is_null($param)) {
722         if ($allownull == NULL_ALLOWED) {
723             return null;
724         } else {
725             throw new invalid_parameter_exception($debuginfo);
726         }
727     }
728     if (is_array($param) or is_object($param)) {
729         throw new invalid_parameter_exception($debuginfo);
730     }
732     $cleaned = clean_param($param, $type);
734     if ($type == PARAM_FLOAT) {
735         // Do not detect precision loss here.
736         if (is_float($param) or is_int($param)) {
737             // These always fit.
738         } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
739             throw new invalid_parameter_exception($debuginfo);
740         }
741     } else if ((string)$param !== (string)$cleaned) {
742         // Conversion to string is usually lossless.
743         throw new invalid_parameter_exception($debuginfo);
744     }
746     return $cleaned;
749 /**
750  * Makes sure array contains only the allowed types, this function does not validate array key names!
751  *
752  * <code>
753  * $options = clean_param($options, PARAM_INT);
754  * </code>
755  *
756  * @param array $param the variable array we are cleaning
757  * @param string $type expected format of param after cleaning.
758  * @param bool $recursive clean recursive arrays
759  * @return array
760  * @throws coding_exception
761  */
762 function clean_param_array(array $param = null, $type, $recursive = false) {
763     // Convert null to empty array.
764     $param = (array)$param;
765     foreach ($param as $key => $value) {
766         if (is_array($value)) {
767             if ($recursive) {
768                 $param[$key] = clean_param_array($value, $type, true);
769             } else {
770                 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
771             }
772         } else {
773             $param[$key] = clean_param($value, $type);
774         }
775     }
776     return $param;
779 /**
780  * Used by {@link optional_param()} and {@link required_param()} to
781  * clean the variables and/or cast to specific types, based on
782  * an options field.
783  * <code>
784  * $course->format = clean_param($course->format, PARAM_ALPHA);
785  * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
786  * </code>
787  *
788  * @param mixed $param the variable we are cleaning
789  * @param string $type expected format of param after cleaning.
790  * @return mixed
791  * @throws coding_exception
792  */
793 function clean_param($param, $type) {
794     global $CFG;
796     if (is_array($param)) {
797         throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
798     } else if (is_object($param)) {
799         if (method_exists($param, '__toString')) {
800             $param = $param->__toString();
801         } else {
802             throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
803         }
804     }
806     switch ($type) {
807         case PARAM_RAW:
808             // No cleaning at all.
809             $param = fix_utf8($param);
810             return $param;
812         case PARAM_RAW_TRIMMED:
813             // No cleaning, but strip leading and trailing whitespace.
814             $param = fix_utf8($param);
815             return trim($param);
817         case PARAM_CLEAN:
818             // General HTML cleaning, try to use more specific type if possible this is deprecated!
819             // Please use more specific type instead.
820             if (is_numeric($param)) {
821                 return $param;
822             }
823             $param = fix_utf8($param);
824             // Sweep for scripts, etc.
825             return clean_text($param);
827         case PARAM_CLEANHTML:
828             // Clean html fragment.
829             $param = fix_utf8($param);
830             // Sweep for scripts, etc.
831             $param = clean_text($param, FORMAT_HTML);
832             return trim($param);
834         case PARAM_INT:
835             // Convert to integer.
836             return (int)$param;
838         case PARAM_FLOAT:
839             // Convert to float.
840             return (float)$param;
842         case PARAM_LOCALISEDFLOAT:
843             // Convert to float.
844             return unformat_float($param, true);
846         case PARAM_ALPHA:
847             // Remove everything not `a-z`.
848             return preg_replace('/[^a-zA-Z]/i', '', $param);
850         case PARAM_ALPHAEXT:
851             // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
852             return preg_replace('/[^a-zA-Z_-]/i', '', $param);
854         case PARAM_ALPHANUM:
855             // Remove everything not `a-zA-Z0-9`.
856             return preg_replace('/[^A-Za-z0-9]/i', '', $param);
858         case PARAM_ALPHANUMEXT:
859             // Remove everything not `a-zA-Z0-9_-`.
860             return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
862         case PARAM_SEQUENCE:
863             // Remove everything not `0-9,`.
864             return preg_replace('/[^0-9,]/i', '', $param);
866         case PARAM_BOOL:
867             // Convert to 1 or 0.
868             $tempstr = strtolower($param);
869             if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
870                 $param = 1;
871             } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
872                 $param = 0;
873             } else {
874                 $param = empty($param) ? 0 : 1;
875             }
876             return $param;
878         case PARAM_NOTAGS:
879             // Strip all tags.
880             $param = fix_utf8($param);
881             return strip_tags($param);
883         case PARAM_TEXT:
884             // Leave only tags needed for multilang.
885             $param = fix_utf8($param);
886             // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
887             // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
888             do {
889                 if (strpos($param, '</lang>') !== false) {
890                     // Old and future mutilang syntax.
891                     $param = strip_tags($param, '<lang>');
892                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
893                         break;
894                     }
895                     $open = false;
896                     foreach ($matches[0] as $match) {
897                         if ($match === '</lang>') {
898                             if ($open) {
899                                 $open = false;
900                                 continue;
901                             } else {
902                                 break 2;
903                             }
904                         }
905                         if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
906                             break 2;
907                         } else {
908                             $open = true;
909                         }
910                     }
911                     if ($open) {
912                         break;
913                     }
914                     return $param;
916                 } else if (strpos($param, '</span>') !== false) {
917                     // Current problematic multilang syntax.
918                     $param = strip_tags($param, '<span>');
919                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
920                         break;
921                     }
922                     $open = false;
923                     foreach ($matches[0] as $match) {
924                         if ($match === '</span>') {
925                             if ($open) {
926                                 $open = false;
927                                 continue;
928                             } else {
929                                 break 2;
930                             }
931                         }
932                         if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
933                             break 2;
934                         } else {
935                             $open = true;
936                         }
937                     }
938                     if ($open) {
939                         break;
940                     }
941                     return $param;
942                 }
943             } while (false);
944             // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
945             return strip_tags($param);
947         case PARAM_COMPONENT:
948             // We do not want any guessing here, either the name is correct or not
949             // please note only normalised component names are accepted.
950             if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
951                 return '';
952             }
953             if (strpos($param, '__') !== false) {
954                 return '';
955             }
956             if (strpos($param, 'mod_') === 0) {
957                 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
958                 if (substr_count($param, '_') != 1) {
959                     return '';
960                 }
961             }
962             return $param;
964         case PARAM_PLUGIN:
965         case PARAM_AREA:
966             // We do not want any guessing here, either the name is correct or not.
967             if (!is_valid_plugin_name($param)) {
968                 return '';
969             }
970             return $param;
972         case PARAM_SAFEDIR:
973             // Remove everything not a-zA-Z0-9_- .
974             return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
976         case PARAM_SAFEPATH:
977             // Remove everything not a-zA-Z0-9/_- .
978             return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
980         case PARAM_FILE:
981             // Strip all suspicious characters from filename.
982             $param = fix_utf8($param);
983             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
984             if ($param === '.' || $param === '..') {
985                 $param = '';
986             }
987             return $param;
989         case PARAM_PATH:
990             // Strip all suspicious characters from file path.
991             $param = fix_utf8($param);
992             $param = str_replace('\\', '/', $param);
994             // Explode the path and clean each element using the PARAM_FILE rules.
995             $breadcrumb = explode('/', $param);
996             foreach ($breadcrumb as $key => $crumb) {
997                 if ($crumb === '.' && $key === 0) {
998                     // Special condition to allow for relative current path such as ./currentdirfile.txt.
999                 } else {
1000                     $crumb = clean_param($crumb, PARAM_FILE);
1001                 }
1002                 $breadcrumb[$key] = $crumb;
1003             }
1004             $param = implode('/', $breadcrumb);
1006             // Remove multiple current path (./././) and multiple slashes (///).
1007             $param = preg_replace('~//+~', '/', $param);
1008             $param = preg_replace('~/(\./)+~', '/', $param);
1009             return $param;
1011         case PARAM_HOST:
1012             // Allow FQDN or IPv4 dotted quad.
1013             $param = preg_replace('/[^\.\d\w-]/', '', $param );
1014             // Match ipv4 dotted quad.
1015             if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1016                 // Confirm values are ok.
1017                 if ( $match[0] > 255
1018                      || $match[1] > 255
1019                      || $match[3] > 255
1020                      || $match[4] > 255 ) {
1021                     // Hmmm, what kind of dotted quad is this?
1022                     $param = '';
1023                 }
1024             } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1025                        && !preg_match('/^[\.-]/',  $param) // No leading dots/hyphens.
1026                        && !preg_match('/[\.-]$/',  $param) // No trailing dots/hyphens.
1027                        ) {
1028                 // All is ok - $param is respected.
1029             } else {
1030                 // All is not ok...
1031                 $param='';
1032             }
1033             return $param;
1035         case PARAM_URL:
1036             // Allow safe urls.
1037             $param = fix_utf8($param);
1038             include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1039             if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1040                 // All is ok, param is respected.
1041             } else {
1042                 // Not really ok.
1043                 $param ='';
1044             }
1045             return $param;
1047         case PARAM_LOCALURL:
1048             // Allow http absolute, root relative and relative URLs within wwwroot.
1049             $param = clean_param($param, PARAM_URL);
1050             if (!empty($param)) {
1052                 if ($param === $CFG->wwwroot) {
1053                     // Exact match;
1054                 } else if (preg_match(':^/:', $param)) {
1055                     // Root-relative, ok!
1056                 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1057                     // Absolute, and matches our wwwroot.
1058                 } else {
1059                     // Relative - let's make sure there are no tricks.
1060                     if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1061                         // Looks ok.
1062                     } else {
1063                         $param = '';
1064                     }
1065                 }
1066             }
1067             return $param;
1069         case PARAM_PEM:
1070             $param = trim($param);
1071             // PEM formatted strings may contain letters/numbers and the symbols:
1072             //   forward slash: /
1073             //   plus sign:     +
1074             //   equal sign:    =
1075             //   , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1076             if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1077                 list($wholething, $body) = $matches;
1078                 unset($wholething, $matches);
1079                 $b64 = clean_param($body, PARAM_BASE64);
1080                 if (!empty($b64)) {
1081                     return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1082                 } else {
1083                     return '';
1084                 }
1085             }
1086             return '';
1088         case PARAM_BASE64:
1089             if (!empty($param)) {
1090                 // PEM formatted strings may contain letters/numbers and the symbols
1091                 //   forward slash: /
1092                 //   plus sign:     +
1093                 //   equal sign:    =.
1094                 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1095                     return '';
1096                 }
1097                 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1098                 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1099                 // than (or equal to) 64 characters long.
1100                 for ($i=0, $j=count($lines); $i < $j; $i++) {
1101                     if ($i + 1 == $j) {
1102                         if (64 < strlen($lines[$i])) {
1103                             return '';
1104                         }
1105                         continue;
1106                     }
1108                     if (64 != strlen($lines[$i])) {
1109                         return '';
1110                     }
1111                 }
1112                 return implode("\n", $lines);
1113             } else {
1114                 return '';
1115             }
1117         case PARAM_TAG:
1118             $param = fix_utf8($param);
1119             // Please note it is not safe to use the tag name directly anywhere,
1120             // it must be processed with s(), urlencode() before embedding anywhere.
1121             // Remove some nasties.
1122             $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1123             // Convert many whitespace chars into one.
1124             $param = preg_replace('/\s+/u', ' ', $param);
1125             $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1126             return $param;
1128         case PARAM_TAGLIST:
1129             $param = fix_utf8($param);
1130             $tags = explode(',', $param);
1131             $result = array();
1132             foreach ($tags as $tag) {
1133                 $res = clean_param($tag, PARAM_TAG);
1134                 if ($res !== '') {
1135                     $result[] = $res;
1136                 }
1137             }
1138             if ($result) {
1139                 return implode(',', $result);
1140             } else {
1141                 return '';
1142             }
1144         case PARAM_CAPABILITY:
1145             if (get_capability_info($param)) {
1146                 return $param;
1147             } else {
1148                 return '';
1149             }
1151         case PARAM_PERMISSION:
1152             $param = (int)$param;
1153             if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1154                 return $param;
1155             } else {
1156                 return CAP_INHERIT;
1157             }
1159         case PARAM_AUTH:
1160             $param = clean_param($param, PARAM_PLUGIN);
1161             if (empty($param)) {
1162                 return '';
1163             } else if (exists_auth_plugin($param)) {
1164                 return $param;
1165             } else {
1166                 return '';
1167             }
1169         case PARAM_LANG:
1170             $param = clean_param($param, PARAM_SAFEDIR);
1171             if (get_string_manager()->translation_exists($param)) {
1172                 return $param;
1173             } else {
1174                 // Specified language is not installed or param malformed.
1175                 return '';
1176             }
1178         case PARAM_THEME:
1179             $param = clean_param($param, PARAM_PLUGIN);
1180             if (empty($param)) {
1181                 return '';
1182             } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1183                 return $param;
1184             } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1185                 return $param;
1186             } else {
1187                 // Specified theme is not installed.
1188                 return '';
1189             }
1191         case PARAM_USERNAME:
1192             $param = fix_utf8($param);
1193             $param = trim($param);
1194             // Convert uppercase to lowercase MDL-16919.
1195             $param = core_text::strtolower($param);
1196             if (empty($CFG->extendedusernamechars)) {
1197                 $param = str_replace(" " , "", $param);
1198                 // Regular expression, eliminate all chars EXCEPT:
1199                 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1200                 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1201             }
1202             return $param;
1204         case PARAM_EMAIL:
1205             $param = fix_utf8($param);
1206             if (validate_email($param)) {
1207                 return $param;
1208             } else {
1209                 return '';
1210             }
1212         case PARAM_STRINGID:
1213             if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1214                 return $param;
1215             } else {
1216                 return '';
1217             }
1219         case PARAM_TIMEZONE:
1220             // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1221             $param = fix_utf8($param);
1222             $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1223             if (preg_match($timezonepattern, $param)) {
1224                 return $param;
1225             } else {
1226                 return '';
1227             }
1229         default:
1230             // Doh! throw error, switched parameters in optional_param or another serious problem.
1231             print_error("unknownparamtype", '', '', $type);
1232     }
1235 /**
1236  * Whether the PARAM_* type is compatible in RTL.
1237  *
1238  * Being compatible with RTL means that the data they contain can flow
1239  * from right-to-left or left-to-right without compromising the user experience.
1240  *
1241  * Take URLs for example, they are not RTL compatible as they should always
1242  * flow from the left to the right. This also applies to numbers, email addresses,
1243  * configuration snippets, base64 strings, etc...
1244  *
1245  * This function tries to best guess which parameters can contain localised strings.
1246  *
1247  * @param string $paramtype Constant PARAM_*.
1248  * @return bool
1249  */
1250 function is_rtl_compatible($paramtype) {
1251     return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1254 /**
1255  * Makes sure the data is using valid utf8, invalid characters are discarded.
1256  *
1257  * Note: this function is not intended for full objects with methods and private properties.
1258  *
1259  * @param mixed $value
1260  * @return mixed with proper utf-8 encoding
1261  */
1262 function fix_utf8($value) {
1263     if (is_null($value) or $value === '') {
1264         return $value;
1266     } else if (is_string($value)) {
1267         if ((string)(int)$value === $value) {
1268             // Shortcut.
1269             return $value;
1270         }
1271         // No null bytes expected in our data, so let's remove it.
1272         $value = str_replace("\0", '', $value);
1274         // Note: this duplicates min_fix_utf8() intentionally.
1275         static $buggyiconv = null;
1276         if ($buggyiconv === null) {
1277             $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1278         }
1280         if ($buggyiconv) {
1281             if (function_exists('mb_convert_encoding')) {
1282                 $subst = mb_substitute_character();
1283                 mb_substitute_character('');
1284                 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1285                 mb_substitute_character($subst);
1287             } else {
1288                 // Warn admins on admin/index.php page.
1289                 $result = $value;
1290             }
1292         } else {
1293             $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1294         }
1296         return $result;
1298     } else if (is_array($value)) {
1299         foreach ($value as $k => $v) {
1300             $value[$k] = fix_utf8($v);
1301         }
1302         return $value;
1304     } else if (is_object($value)) {
1305         // Do not modify original.
1306         $value = clone($value);
1307         foreach ($value as $k => $v) {
1308             $value->$k = fix_utf8($v);
1309         }
1310         return $value;
1312     } else {
1313         // This is some other type, no utf-8 here.
1314         return $value;
1315     }
1318 /**
1319  * Return true if given value is integer or string with integer value
1320  *
1321  * @param mixed $value String or Int
1322  * @return bool true if number, false if not
1323  */
1324 function is_number($value) {
1325     if (is_int($value)) {
1326         return true;
1327     } else if (is_string($value)) {
1328         return ((string)(int)$value) === $value;
1329     } else {
1330         return false;
1331     }
1334 /**
1335  * Returns host part from url.
1336  *
1337  * @param string $url full url
1338  * @return string host, null if not found
1339  */
1340 function get_host_from_url($url) {
1341     preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1342     if ($matches) {
1343         return $matches[1];
1344     }
1345     return null;
1348 /**
1349  * Tests whether anything was returned by text editor
1350  *
1351  * This function is useful for testing whether something you got back from
1352  * the HTML editor actually contains anything. Sometimes the HTML editor
1353  * appear to be empty, but actually you get back a <br> tag or something.
1354  *
1355  * @param string $string a string containing HTML.
1356  * @return boolean does the string contain any actual content - that is text,
1357  * images, objects, etc.
1358  */
1359 function html_is_blank($string) {
1360     return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1363 /**
1364  * Set a key in global configuration
1365  *
1366  * Set a key/value pair in both this session's {@link $CFG} global variable
1367  * and in the 'config' database table for future sessions.
1368  *
1369  * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1370  * In that case it doesn't affect $CFG.
1371  *
1372  * A NULL value will delete the entry.
1373  *
1374  * NOTE: this function is called from lib/db/upgrade.php
1375  *
1376  * @param string $name the key to set
1377  * @param string $value the value to set (without magic quotes)
1378  * @param string $plugin (optional) the plugin scope, default null
1379  * @return bool true or exception
1380  */
1381 function set_config($name, $value, $plugin=null) {
1382     global $CFG, $DB;
1384     if (empty($plugin)) {
1385         if (!array_key_exists($name, $CFG->config_php_settings)) {
1386             // So it's defined for this invocation at least.
1387             if (is_null($value)) {
1388                 unset($CFG->$name);
1389             } else {
1390                 // Settings from db are always strings.
1391                 $CFG->$name = (string)$value;
1392             }
1393         }
1395         if ($DB->get_field('config', 'name', array('name' => $name))) {
1396             if ($value === null) {
1397                 $DB->delete_records('config', array('name' => $name));
1398             } else {
1399                 $DB->set_field('config', 'value', $value, array('name' => $name));
1400             }
1401         } else {
1402             if ($value !== null) {
1403                 $config = new stdClass();
1404                 $config->name  = $name;
1405                 $config->value = $value;
1406                 $DB->insert_record('config', $config, false);
1407             }
1408             // When setting config during a Behat test (in the CLI script, not in the web browser
1409             // requests), remember which ones are set so that we can clear them later.
1410             if (defined('BEHAT_TEST')) {
1411                 if (!property_exists($CFG, 'behat_cli_added_config')) {
1412                     $CFG->behat_cli_added_config = [];
1413                 }
1414                 $CFG->behat_cli_added_config[$name] = true;
1415             }
1416         }
1417         if ($name === 'siteidentifier') {
1418             cache_helper::update_site_identifier($value);
1419         }
1420         cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1421     } else {
1422         // Plugin scope.
1423         if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1424             if ($value===null) {
1425                 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1426             } else {
1427                 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1428             }
1429         } else {
1430             if ($value !== null) {
1431                 $config = new stdClass();
1432                 $config->plugin = $plugin;
1433                 $config->name   = $name;
1434                 $config->value  = $value;
1435                 $DB->insert_record('config_plugins', $config, false);
1436             }
1437         }
1438         cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1439     }
1441     return true;
1444 /**
1445  * Get configuration values from the global config table
1446  * or the config_plugins table.
1447  *
1448  * If called with one parameter, it will load all the config
1449  * variables for one plugin, and return them as an object.
1450  *
1451  * If called with 2 parameters it will return a string single
1452  * value or false if the value is not found.
1453  *
1454  * NOTE: this function is called from lib/db/upgrade.php
1455  *
1456  * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1457  *     that we need only fetch it once per request.
1458  * @param string $plugin full component name
1459  * @param string $name default null
1460  * @return mixed hash-like object or single value, return false no config found
1461  * @throws dml_exception
1462  */
1463 function get_config($plugin, $name = null) {
1464     global $CFG, $DB;
1466     static $siteidentifier = null;
1468     if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1469         $forced =& $CFG->config_php_settings;
1470         $iscore = true;
1471         $plugin = 'core';
1472     } else {
1473         if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1474             $forced =& $CFG->forced_plugin_settings[$plugin];
1475         } else {
1476             $forced = array();
1477         }
1478         $iscore = false;
1479     }
1481     if ($siteidentifier === null) {
1482         try {
1483             // This may fail during installation.
1484             // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1485             // install the database.
1486             $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1487         } catch (dml_exception $ex) {
1488             // Set siteidentifier to false. We don't want to trip this continually.
1489             $siteidentifier = false;
1490             throw $ex;
1491         }
1492     }
1494     if (!empty($name)) {
1495         if (array_key_exists($name, $forced)) {
1496             return (string)$forced[$name];
1497         } else if ($name === 'siteidentifier' && $plugin == 'core') {
1498             return $siteidentifier;
1499         }
1500     }
1502     $cache = cache::make('core', 'config');
1503     $result = $cache->get($plugin);
1504     if ($result === false) {
1505         // The user is after a recordset.
1506         if (!$iscore) {
1507             $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1508         } else {
1509             // This part is not really used any more, but anyway...
1510             $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1511         }
1512         $cache->set($plugin, $result);
1513     }
1515     if (!empty($name)) {
1516         if (array_key_exists($name, $result)) {
1517             return $result[$name];
1518         }
1519         return false;
1520     }
1522     if ($plugin === 'core') {
1523         $result['siteidentifier'] = $siteidentifier;
1524     }
1526     foreach ($forced as $key => $value) {
1527         if (is_null($value) or is_array($value) or is_object($value)) {
1528             // We do not want any extra mess here, just real settings that could be saved in db.
1529             unset($result[$key]);
1530         } else {
1531             // Convert to string as if it went through the DB.
1532             $result[$key] = (string)$value;
1533         }
1534     }
1536     return (object)$result;
1539 /**
1540  * Removes a key from global configuration.
1541  *
1542  * NOTE: this function is called from lib/db/upgrade.php
1543  *
1544  * @param string $name the key to set
1545  * @param string $plugin (optional) the plugin scope
1546  * @return boolean whether the operation succeeded.
1547  */
1548 function unset_config($name, $plugin=null) {
1549     global $CFG, $DB;
1551     if (empty($plugin)) {
1552         unset($CFG->$name);
1553         $DB->delete_records('config', array('name' => $name));
1554         cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1555     } else {
1556         $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1557         cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1558     }
1560     return true;
1563 /**
1564  * Remove all the config variables for a given plugin.
1565  *
1566  * NOTE: this function is called from lib/db/upgrade.php
1567  *
1568  * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1569  * @return boolean whether the operation succeeded.
1570  */
1571 function unset_all_config_for_plugin($plugin) {
1572     global $DB;
1573     // Delete from the obvious config_plugins first.
1574     $DB->delete_records('config_plugins', array('plugin' => $plugin));
1575     // Next delete any suspect settings from config.
1576     $like = $DB->sql_like('name', '?', true, true, false, '|');
1577     $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1578     $DB->delete_records_select('config', $like, $params);
1579     // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1580     cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1582     return true;
1585 /**
1586  * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1587  *
1588  * All users are verified if they still have the necessary capability.
1589  *
1590  * @param string $value the value of the config setting.
1591  * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1592  * @param bool $includeadmins include administrators.
1593  * @return array of user objects.
1594  */
1595 function get_users_from_config($value, $capability, $includeadmins = true) {
1596     if (empty($value) or $value === '$@NONE@$') {
1597         return array();
1598     }
1600     // We have to make sure that users still have the necessary capability,
1601     // it should be faster to fetch them all first and then test if they are present
1602     // instead of validating them one-by-one.
1603     $users = get_users_by_capability(context_system::instance(), $capability);
1604     if ($includeadmins) {
1605         $admins = get_admins();
1606         foreach ($admins as $admin) {
1607             $users[$admin->id] = $admin;
1608         }
1609     }
1611     if ($value === '$@ALL@$') {
1612         return $users;
1613     }
1615     $result = array(); // Result in correct order.
1616     $allowed = explode(',', $value);
1617     foreach ($allowed as $uid) {
1618         if (isset($users[$uid])) {
1619             $user = $users[$uid];
1620             $result[$user->id] = $user;
1621         }
1622     }
1624     return $result;
1628 /**
1629  * Invalidates browser caches and cached data in temp.
1630  *
1631  * @return void
1632  */
1633 function purge_all_caches() {
1634     purge_caches();
1637 /**
1638  * Selectively invalidate different types of cache.
1639  *
1640  * Purges the cache areas specified.  By default, this will purge all caches but can selectively purge specific
1641  * areas alone or in combination.
1642  *
1643  * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1644  *        'muc'    Purge MUC caches?
1645  *        'theme'  Purge theme cache?
1646  *        'lang'   Purge language string cache?
1647  *        'js'     Purge javascript cache?
1648  *        'filter' Purge text filter cache?
1649  *        'other'  Purge all other caches?
1650  */
1651 function purge_caches($options = []) {
1652     $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1653     if (empty(array_filter($options))) {
1654         $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1655     } else {
1656         $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1657     }
1658     if ($options['muc']) {
1659         cache_helper::purge_all();
1660     }
1661     if ($options['theme']) {
1662         theme_reset_all_caches();
1663     }
1664     if ($options['lang']) {
1665         get_string_manager()->reset_caches();
1666     }
1667     if ($options['js']) {
1668         js_reset_all_caches();
1669     }
1670     if ($options['template']) {
1671         template_reset_all_caches();
1672     }
1673     if ($options['filter']) {
1674         reset_text_filters_cache();
1675     }
1676     if ($options['other']) {
1677         purge_other_caches();
1678     }
1681 /**
1682  * Purge all non-MUC caches not otherwise purged in purge_caches.
1683  *
1684  * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1685  * {@link phpunit_util::reset_dataroot()}
1686  */
1687 function purge_other_caches() {
1688     global $DB, $CFG;
1689     core_text::reset_caches();
1690     if (class_exists('core_plugin_manager')) {
1691         core_plugin_manager::reset_caches();
1692     }
1694     // Bump up cacherev field for all courses.
1695     try {
1696         increment_revision_number('course', 'cacherev', '');
1697     } catch (moodle_exception $e) {
1698         // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1699     }
1701     $DB->reset_caches();
1703     // Purge all other caches: rss, simplepie, etc.
1704     clearstatcache();
1705     remove_dir($CFG->cachedir.'', true);
1707     // Make sure cache dir is writable, throws exception if not.
1708     make_cache_directory('');
1710     // This is the only place where we purge local caches, we are only adding files there.
1711     // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1712     remove_dir($CFG->localcachedir, true);
1713     set_config('localcachedirpurged', time());
1714     make_localcache_directory('', true);
1715     \core\task\manager::clear_static_caches();
1718 /**
1719  * Get volatile flags
1720  *
1721  * @param string $type
1722  * @param int $changedsince default null
1723  * @return array records array
1724  */
1725 function get_cache_flags($type, $changedsince = null) {
1726     global $DB;
1728     $params = array('type' => $type, 'expiry' => time());
1729     $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1730     if ($changedsince !== null) {
1731         $params['changedsince'] = $changedsince;
1732         $sqlwhere .= " AND timemodified > :changedsince";
1733     }
1734     $cf = array();
1735     if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1736         foreach ($flags as $flag) {
1737             $cf[$flag->name] = $flag->value;
1738         }
1739     }
1740     return $cf;
1743 /**
1744  * Get volatile flags
1745  *
1746  * @param string $type
1747  * @param string $name
1748  * @param int $changedsince default null
1749  * @return string|false The cache flag value or false
1750  */
1751 function get_cache_flag($type, $name, $changedsince=null) {
1752     global $DB;
1754     $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1756     $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1757     if ($changedsince !== null) {
1758         $params['changedsince'] = $changedsince;
1759         $sqlwhere .= " AND timemodified > :changedsince";
1760     }
1762     return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1765 /**
1766  * Set a volatile flag
1767  *
1768  * @param string $type the "type" namespace for the key
1769  * @param string $name the key to set
1770  * @param string $value the value to set (without magic quotes) - null will remove the flag
1771  * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1772  * @return bool Always returns true
1773  */
1774 function set_cache_flag($type, $name, $value, $expiry = null) {
1775     global $DB;
1777     $timemodified = time();
1778     if ($expiry === null || $expiry < $timemodified) {
1779         $expiry = $timemodified + 24 * 60 * 60;
1780     } else {
1781         $expiry = (int)$expiry;
1782     }
1784     if ($value === null) {
1785         unset_cache_flag($type, $name);
1786         return true;
1787     }
1789     if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1790         // This is a potential problem in DEBUG_DEVELOPER.
1791         if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1792             return true; // No need to update.
1793         }
1794         $f->value        = $value;
1795         $f->expiry       = $expiry;
1796         $f->timemodified = $timemodified;
1797         $DB->update_record('cache_flags', $f);
1798     } else {
1799         $f = new stdClass();
1800         $f->flagtype     = $type;
1801         $f->name         = $name;
1802         $f->value        = $value;
1803         $f->expiry       = $expiry;
1804         $f->timemodified = $timemodified;
1805         $DB->insert_record('cache_flags', $f);
1806     }
1807     return true;
1810 /**
1811  * Removes a single volatile flag
1812  *
1813  * @param string $type the "type" namespace for the key
1814  * @param string $name the key to set
1815  * @return bool
1816  */
1817 function unset_cache_flag($type, $name) {
1818     global $DB;
1819     $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1820     return true;
1823 /**
1824  * Garbage-collect volatile flags
1825  *
1826  * @return bool Always returns true
1827  */
1828 function gc_cache_flags() {
1829     global $DB;
1830     $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1831     return true;
1834 // USER PREFERENCE API.
1836 /**
1837  * Refresh user preference cache. This is used most often for $USER
1838  * object that is stored in session, but it also helps with performance in cron script.
1839  *
1840  * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1841  *
1842  * @package  core
1843  * @category preference
1844  * @access   public
1845  * @param    stdClass         $user          User object. Preferences are preloaded into 'preference' property
1846  * @param    int              $cachelifetime Cache life time on the current page (in seconds)
1847  * @throws   coding_exception
1848  * @return   null
1849  */
1850 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1851     global $DB;
1852     // Static cache, we need to check on each page load, not only every 2 minutes.
1853     static $loadedusers = array();
1855     if (!isset($user->id)) {
1856         throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1857     }
1859     if (empty($user->id) or isguestuser($user->id)) {
1860         // No permanent storage for not-logged-in users and guest.
1861         if (!isset($user->preference)) {
1862             $user->preference = array();
1863         }
1864         return;
1865     }
1867     $timenow = time();
1869     if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1870         // Already loaded at least once on this page. Are we up to date?
1871         if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1872             // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1873             return;
1875         } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1876             // No change since the lastcheck on this page.
1877             $user->preference['_lastloaded'] = $timenow;
1878             return;
1879         }
1880     }
1882     // OK, so we have to reload all preferences.
1883     $loadedusers[$user->id] = true;
1884     $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1885     $user->preference['_lastloaded'] = $timenow;
1888 /**
1889  * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1890  *
1891  * NOTE: internal function, do not call from other code.
1892  *
1893  * @package core
1894  * @access private
1895  * @param integer $userid the user whose prefs were changed.
1896  */
1897 function mark_user_preferences_changed($userid) {
1898     global $CFG;
1900     if (empty($userid) or isguestuser($userid)) {
1901         // No cache flags for guest and not-logged-in users.
1902         return;
1903     }
1905     set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1908 /**
1909  * Sets a preference for the specified user.
1910  *
1911  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1912  *
1913  * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1914  *
1915  * @package  core
1916  * @category preference
1917  * @access   public
1918  * @param    string            $name  The key to set as preference for the specified user
1919  * @param    string            $value The value to set for the $name key in the specified user's
1920  *                                    record, null means delete current value.
1921  * @param    stdClass|int|null $user  A moodle user object or id, null means current user
1922  * @throws   coding_exception
1923  * @return   bool                     Always true or exception
1924  */
1925 function set_user_preference($name, $value, $user = null) {
1926     global $USER, $DB;
1928     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1929         throw new coding_exception('Invalid preference name in set_user_preference() call');
1930     }
1932     if (is_null($value)) {
1933         // Null means delete current.
1934         return unset_user_preference($name, $user);
1935     } else if (is_object($value)) {
1936         throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1937     } else if (is_array($value)) {
1938         throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1939     }
1940     // Value column maximum length is 1333 characters.
1941     $value = (string)$value;
1942     if (core_text::strlen($value) > 1333) {
1943         throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1944     }
1946     if (is_null($user)) {
1947         $user = $USER;
1948     } else if (isset($user->id)) {
1949         // It is a valid object.
1950     } else if (is_numeric($user)) {
1951         $user = (object)array('id' => (int)$user);
1952     } else {
1953         throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1954     }
1956     check_user_preferences_loaded($user);
1958     if (empty($user->id) or isguestuser($user->id)) {
1959         // No permanent storage for not-logged-in users and guest.
1960         $user->preference[$name] = $value;
1961         return true;
1962     }
1964     if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1965         if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1966             // Preference already set to this value.
1967             return true;
1968         }
1969         $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1971     } else {
1972         $preference = new stdClass();
1973         $preference->userid = $user->id;
1974         $preference->name   = $name;
1975         $preference->value  = $value;
1976         $DB->insert_record('user_preferences', $preference);
1977     }
1979     // Update value in cache.
1980     $user->preference[$name] = $value;
1981     // Update the $USER in case where we've not a direct reference to $USER.
1982     if ($user !== $USER && $user->id == $USER->id) {
1983         $USER->preference[$name] = $value;
1984     }
1986     // Set reload flag for other sessions.
1987     mark_user_preferences_changed($user->id);
1989     return true;
1992 /**
1993  * Sets a whole array of preferences for the current user
1994  *
1995  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1996  *
1997  * @package  core
1998  * @category preference
1999  * @access   public
2000  * @param    array             $prefarray An array of key/value pairs to be set
2001  * @param    stdClass|int|null $user      A moodle user object or id, null means current user
2002  * @return   bool                         Always true or exception
2003  */
2004 function set_user_preferences(array $prefarray, $user = null) {
2005     foreach ($prefarray as $name => $value) {
2006         set_user_preference($name, $value, $user);
2007     }
2008     return true;
2011 /**
2012  * Unsets a preference completely by deleting it from the database
2013  *
2014  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2015  *
2016  * @package  core
2017  * @category preference
2018  * @access   public
2019  * @param    string            $name The key to unset as preference for the specified user
2020  * @param    stdClass|int|null $user A moodle user object or id, null means current user
2021  * @throws   coding_exception
2022  * @return   bool                    Always true or exception
2023  */
2024 function unset_user_preference($name, $user = null) {
2025     global $USER, $DB;
2027     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2028         throw new coding_exception('Invalid preference name in unset_user_preference() call');
2029     }
2031     if (is_null($user)) {
2032         $user = $USER;
2033     } else if (isset($user->id)) {
2034         // It is a valid object.
2035     } else if (is_numeric($user)) {
2036         $user = (object)array('id' => (int)$user);
2037     } else {
2038         throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2039     }
2041     check_user_preferences_loaded($user);
2043     if (empty($user->id) or isguestuser($user->id)) {
2044         // No permanent storage for not-logged-in user and guest.
2045         unset($user->preference[$name]);
2046         return true;
2047     }
2049     // Delete from DB.
2050     $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2052     // Delete the preference from cache.
2053     unset($user->preference[$name]);
2054     // Update the $USER in case where we've not a direct reference to $USER.
2055     if ($user !== $USER && $user->id == $USER->id) {
2056         unset($USER->preference[$name]);
2057     }
2059     // Set reload flag for other sessions.
2060     mark_user_preferences_changed($user->id);
2062     return true;
2065 /**
2066  * Used to fetch user preference(s)
2067  *
2068  * If no arguments are supplied this function will return
2069  * all of the current user preferences as an array.
2070  *
2071  * If a name is specified then this function
2072  * attempts to return that particular preference value.  If
2073  * none is found, then the optional value $default is returned,
2074  * otherwise null.
2075  *
2076  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2077  *
2078  * @package  core
2079  * @category preference
2080  * @access   public
2081  * @param    string            $name    Name of the key to use in finding a preference value
2082  * @param    mixed|null        $default Value to be returned if the $name key is not set in the user preferences
2083  * @param    stdClass|int|null $user    A moodle user object or id, null means current user
2084  * @throws   coding_exception
2085  * @return   string|mixed|null          A string containing the value of a single preference. An
2086  *                                      array with all of the preferences or null
2087  */
2088 function get_user_preferences($name = null, $default = null, $user = null) {
2089     global $USER;
2091     if (is_null($name)) {
2092         // All prefs.
2093     } else if (is_numeric($name) or $name === '_lastloaded') {
2094         throw new coding_exception('Invalid preference name in get_user_preferences() call');
2095     }
2097     if (is_null($user)) {
2098         $user = $USER;
2099     } else if (isset($user->id)) {
2100         // Is a valid object.
2101     } else if (is_numeric($user)) {
2102         if ($USER->id == $user) {
2103             $user = $USER;
2104         } else {
2105             $user = (object)array('id' => (int)$user);
2106         }
2107     } else {
2108         throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2109     }
2111     check_user_preferences_loaded($user);
2113     if (empty($name)) {
2114         // All values.
2115         return $user->preference;
2116     } else if (isset($user->preference[$name])) {
2117         // The single string value.
2118         return $user->preference[$name];
2119     } else {
2120         // Default value (null if not specified).
2121         return $default;
2122     }
2125 // FUNCTIONS FOR HANDLING TIME.
2127 /**
2128  * Given Gregorian date parts in user time produce a GMT timestamp.
2129  *
2130  * @package core
2131  * @category time
2132  * @param int $year The year part to create timestamp of
2133  * @param int $month The month part to create timestamp of
2134  * @param int $day The day part to create timestamp of
2135  * @param int $hour The hour part to create timestamp of
2136  * @param int $minute The minute part to create timestamp of
2137  * @param int $second The second part to create timestamp of
2138  * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2139  *             if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2140  * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2141  *             applied only if timezone is 99 or string.
2142  * @return int GMT timestamp
2143  */
2144 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2145     $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2146     $date->setDate((int)$year, (int)$month, (int)$day);
2147     $date->setTime((int)$hour, (int)$minute, (int)$second);
2149     $time = $date->getTimestamp();
2151     if ($time === false) {
2152         throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2153             ' This can fail if year is more than 2038 and OS is 32 bit windows');
2154     }
2156     // Moodle BC DST stuff.
2157     if (!$applydst) {
2158         $time += dst_offset_on($time, $timezone);
2159     }
2161     return $time;
2165 /**
2166  * Format a date/time (seconds) as weeks, days, hours etc as needed
2167  *
2168  * Given an amount of time in seconds, returns string
2169  * formatted nicely as years, days, hours etc as needed
2170  *
2171  * @package core
2172  * @category time
2173  * @uses MINSECS
2174  * @uses HOURSECS
2175  * @uses DAYSECS
2176  * @uses YEARSECS
2177  * @param int $totalsecs Time in seconds
2178  * @param stdClass $str Should be a time object
2179  * @return string A nicely formatted date/time string
2180  */
2181 function format_time($totalsecs, $str = null) {
2183     $totalsecs = abs($totalsecs);
2185     if (!$str) {
2186         // Create the str structure the slow way.
2187         $str = new stdClass();
2188         $str->day   = get_string('day');
2189         $str->days  = get_string('days');
2190         $str->hour  = get_string('hour');
2191         $str->hours = get_string('hours');
2192         $str->min   = get_string('min');
2193         $str->mins  = get_string('mins');
2194         $str->sec   = get_string('sec');
2195         $str->secs  = get_string('secs');
2196         $str->year  = get_string('year');
2197         $str->years = get_string('years');
2198     }
2200     $years     = floor($totalsecs/YEARSECS);
2201     $remainder = $totalsecs - ($years*YEARSECS);
2202     $days      = floor($remainder/DAYSECS);
2203     $remainder = $totalsecs - ($days*DAYSECS);
2204     $hours     = floor($remainder/HOURSECS);
2205     $remainder = $remainder - ($hours*HOURSECS);
2206     $mins      = floor($remainder/MINSECS);
2207     $secs      = $remainder - ($mins*MINSECS);
2209     $ss = ($secs == 1)  ? $str->sec  : $str->secs;
2210     $sm = ($mins == 1)  ? $str->min  : $str->mins;
2211     $sh = ($hours == 1) ? $str->hour : $str->hours;
2212     $sd = ($days == 1)  ? $str->day  : $str->days;
2213     $sy = ($years == 1)  ? $str->year  : $str->years;
2215     $oyears = '';
2216     $odays = '';
2217     $ohours = '';
2218     $omins = '';
2219     $osecs = '';
2221     if ($years) {
2222         $oyears  = $years .' '. $sy;
2223     }
2224     if ($days) {
2225         $odays  = $days .' '. $sd;
2226     }
2227     if ($hours) {
2228         $ohours = $hours .' '. $sh;
2229     }
2230     if ($mins) {
2231         $omins  = $mins .' '. $sm;
2232     }
2233     if ($secs) {
2234         $osecs  = $secs .' '. $ss;
2235     }
2237     if ($years) {
2238         return trim($oyears .' '. $odays);
2239     }
2240     if ($days) {
2241         return trim($odays .' '. $ohours);
2242     }
2243     if ($hours) {
2244         return trim($ohours .' '. $omins);
2245     }
2246     if ($mins) {
2247         return trim($omins .' '. $osecs);
2248     }
2249     if ($secs) {
2250         return $osecs;
2251     }
2252     return get_string('now');
2255 /**
2256  * Returns a formatted string that represents a date in user time.
2257  *
2258  * @package core
2259  * @category time
2260  * @param int $date the timestamp in UTC, as obtained from the database.
2261  * @param string $format strftime format. You should probably get this using
2262  *        get_string('strftime...', 'langconfig');
2263  * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2264  *        not 99 then daylight saving will not be added.
2265  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2266  * @param bool $fixday If true (default) then the leading zero from %d is removed.
2267  *        If false then the leading zero is maintained.
2268  * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2269  * @return string the formatted date/time.
2270  */
2271 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2272     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2273     return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2276 /**
2277  * Returns a html "time" tag with both the exact user date with timezone information
2278  * as a datetime attribute in the W3C format, and the user readable date and time as text.
2279  *
2280  * @package core
2281  * @category time
2282  * @param int $date the timestamp in UTC, as obtained from the database.
2283  * @param string $format strftime format. You should probably get this using
2284  *        get_string('strftime...', 'langconfig');
2285  * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2286  *        not 99 then daylight saving will not be added.
2287  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2288  * @param bool $fixday If true (default) then the leading zero from %d is removed.
2289  *        If false then the leading zero is maintained.
2290  * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2291  * @return string the formatted date/time.
2292  */
2293 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2294     $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2295     if (CLI_SCRIPT && !PHPUNIT_TEST) {
2296         return $userdatestr;
2297     }
2298     $machinedate = new DateTime();
2299     $machinedate->setTimestamp(intval($date));
2300     $machinedate->setTimezone(core_date::get_user_timezone_object());
2302     return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2305 /**
2306  * Returns a formatted date ensuring it is UTF-8.
2307  *
2308  * If we are running under Windows convert to Windows encoding and then back to UTF-8
2309  * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2310  *
2311  * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2312  * @param string $format strftime format.
2313  * @param int|float|string $tz the user timezone
2314  * @return string the formatted date/time.
2315  * @since Moodle 2.3.3
2316  */
2317 function date_format_string($date, $format, $tz = 99) {
2318     global $CFG;
2320     $localewincharset = null;
2321     // Get the calendar type user is using.
2322     if ($CFG->ostype == 'WINDOWS') {
2323         $calendartype = \core_calendar\type_factory::get_calendar_instance();
2324         $localewincharset = $calendartype->locale_win_charset();
2325     }
2327     if ($localewincharset) {
2328         $format = core_text::convert($format, 'utf-8', $localewincharset);
2329     }
2331     date_default_timezone_set(core_date::get_user_timezone($tz));
2332     $datestring = strftime($format, $date);
2333     core_date::set_default_server_timezone();
2335     if ($localewincharset) {
2336         $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2337     }
2339     return $datestring;
2342 /**
2343  * Given a $time timestamp in GMT (seconds since epoch),
2344  * returns an array that represents the Gregorian date in user time
2345  *
2346  * @package core
2347  * @category time
2348  * @param int $time Timestamp in GMT
2349  * @param float|int|string $timezone user timezone
2350  * @return array An array that represents the date in user time
2351  */
2352 function usergetdate($time, $timezone=99) {
2353     date_default_timezone_set(core_date::get_user_timezone($timezone));
2354     $result = getdate($time);
2355     core_date::set_default_server_timezone();
2357     return $result;
2360 /**
2361  * Given a GMT timestamp (seconds since epoch), offsets it by
2362  * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2363  *
2364  * NOTE: this function does not include DST properly,
2365  *       you should use the PHP date stuff instead!
2366  *
2367  * @package core
2368  * @category time
2369  * @param int $date Timestamp in GMT
2370  * @param float|int|string $timezone user timezone
2371  * @return int
2372  */
2373 function usertime($date, $timezone=99) {
2374     $userdate = new DateTime('@' . $date);
2375     $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2376     $dst = dst_offset_on($date, $timezone);
2378     return $date - $userdate->getOffset() + $dst;
2381 /**
2382  * Get a formatted string representation of an interval between two unix timestamps.
2383  *
2384  * E.g.
2385  * $intervalstring = get_time_interval_string(12345600, 12345660);
2386  * Will produce the string:
2387  * '0d 0h 1m'
2388  *
2389  * @param int $time1 unix timestamp
2390  * @param int $time2 unix timestamp
2391  * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2392  * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2393  */
2394 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2395     $dtdate = new DateTime();
2396     $dtdate->setTimeStamp($time1);
2397     $dtdate2 = new DateTime();
2398     $dtdate2->setTimeStamp($time2);
2399     $interval = $dtdate2->diff($dtdate);
2400     $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2401     return $interval->format($format);
2404 /**
2405  * Given a time, return the GMT timestamp of the most recent midnight
2406  * for the current user.
2407  *
2408  * @package core
2409  * @category time
2410  * @param int $date Timestamp in GMT
2411  * @param float|int|string $timezone user timezone
2412  * @return int Returns a GMT timestamp
2413  */
2414 function usergetmidnight($date, $timezone=99) {
2416     $userdate = usergetdate($date, $timezone);
2418     // Time of midnight of this user's day, in GMT.
2419     return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2423 /**
2424  * Returns a string that prints the user's timezone
2425  *
2426  * @package core
2427  * @category time
2428  * @param float|int|string $timezone user timezone
2429  * @return string
2430  */
2431 function usertimezone($timezone=99) {
2432     $tz = core_date::get_user_timezone($timezone);
2433     return core_date::get_localised_timezone($tz);
2436 /**
2437  * Returns a float or a string which denotes the user's timezone
2438  * 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)
2439  * means that for this timezone there are also DST rules to be taken into account
2440  * Checks various settings and picks the most dominant of those which have a value
2441  *
2442  * @package core
2443  * @category time
2444  * @param float|int|string $tz timezone to calculate GMT time offset before
2445  *        calculating user timezone, 99 is default user timezone
2446  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2447  * @return float|string
2448  */
2449 function get_user_timezone($tz = 99) {
2450     global $USER, $CFG;
2452     $timezones = array(
2453         $tz,
2454         isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2455         isset($USER->timezone) ? $USER->timezone : 99,
2456         isset($CFG->timezone) ? $CFG->timezone : 99,
2457         );
2459     $tz = 99;
2461     // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2462     foreach ($timezones as $nextvalue) {
2463         if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2464             $tz = $nextvalue;
2465         }
2466     }
2467     return is_numeric($tz) ? (float) $tz : $tz;
2470 /**
2471  * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2472  * - Note: Daylight saving only works for string timezones and not for float.
2473  *
2474  * @package core
2475  * @category time
2476  * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2477  * @param int|float|string $strtimezone user timezone
2478  * @return int
2479  */
2480 function dst_offset_on($time, $strtimezone = null) {
2481     $tz = core_date::get_user_timezone($strtimezone);
2482     $date = new DateTime('@' . $time);
2483     $date->setTimezone(new DateTimeZone($tz));
2484     if ($date->format('I') == '1') {
2485         if ($tz === 'Australia/Lord_Howe') {
2486             return 1800;
2487         }
2488         return 3600;
2489     }
2490     return 0;
2493 /**
2494  * Calculates when the day appears in specific month
2495  *
2496  * @package core
2497  * @category time
2498  * @param int $startday starting day of the month
2499  * @param int $weekday The day when week starts (normally taken from user preferences)
2500  * @param int $month The month whose day is sought
2501  * @param int $year The year of the month whose day is sought
2502  * @return int
2503  */
2504 function find_day_in_month($startday, $weekday, $month, $year) {
2505     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2507     $daysinmonth = days_in_month($month, $year);
2508     $daysinweek = count($calendartype->get_weekdays());
2510     if ($weekday == -1) {
2511         // Don't care about weekday, so return:
2512         //    abs($startday) if $startday != -1
2513         //    $daysinmonth otherwise.
2514         return ($startday == -1) ? $daysinmonth : abs($startday);
2515     }
2517     // From now on we 're looking for a specific weekday.
2518     // Give "end of month" its actual value, since we know it.
2519     if ($startday == -1) {
2520         $startday = -1 * $daysinmonth;
2521     }
2523     // Starting from day $startday, the sign is the direction.
2524     if ($startday < 1) {
2525         $startday = abs($startday);
2526         $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2528         // This is the last such weekday of the month.
2529         $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2530         if ($lastinmonth > $daysinmonth) {
2531             $lastinmonth -= $daysinweek;
2532         }
2534         // Find the first such weekday <= $startday.
2535         while ($lastinmonth > $startday) {
2536             $lastinmonth -= $daysinweek;
2537         }
2539         return $lastinmonth;
2540     } else {
2541         $indexweekday = dayofweek($startday, $month, $year);
2543         $diff = $weekday - $indexweekday;
2544         if ($diff < 0) {
2545             $diff += $daysinweek;
2546         }
2548         // This is the first such weekday of the month equal to or after $startday.
2549         $firstfromindex = $startday + $diff;
2551         return $firstfromindex;
2552     }
2555 /**
2556  * Calculate the number of days in a given month
2557  *
2558  * @package core
2559  * @category time
2560  * @param int $month The month whose day count is sought
2561  * @param int $year The year of the month whose day count is sought
2562  * @return int
2563  */
2564 function days_in_month($month, $year) {
2565     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2566     return $calendartype->get_num_days_in_month($year, $month);
2569 /**
2570  * Calculate the position in the week of a specific calendar day
2571  *
2572  * @package core
2573  * @category time
2574  * @param int $day The day of the date whose position in the week is sought
2575  * @param int $month The month of the date whose position in the week is sought
2576  * @param int $year The year of the date whose position in the week is sought
2577  * @return int
2578  */
2579 function dayofweek($day, $month, $year) {
2580     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2581     return $calendartype->get_weekday($year, $month, $day);
2584 // USER AUTHENTICATION AND LOGIN.
2586 /**
2587  * Returns full login url.
2588  *
2589  * Any form submissions for authentication to this URL must include username,
2590  * password as well as a logintoken generated by \core\session\manager::get_login_token().
2591  *
2592  * @return string login url
2593  */
2594 function get_login_url() {
2595     global $CFG;
2597     return "$CFG->wwwroot/login/index.php";
2600 /**
2601  * This function checks that the current user is logged in and has the
2602  * required privileges
2603  *
2604  * This function checks that the current user is logged in, and optionally
2605  * whether they are allowed to be in a particular course and view a particular
2606  * course module.
2607  * If they are not logged in, then it redirects them to the site login unless
2608  * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2609  * case they are automatically logged in as guests.
2610  * If $courseid is given and the user is not enrolled in that course then the
2611  * user is redirected to the course enrolment page.
2612  * If $cm is given and the course module is hidden and the user is not a teacher
2613  * in the course then the user is redirected to the course home page.
2614  *
2615  * When $cm parameter specified, this function sets page layout to 'module'.
2616  * You need to change it manually later if some other layout needed.
2617  *
2618  * @package    core_access
2619  * @category   access
2620  *
2621  * @param mixed $courseorid id of the course or course object
2622  * @param bool $autologinguest default true
2623  * @param object $cm course module object
2624  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2625  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2626  *             in order to keep redirects working properly. MDL-14495
2627  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2628  * @return mixed Void, exit, and die depending on path
2629  * @throws coding_exception
2630  * @throws require_login_exception
2631  * @throws moodle_exception
2632  */
2633 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2634     global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2636     // Must not redirect when byteserving already started.
2637     if (!empty($_SERVER['HTTP_RANGE'])) {
2638         $preventredirect = true;
2639     }
2641     if (AJAX_SCRIPT) {
2642         // We cannot redirect for AJAX scripts either.
2643         $preventredirect = true;
2644     }
2646     // Setup global $COURSE, themes, language and locale.
2647     if (!empty($courseorid)) {
2648         if (is_object($courseorid)) {
2649             $course = $courseorid;
2650         } else if ($courseorid == SITEID) {
2651             $course = clone($SITE);
2652         } else {
2653             $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2654         }
2655         if ($cm) {
2656             if ($cm->course != $course->id) {
2657                 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2658             }
2659             // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2660             if (!($cm instanceof cm_info)) {
2661                 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2662                 // db queries so this is not really a performance concern, however it is obviously
2663                 // better if you use get_fast_modinfo to get the cm before calling this.
2664                 $modinfo = get_fast_modinfo($course);
2665                 $cm = $modinfo->get_cm($cm->id);
2666             }
2667         }
2668     } else {
2669         // Do not touch global $COURSE via $PAGE->set_course(),
2670         // the reasons is we need to be able to call require_login() at any time!!
2671         $course = $SITE;
2672         if ($cm) {
2673             throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2674         }
2675     }
2677     // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2678     // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2679     // risk leading the user back to the AJAX request URL.
2680     if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2681         $setwantsurltome = false;
2682     }
2684     // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2685     if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2686         if ($preventredirect) {
2687             throw new require_login_session_timeout_exception();
2688         } else {
2689             if ($setwantsurltome) {
2690                 $SESSION->wantsurl = qualified_me();
2691             }
2692             redirect(get_login_url());
2693         }
2694     }
2696     // If the user is not even logged in yet then make sure they are.
2697     if (!isloggedin()) {
2698         if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2699             if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2700                 // Misconfigured site guest, just redirect to login page.
2701                 redirect(get_login_url());
2702                 exit; // Never reached.
2703             }
2704             $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2705             complete_user_login($guest);
2706             $USER->autologinguest = true;
2707             $SESSION->lang = $lang;
2708         } else {
2709             // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2710             if ($preventredirect) {
2711                 throw new require_login_exception('You are not logged in');
2712             }
2714             if ($setwantsurltome) {
2715                 $SESSION->wantsurl = qualified_me();
2716             }
2718             $referer = get_local_referer(false);
2719             if (!empty($referer)) {
2720                 $SESSION->fromurl = $referer;
2721             }
2723             // Give auth plugins an opportunity to authenticate or redirect to an external login page
2724             $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2725             foreach($authsequence as $authname) {
2726                 $authplugin = get_auth_plugin($authname);
2727                 $authplugin->pre_loginpage_hook();
2728                 if (isloggedin()) {
2729                     if ($cm) {
2730                         $modinfo = get_fast_modinfo($course);
2731                         $cm = $modinfo->get_cm($cm->id);
2732                     }
2733                     set_access_log_user();
2734                     break;
2735                 }
2736             }
2738             // If we're still not logged in then go to the login page
2739             if (!isloggedin()) {
2740                 redirect(get_login_url());
2741                 exit; // Never reached.
2742             }
2743         }
2744     }
2746     // Loginas as redirection if needed.
2747     if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2748         if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2749             if ($USER->loginascontext->instanceid != $course->id) {
2750                 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2751             }
2752         }
2753     }
2755     // Check whether the user should be changing password (but only if it is REALLY them).
2756     if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2757         $userauth = get_auth_plugin($USER->auth);
2758         if ($userauth->can_change_password() and !$preventredirect) {
2759             if ($setwantsurltome) {
2760                 $SESSION->wantsurl = qualified_me();
2761             }
2762             if ($changeurl = $userauth->change_password_url()) {
2763                 // Use plugin custom url.
2764                 redirect($changeurl);
2765             } else {
2766                 // Use moodle internal method.
2767                 redirect($CFG->wwwroot .'/login/change_password.php');
2768             }
2769         } else if ($userauth->can_change_password()) {
2770             throw new moodle_exception('forcepasswordchangenotice');
2771         } else {
2772             throw new moodle_exception('nopasswordchangeforced', 'auth');
2773         }
2774     }
2776     // Check that the user account is properly set up. If we can't redirect to
2777     // edit their profile and this is not a WS request, perform just the lax check.
2778     // It will allow them to use filepicker on the profile edit page.
2780     if ($preventredirect && !WS_SERVER) {
2781         $usernotfullysetup = user_not_fully_set_up($USER, false);
2782     } else {
2783         $usernotfullysetup = user_not_fully_set_up($USER, true);
2784     }
2786     if ($usernotfullysetup) {
2787         if ($preventredirect) {
2788             throw new moodle_exception('usernotfullysetup');
2789         }
2790         if ($setwantsurltome) {
2791             $SESSION->wantsurl = qualified_me();
2792         }
2793         redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2794     }
2796     // Make sure the USER has a sesskey set up. Used for CSRF protection.
2797     sesskey();
2799     if (\core\session\manager::is_loggedinas()) {
2800         // During a "logged in as" session we should force all content to be cleaned because the
2801         // logged in user will be viewing potentially malicious user generated content.
2802         // See MDL-63786 for more details.
2803         $CFG->forceclean = true;
2804     }
2806     $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2808     // Do not bother admins with any formalities, except for activities pending deletion.
2809     if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2810         // Set the global $COURSE.
2811         if ($cm) {
2812             $PAGE->set_cm($cm, $course);
2813             $PAGE->set_pagelayout('incourse');
2814         } else if (!empty($courseorid)) {
2815             $PAGE->set_course($course);
2816         }
2817         // Set accesstime or the user will appear offline which messes up messaging.
2818         // Do not update access time for webservice or ajax requests.
2819         if (!WS_SERVER && !AJAX_SCRIPT) {
2820             user_accesstime_log($course->id);
2821         }
2823         foreach ($afterlogins as $plugintype => $plugins) {
2824             foreach ($plugins as $pluginfunction) {
2825                 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2826             }
2827         }
2828         return;
2829     }
2831     // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2832     // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2833     if (!defined('NO_SITEPOLICY_CHECK')) {
2834         define('NO_SITEPOLICY_CHECK', false);
2835     }
2837     // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2838     // Do not test if the script explicitly asked for skipping the site policies check.
2839     if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2840         $manager = new \core_privacy\local\sitepolicy\manager();
2841         if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2842             if ($preventredirect) {
2843                 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2844             }
2845             if ($setwantsurltome) {
2846                 $SESSION->wantsurl = qualified_me();
2847             }
2848             redirect($policyurl);
2849         }
2850     }
2852     // Fetch the system context, the course context, and prefetch its child contexts.
2853     $sysctx = context_system::instance();
2854     $coursecontext = context_course::instance($course->id, MUST_EXIST);
2855     if ($cm) {
2856         $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2857     } else {
2858         $cmcontext = null;
2859     }
2861     // If the site is currently under maintenance, then print a message.
2862     if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2863         if ($preventredirect) {
2864             throw new require_login_exception('Maintenance in progress');
2865         }
2866         $PAGE->set_context(null);
2867         print_maintenance_message();
2868     }
2870     // Make sure the course itself is not hidden.
2871     if ($course->id == SITEID) {
2872         // Frontpage can not be hidden.
2873     } else {
2874         if (is_role_switched($course->id)) {
2875             // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2876         } else {
2877             if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2878                 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2879                 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2880                 if ($preventredirect) {
2881                     throw new require_login_exception('Course is hidden');
2882                 }
2883                 $PAGE->set_context(null);
2884                 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2885                 // the navigation will mess up when trying to find it.
2886                 navigation_node::override_active_url(new moodle_url('/'));
2887                 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2888             }
2889         }
2890     }
2892     // Is the user enrolled?
2893     if ($course->id == SITEID) {
2894         // Everybody is enrolled on the frontpage.
2895     } else {
2896         if (\core\session\manager::is_loggedinas()) {
2897             // Make sure the REAL person can access this course first.
2898             $realuser = \core\session\manager::get_realuser();
2899             if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2900                 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2901                 if ($preventredirect) {
2902                     throw new require_login_exception('Invalid course login-as access');
2903                 }
2904                 $PAGE->set_context(null);
2905                 echo $OUTPUT->header();
2906                 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2907             }
2908         }
2910         $access = false;
2912         if (is_role_switched($course->id)) {
2913             // Ok, user had to be inside this course before the switch.
2914             $access = true;
2916         } else if (is_viewing($coursecontext, $USER)) {
2917             // Ok, no need to mess with enrol.
2918             $access = true;
2920         } else {
2921             if (isset($USER->enrol['enrolled'][$course->id])) {
2922                 if ($USER->enrol['enrolled'][$course->id] > time()) {
2923                     $access = true;
2924                     if (isset($USER->enrol['tempguest'][$course->id])) {
2925                         unset($USER->enrol['tempguest'][$course->id]);
2926                         remove_temp_course_roles($coursecontext);
2927                     }
2928                 } else {
2929                     // Expired.
2930                     unset($USER->enrol['enrolled'][$course->id]);
2931                 }
2932             }
2933             if (isset($USER->enrol['tempguest'][$course->id])) {
2934                 if ($USER->enrol['tempguest'][$course->id] == 0) {
2935                     $access = true;
2936                 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2937                     $access = true;
2938                 } else {
2939                     // Expired.
2940                     unset($USER->enrol['tempguest'][$course->id]);
2941                     remove_temp_course_roles($coursecontext);
2942                 }
2943             }
2945             if (!$access) {
2946                 // Cache not ok.
2947                 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2948                 if ($until !== false) {
2949                     // Active participants may always access, a timestamp in the future, 0 (always) or false.
2950                     if ($until == 0) {
2951                         $until = ENROL_MAX_TIMESTAMP;
2952                     }
2953                     $USER->enrol['enrolled'][$course->id] = $until;
2954                     $access = true;
2956                 } else if (core_course_category::can_view_course_info($course)) {
2957                     $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2958                     $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2959                     $enrols = enrol_get_plugins(true);
2960                     // First ask all enabled enrol instances in course if they want to auto enrol user.
2961                     foreach ($instances as $instance) {
2962                         if (!isset($enrols[$instance->enrol])) {
2963                             continue;
2964                         }
2965                         // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2966                         $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2967                         if ($until !== false) {
2968                             if ($until == 0) {
2969                                 $until = ENROL_MAX_TIMESTAMP;
2970                             }
2971                             $USER->enrol['enrolled'][$course->id] = $until;
2972                             $access = true;
2973                             break;
2974                         }
2975                     }
2976                     // If not enrolled yet try to gain temporary guest access.
2977                     if (!$access) {
2978                         foreach ($instances as $instance) {
2979                             if (!isset($enrols[$instance->enrol])) {
2980                                 continue;
2981                             }
2982                             // Get a duration for the guest access, a timestamp in the future or false.
2983                             $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2984                             if ($until !== false and $until > time()) {
2985                                 $USER->enrol['tempguest'][$course->id] = $until;
2986                                 $access = true;
2987                                 break;
2988                             }
2989                         }
2990                     }
2991                 } else {
2992                     // User is not enrolled and is not allowed to browse courses here.
2993                     if ($preventredirect) {
2994                         throw new require_login_exception('Course is not available');
2995                     }
2996                     $PAGE->set_context(null);
2997                     // We need to override the navigation URL as the course won't have been added to the navigation and thus
2998                     // the navigation will mess up when trying to find it.
2999                     navigation_node::override_active_url(new moodle_url('/'));
3000                     notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3001                 }
3002             }
3003         }
3005         if (!$access) {
3006             if ($preventredirect) {
3007                 throw new require_login_exception('Not enrolled');
3008             }
3009             if ($setwantsurltome) {
3010                 $SESSION->wantsurl = qualified_me();
3011             }
3012             redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3013         }
3014     }
3016     // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3017     if ($cm && $cm->deletioninprogress) {
3018         if ($preventredirect) {
3019             throw new moodle_exception('activityisscheduledfordeletion');
3020         }
3021         require_once($CFG->dirroot . '/course/lib.php');
3022         redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3023     }
3025     // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3026     if ($cm && !$cm->uservisible) {
3027         if ($preventredirect) {
3028             throw new require_login_exception('Activity is hidden');
3029         }
3030         // Get the error message that activity is not available and why (if explanation can be shown to the user).
3031         $PAGE->set_course($course);
3032         $renderer = $PAGE->get_renderer('course');
3033         $message = $renderer->course_section_cm_unavailable_error_message($cm);
3034         redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3035     }
3037     // Set the global $COURSE.
3038     if ($cm) {
3039         $PAGE->set_cm($cm, $course);
3040         $PAGE->set_pagelayout('incourse');
3041     } else if (!empty($courseorid)) {
3042         $PAGE->set_course($course);
3043     }
3045     foreach ($afterlogins as $plugintype => $plugins) {
3046         foreach ($plugins as $pluginfunction) {
3047             $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3048         }
3049     }
3051     // Finally access granted, update lastaccess times.
3052     // Do not update access time for webservice or ajax requests.
3053     if (!WS_SERVER && !AJAX_SCRIPT) {
3054         user_accesstime_log($course->id);
3055     }
3058 /**
3059  * A convenience function for where we must be logged in as admin
3060  * @return void
3061  */
3062 function require_admin() {
3063     require_login(null, false);
3064     require_capability('moodle/site:config', context_system::instance());
3067 /**
3068  * This function just makes sure a user is logged out.
3069  *
3070  * @package    core_access
3071  * @category   access
3072  */
3073 function require_logout() {
3074     global $USER, $DB;
3076     if (!isloggedin()) {
3077         // This should not happen often, no need for hooks or events here.
3078         \core\session\manager::terminate_current();
3079         return;
3080     }
3082     // Execute hooks before action.
3083     $authplugins = array();
3084     $authsequence = get_enabled_auth_plugins();
3085     foreach ($authsequence as $authname) {
3086         $authplugins[$authname] = get_auth_plugin($authname);
3087         $authplugins[$authname]->prelogout_hook();
3088     }
3090     // Store info that gets removed during logout.
3091     $sid = session_id();
3092     $event = \core\event\user_loggedout::create(
3093         array(
3094             'userid' => $USER->id,
3095             'objectid' => $USER->id,
3096             'other' => array('sessionid' => $sid),
3097         )
3098     );
3099     if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3100         $event->add_record_snapshot('sessions', $session);
3101     }
3103     // Clone of $USER object to be used by auth plugins.
3104     $user = fullclone($USER);
3106     // Delete session record and drop $_SESSION content.
3107     \core\session\manager::terminate_current();
3109     // Trigger event AFTER action.
3110     $event->trigger();
3112     // Hook to execute auth plugins redirection after event trigger.
3113     foreach ($authplugins as $authplugin) {
3114         $authplugin->postlogout_hook($user);
3115     }
3118 /**
3119  * Weaker version of require_login()
3120  *
3121  * This is a weaker version of {@link require_login()} which only requires login
3122  * when called from within a course rather than the site page, unless
3123  * the forcelogin option is turned on.
3124  * @see require_login()
3125  *
3126  * @package    core_access
3127  * @category   access
3128  *
3129  * @param mixed $courseorid The course object or id in question
3130  * @param bool $autologinguest Allow autologin guests if that is wanted
3131  * @param object $cm Course activity module if known
3132  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3133  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3134  *             in order to keep redirects working properly. MDL-14495
3135  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3136  * @return void
3137  * @throws coding_exception
3138  */
3139 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3140     global $CFG, $PAGE, $SITE;
3141     $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3142           or (!is_object($courseorid) and $courseorid == SITEID));
3143     if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3144         // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3145         // db queries so this is not really a performance concern, however it is obviously
3146         // better if you use get_fast_modinfo to get the cm before calling this.
3147         if (is_object($courseorid)) {
3148             $course = $courseorid;
3149         } else {
3150             $course = clone($SITE);
3151         }
3152         $modinfo = get_fast_modinfo($course);
3153         $cm = $modinfo->get_cm($cm->id);
3154     }
3155     if (!empty($CFG->forcelogin)) {
3156         // Login required for both SITE and courses.
3157         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3159     } else if ($issite && !empty($cm) and !$cm->uservisible) {
3160         // Always login for hidden activities.
3161         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3163     } else if (isloggedin() && !isguestuser()) {
3164         // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3165         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3167     } else if ($issite) {
3168         // Login for SITE not required.
3169         // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3170         if (!empty($courseorid)) {
3171             if (is_object($courseorid)) {
3172                 $course = $courseorid;
3173             } else {
3174                 $course = clone $SITE;
3175             }
3176             if ($cm) {
3177                 if ($cm->course != $course->id) {
3178                     throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3179                 }
3180                 $PAGE->set_cm($cm, $course);
3181                 $PAGE->set_pagelayout('incourse');
3182             } else {
3183                 $PAGE->set_course($course);
3184             }
3185         } else {
3186             // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3187             $PAGE->set_course($PAGE->course);
3188         }
3189         // Do not update access time for webservice or ajax requests.
3190         if (!WS_SERVER && !AJAX_SCRIPT) {
3191             user_accesstime_log(SITEID);
3192         }
3193         return;
3195     } else {
3196         // Course login always required.
3197         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3198     }
3201 /**
3202  * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3203  *
3204  * @param  string $keyvalue the key value
3205  * @param  string $script   unique script identifier
3206  * @param  int $instance    instance id
3207  * @return stdClass the key entry in the user_private_key table
3208  * @since Moodle 3.2
3209  * @throws moodle_exception
3210  */
3211 function validate_user_key($keyvalue, $script, $instance) {
3212     global $DB;
3214     if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3215         print_error('invalidkey');
3216     }
3218     if (!empty($key->validuntil) and $key->validuntil < time()) {
3219         print_error('expiredkey');
3220     }
3222     if ($key->iprestriction) {
3223         $remoteaddr = getremoteaddr(null);
3224         if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3225             print_error('ipmismatch');
3226         }
3227     }
3228     return $key;
3231 /**
3232  * Require key login. Function terminates with error if key not found or incorrect.
3233  *
3234  * @uses NO_MOODLE_COOKIES
3235  * @uses PARAM_ALPHANUM
3236  * @param string $script unique script identifier
3237  * @param int $instance optional instance id
3238  * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3239  * @return int Instance ID
3240  */
3241 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3242     global $DB;
3244     if (!NO_MOODLE_COOKIES) {
3245         print_error('sessioncookiesdisable');
3246     }
3248     // Extra safety.
3249     \core\session\manager::write_close();
3251     if (null === $keyvalue) {
3252         $keyvalue = required_param('key', PARAM_ALPHANUM);
3253     }
3255     $key = validate_user_key($keyvalue, $script, $instance);
3257     if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3258         print_error('invaliduserid');
3259     }
3261     core_user::require_active_user($user, true, true);
3263     // Emulate normal session.
3264     enrol_check_plugins($user);
3265     \core\session\manager::set_user($user);
3267     // Note we are not using normal login.
3268     if (!defined('USER_KEY_LOGIN')) {
3269         define('USER_KEY_LOGIN', true);
3270     }
3272     // Return instance id - it might be empty.
3273     return $key->instance;
3276 /**
3277  * Creates a new private user access key.
3278  *
3279  * @param string $script unique target identifier
3280  * @param int $userid
3281  * @param int $instance optional instance id
3282  * @param string $iprestriction optional ip restricted access
3283  * @param int $validuntil key valid only until given data
3284  * @return string access key value
3285  */
3286 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3287     global $DB;
3289     $key = new stdClass();
3290     $key->script        = $script;
3291     $key->userid        = $userid;
3292     $key->instance      = $instance;
3293     $key->iprestriction = $iprestriction;
3294     $key->validuntil    = $validuntil;
3295     $key->timecreated   = time();
3297     // Something long and unique.
3298     $key->value         = md5($userid.'_'.time().random_string(40));
3299     while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3300         // Must be unique.
3301         $key->value     = md5($userid.'_'.time().random_string(40));
3302     }
3303     $DB->insert_record('user_private_key', $key);
3304     return $key->value;
3307 /**
3308  * Delete the user's new private user access keys for a particular script.
3309  *
3310  * @param string $script unique target identifier
3311  * @param int $userid
3312  * @return void
3313  */
3314 function delete_user_key($script, $userid) {
3315     global $DB;
3316     $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3319 /**
3320  * Gets a private user access key (and creates one if one doesn't exist).
3321  *
3322  * @param string $script unique target identifier
3323  * @param int $userid
3324  * @param int $instance optional instance id
3325  * @param string $iprestriction optional ip restricted access
3326  * @param int $validuntil key valid only until given date
3327  * @return string access key value
3328  */
3329 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3330     global $DB;
3332     if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3333                                                          'instance' => $instance, 'iprestriction' => $iprestriction,
3334                                                          'validuntil' => $validuntil))) {
3335         return $key->value;
3336     } else {
3337         return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3338     }
3342 /**
3343  * Modify the user table by setting the currently logged in user's last login to now.
3344  *
3345  * @return bool Always returns true
3346  */
3347 function update_user_login_times() {
3348     global $USER, $DB;
3350     if (isguestuser()) {
3351         // Do not update guest access times/ips for performance.
3352         return true;
3353     }
3355     $now = time();
3357     $user = new stdClass();
3358     $user->id = $USER->id;
3360     // Make sure all users that logged in have some firstaccess.
3361     if ($USER->firstaccess == 0) {
3362         $USER->firstaccess = $user->firstaccess = $now;
3363     }
3365     // Store the previous current as lastlogin.
3366     $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3368     $USER->currentlogin = $user->currentlogin = $now;
3370     // Function user_accesstime_log() may not update immediately, better do it here.
3371     $USER->lastaccess = $user->lastaccess = $now;
3372     $USER->lastip = $user->lastip = getremoteaddr();
3374     // Note: do not call user_update_user() here because this is part of the login process,
3375     //       the login event means that these fields were updated.
3376     $DB->update_record('user', $user);
3377     return true;
3380 /**
3381  * Determines if a user has completed setting up their account.
3382  *
3383  * The lax mode (with $strict = false) has been introduced for special cases
3384  * only where we want to skip certain checks intentionally. This is valid in
3385  * certain mnet or ajax scenarios when the user cannot / should not be
3386  * redirected to edit their profile. In most cases, you should perform the
3387  * strict check.
3388  *
3389  * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3390  * @param bool $strict Be more strict and assert id and custom profile fields set, too
3391  * @return bool
3392  */
3393 function user_not_fully_set_up($user, $strict = true) {
3394     global $CFG;
3395     require_once($CFG->dirroot.'/user/profile/lib.php');
3397     if (isguestuser($user)) {
3398         return false;
3399     }
3401     if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3402         return true;
3403     }
3405     if ($strict) {
3406         if (empty($user->id)) {
3407             // Strict mode can be used with existing accounts only.
3408             return true;
3409         }
3410         if (!profile_has_required_custom_fields_set($user->id)) {
3411             return true;
3412         }
3413     }
3415     return false;
3418 /**
3419  * Check whether the user has exceeded the bounce threshold
3420  *
3421  * @param stdClass $user A {@link $USER} object
3422  * @return bool true => User has exceeded bounce threshold
3423  */
3424 function over_bounce_threshold($user) {
3425     global $CFG, $DB;
3427     if (empty($CFG->handlebounces)) {
3428         return false;
3429     }
3431     if (empty($user->id)) {
3432         // No real (DB) user, nothing to do here.
3433         return false;
3434     }
3436     // Set sensible defaults.
3437     if (empty($CFG->minbounces)) {
3438         $CFG->minbounces = 10;
3439     }
3440     if (empty($CFG->bounceratio)) {
3441         $CFG->bounceratio = .20;
3442     }
3443     $bouncecount = 0;
3444     $sendcount = 0;
3445     if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3446         $bouncecount = $bounce->value;
3447     }
3448     if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3449         $sendcount = $send->value;
3450     }
3451     return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3454 /**
3455  * Used to increment or reset email sent count
3456  *
3457  * @param stdClass $user object containing an id
3458  * @param bool $reset will reset the count to 0
3459  * @return void
3460  */
3461 function set_send_count($user, $reset=false) {
3462     global $DB;
3464     if (empty($user->id)) {
3465         // No real (DB) user, nothing to do here.
3466         return;
3467     }
3469     if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3470         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3471         $DB->update_record('user_preferences', $pref);
3472     } else if (!empty($reset)) {
3473         // If it's not there and we're resetting, don't bother. Make a new one.
3474         $pref = new stdClass();
3475         $pref->name   = 'email_send_count';
3476         $pref->value  = 1;
3477         $pref->userid = $user->id;
3478         $DB->insert_record('user_preferences', $pref, false);
3479     }
3482 /**
3483  * Increment or reset user's email bounce count
3484  *
3485  * @param stdClass $user object containing an id
3486  * @param bool $reset will reset the count to 0
3487  */
3488 function set_bounce_count($user, $reset=false) {
3489     global $DB;
3491     if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3492         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3493         $DB->update_record('user_preferences', $pref);
3494     } else if (!empty($reset)) {
3495         // If it's not there and we're resetting, don't bother. Make a new one.
3496         $pref = new stdClass();
3497         $pref->name   = 'email_bounce_count';
3498         $pref->value  = 1;
3499         $pref->userid = $user->id;
3500         $DB->insert_record('user_preferences', $pref, false);
3501     }
3504 /**
3505  * Determines if the logged in user is currently moving an activity
3506  *
3507  * @param int $courseid The id of the course being tested
3508  * @return bool
3509  */
3510 function ismoving($courseid) {
3511     global $USER;
3513     if (!empty($USER->activitycopy)) {
3514         return ($USER->activitycopycourse == $courseid);
3515     }
3516     return false;
3519 /**
3520  * Returns a persons full name
3521  *
3522  * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3523  * The result may depend on system settings or language.  'override' will force both names to be used even if system settings
3524  * specify one.
3525  *
3526  * @param stdClass $user A {@link $USER} object to get full name of.
3527  * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3528  * @return string
3529  */
3530 function fullname($user, $override=false) {
3531     global $CFG, $SESSION;
3533     if (!isset($user->firstname) and !isset($user->lastname)) {
3534         return '';
3535     }
3537     // Get all of the name fields.
3538     $allnames = get_all_user_name_fields();
3539     if ($CFG->debugdeveloper) {
3540         foreach ($allnames as $allname) {
3541             if (!property_exists($user, $allname)) {
3542                 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3543                 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3544                 // Message has been sent, no point in sending the message multiple times.
3545                 break;
3546             }
3547         }
3548     }
3550     if (!$override) {
3551         if (!empty($CFG->forcefirstname)) {
3552             $user->firstname = $CFG->forcefirstname;
3553         }
3554         if (!empty($CFG->forcelastname)) {
3555             $user->lastname = $CFG->forcelastname;
3556         }
3557     }
3559     if (!empty($SESSION->fullnamedisplay)) {
3560         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3561     }
3563     $template = null;
3564     // If the fullnamedisplay setting is available, set the template to that.
3565     if (isset($CFG->fullnamedisplay)) {
3566         $template = $CFG->fullnamedisplay;
3567     }
3568     // If the template is empty, or set to language, return the language string.
3569     if ((empty($template) || $template == 'language') && !$override) {
3570         return get_string('fullnamedisplay', null, $user);
3571     }
3573     // Check to see if we are displaying according to the alternative full name format.
3574     if ($override) {
3575         if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3576             // Default to show just the user names according to the fullnamedisplay string.
3577             return get_string('fullnamedisplay', null, $user);
3578         } else {
3579             // If the override is true, then change the template to use the complete name.
3580             $template = $CFG->alternativefullnameformat;
3581         }
3582     }
3584     $requirednames = array();
3585     // With each name, see if it is in the display name template, and add it to the required names array if it is.
3586     foreach ($allnames as $allname) {
3587         if (strpos($template, $allname) !== false) {
3588             $requirednames[] = $allname;
3589         }
3590     }
3592     $displayname = $template;
3593     // Switch in the actual data into the template.
3594     foreach ($requirednames as $altname) {
3595         if (isset($user->$altname)) {
3596             // Using empty() on the below if statement causes breakages.
3597             if ((string)$user->$altname == '') {
3598                 $displayname = str_replace($altname, 'EMPTY', $displayname);
3599             } else {
3600                 $displayname = str_replace($altname, $user->$altname, $displayname);
3601             }
3602         } else {
3603             $displayname = str_replace($altname, 'EMPTY', $displayname);
3604         }
3605     }
3606     // Tidy up any misc. characters (Not perfect, but gets most characters).
3607     // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3608     // katakana and parenthesis.
3609     $patterns = array();
3610     // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3611     // filled in by a user.
3612     // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3613     $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3614     // This regular expression is to remove any double spaces in the display name.
3615     $patterns[] = '/\s{2,}/u';
3616     foreach ($patterns as $pattern) {
3617         $displayname = preg_replace($pattern, ' ', $displayname);
3618     }
3620     // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3621     $displayname = trim($displayname);
3622     if (empty($displayname)) {
3623         // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3624         // people in general feel is a good setting to fall back on.
3625         $displayname = $user->firstname;
3626     }
3627     return $displayname;
3630 /**
3631  * A centralised location for the all name fields. Returns an array / sql string snippet.
3632  *
3633  * @param bool $returnsql True for an sql select field snippet.
3634  * @param string $tableprefix table query prefix to use in front of each field.
3635  * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3636  * @param string $fieldprefix sql field prefix e.g. id AS userid.
3637  * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3638  * @return array|string All name fields.
3639  */
3640 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3641     // This array is provided in this order because when called by fullname() (above) if firstname is before
3642     // firstnamephonetic str_replace() will change the wrong placeholder.
3643     $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3644                             'lastnamephonetic' => 'lastnamephonetic',
3645                             'middlename' => 'middlename',