6e93ad90d7d1e035c97c20c485205ccad4815157
[moodle.git] / lib / moodlelib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * moodlelib.php - Moodle main library
19  *
20  * Main library file of miscellaneous general-purpose Moodle functions.
21  * Other main libraries:
22  *  - weblib.php      - functions that produce web output
23  *  - datalib.php     - functions that access the database
24  *
25  * @package    core
26  * @subpackage lib
27  * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
28  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29  */
31 defined('MOODLE_INTERNAL') || die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
36 /**
37  * Time constant - the number of seconds in a year
38  */
39 define('YEARSECS', 31536000);
41 /**
42  * Time constant - the number of seconds in a week
43  */
44 define('WEEKSECS', 604800);
46 /**
47  * Time constant - the number of seconds in a day
48  */
49 define('DAYSECS', 86400);
51 /**
52  * Time constant - the number of seconds in an hour
53  */
54 define('HOURSECS', 3600);
56 /**
57  * Time constant - the number of seconds in a minute
58  */
59 define('MINSECS', 60);
61 /**
62  * Time constant - the number of minutes in a day
63  */
64 define('DAYMINS', 1440);
66 /**
67  * Time constant - the number of minutes in an hour
68  */
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
74 /**
75  * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
76  */
77 define('PARAM_ALPHA',    'alpha');
79 /**
80  * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81  * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
82  */
83 define('PARAM_ALPHAEXT', 'alphaext');
85 /**
86  * PARAM_ALPHANUM - expected numbers and letters only.
87  */
88 define('PARAM_ALPHANUM', 'alphanum');
90 /**
91  * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
92  */
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
95 /**
96  * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
97  */
98 define('PARAM_AUTH',  'auth');
100 /**
101  * PARAM_BASE64 - Base 64 encoded format
102  */
103 define('PARAM_BASE64',   'base64');
105 /**
106  * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
107  */
108 define('PARAM_BOOL',     'bool');
110 /**
111  * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112  * checked against the list of capabilities in the database.
113  */
114 define('PARAM_CAPABILITY',   'capability');
116 /**
117  * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118  * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119  * the input (required/optional_param or formslib) and then sanitse the HTML
120  * using format_text on output. This is for the rare cases when you want to
121  * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
122  */
123 define('PARAM_CLEANHTML', 'cleanhtml');
125 /**
126  * PARAM_EMAIL - an email address following the RFC
127  */
128 define('PARAM_EMAIL',   'email');
130 /**
131  * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
132  */
133 define('PARAM_FILE',   'file');
135 /**
136  * PARAM_FLOAT - a real/floating point number.
137  *
138  * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139  * It does not work for languages that use , as a decimal separator.
140  * Instead, do something like
141  *     $rawvalue = required_param('name', PARAM_RAW);
142  *     // ... other code including require_login, which sets current lang ...
143  *     $realvalue = unformat_float($rawvalue);
144  *     // ... then use $realvalue
145  */
146 define('PARAM_FLOAT',  'float');
148 /**
149  * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
150  */
151 define('PARAM_HOST',     'host');
153 /**
154  * PARAM_INT - integers only, use when expecting only numbers.
155  */
156 define('PARAM_INT',      'int');
158 /**
159  * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
160  */
161 define('PARAM_LANG',  'lang');
163 /**
164  * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165  * others! Implies PARAM_URL!)
166  */
167 define('PARAM_LOCALURL', 'localurl');
169 /**
170  * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
171  */
172 define('PARAM_NOTAGS',   'notags');
174 /**
175  * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176  * traversals note: the leading slash is not removed, window drive letter is not allowed
177  */
178 define('PARAM_PATH',     'path');
180 /**
181  * PARAM_PEM - Privacy Enhanced Mail format
182  */
183 define('PARAM_PEM',      'pem');
185 /**
186  * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
187  */
188 define('PARAM_PERMISSION',   'permission');
190 /**
191  * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
192  */
193 define('PARAM_RAW', 'raw');
195 /**
196  * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
197  */
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
200 /**
201  * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
202  */
203 define('PARAM_SAFEDIR',  'safedir');
205 /**
206  * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
207  */
208 define('PARAM_SAFEPATH',  'safepath');
210 /**
211  * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9.  Numbers and comma only.
212  */
213 define('PARAM_SEQUENCE',  'sequence');
215 /**
216  * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
217  */
218 define('PARAM_TAG',   'tag');
220 /**
221  * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
222  */
223 define('PARAM_TAGLIST',   'taglist');
225 /**
226  * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
227  */
228 define('PARAM_TEXT',  'text');
230 /**
231  * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
232  */
233 define('PARAM_THEME',  'theme');
235 /**
236  * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237  * http://localhost.localdomain/ is ok.
238  */
239 define('PARAM_URL',      'url');
241 /**
242  * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243  * accounts, do NOT use when syncing with external systems!!
244  */
245 define('PARAM_USERNAME',    'username');
247 /**
248  * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
249  */
250 define('PARAM_STRINGID',    'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
253 /**
254  * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255  * It was one of the first types, that is why it is abused so much ;-)
256  * @deprecated since 2.0
257  */
258 define('PARAM_CLEAN',    'clean');
260 /**
261  * PARAM_INTEGER - deprecated alias for PARAM_INT
262  * @deprecated since 2.0
263  */
264 define('PARAM_INTEGER',  'int');
266 /**
267  * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268  * @deprecated since 2.0
269  */
270 define('PARAM_NUMBER',  'float');
272 /**
273  * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274  * NOTE: originally alias for PARAM_APLHA
275  * @deprecated since 2.0
276  */
277 define('PARAM_ACTION',   'alphanumext');
279 /**
280  * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281  * NOTE: originally alias for PARAM_APLHA
282  * @deprecated since 2.0
283  */
284 define('PARAM_FORMAT',   'alphanumext');
286 /**
287  * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288  * @deprecated since 2.0
289  */
290 define('PARAM_MULTILANG',  'text');
292 /**
293  * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294  * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295  * America/Port-au-Prince)
296  */
297 define('PARAM_TIMEZONE', 'timezone');
299 /**
300  * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
301  */
302 define('PARAM_CLEANFILE', 'file');
304 /**
305  * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306  * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308  * NOTE: numbers and underscores are strongly discouraged in plugin names!
309  */
310 define('PARAM_COMPONENT', 'component');
312 /**
313  * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314  * It is usually used together with context id and component.
315  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
316  */
317 define('PARAM_AREA', 'area');
319 /**
320  * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
321  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322  * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
323  */
324 define('PARAM_PLUGIN', 'plugin');
327 // Web Services.
329 /**
330  * VALUE_REQUIRED - if the parameter is not supplied, there is an error
331  */
332 define('VALUE_REQUIRED', 1);
334 /**
335  * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
336  */
337 define('VALUE_OPTIONAL', 2);
339 /**
340  * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
341  */
342 define('VALUE_DEFAULT', 0);
344 /**
345  * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
346  */
347 define('NULL_NOT_ALLOWED', false);
349 /**
350  * NULL_ALLOWED - the parameter can be set to null in the database
351  */
352 define('NULL_ALLOWED', true);
354 // Page types.
356 /**
357  * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
358  */
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
374 // Tag constants.
375 /**
376  * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377  * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378  * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
379  *
380  * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
381  */
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
417 /**
418  * True if module supports groupmembersonly (which no longer exists)
419  * @deprecated Since Moodle 2.8
420  */
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
442 /** Unspecified module archetype */
443 define('MOD_ARCHETYPE_OTHER', 0);
444 /** Resource-like type module */
445 define('MOD_ARCHETYPE_RESOURCE', 1);
446 /** Assignment module archetype */
447 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448 /** System (not user-addable) module archetype */
449 define('MOD_ARCHETYPE_SYSTEM', 3);
451 /** Return this from modname_get_types callback to use default display in activity chooser */
452 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
454 /**
455  * Security token used for allowing access
456  * from external application such as web services.
457  * Scripts do not use any session, performance is relatively
458  * low because we need to load access info in each request.
459  * Scripts are executed in parallel.
460  */
461 define('EXTERNAL_TOKEN_PERMANENT', 0);
463 /**
464  * Security token used for allowing access
465  * of embedded applications, the code is executed in the
466  * active user session. Token is invalidated after user logs out.
467  * Scripts are executed serially - normal session locking is used.
468  */
469 define('EXTERNAL_TOKEN_EMBEDDED', 1);
471 /**
472  * The home page should be the site home
473  */
474 define('HOMEPAGE_SITE', 0);
475 /**
476  * The home page should be the users my page
477  */
478 define('HOMEPAGE_MY', 1);
479 /**
480  * The home page can be chosen by the user
481  */
482 define('HOMEPAGE_USER', 2);
484 /**
485  * Hub directory url (should be moodle.org)
486  */
487 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
490 /**
491  * Moodle.org url (should be moodle.org)
492  */
493 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
495 /**
496  * Moodle mobile app service name
497  */
498 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
500 /**
501  * Indicates the user has the capabilities required to ignore activity and course file size restrictions
502  */
503 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
505 /**
506  * Course display settings: display all sections on one page.
507  */
508 define('COURSE_DISPLAY_SINGLEPAGE', 0);
509 /**
510  * Course display settings: split pages into a page per section.
511  */
512 define('COURSE_DISPLAY_MULTIPAGE', 1);
514 /**
515  * Authentication constant: String used in password field when password is not stored.
516  */
517 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
519 // PARAMETER HANDLING.
521 /**
522  * Returns a particular value for the named variable, taken from
523  * POST or GET.  If the parameter doesn't exist then an error is
524  * thrown because we require this variable.
525  *
526  * This function should be used to initialise all required values
527  * in a script that are based on parameters.  Usually it will be
528  * used like this:
529  *    $id = required_param('id', PARAM_INT);
530  *
531  * Please note the $type parameter is now required and the value can not be array.
532  *
533  * @param string $parname the name of the page parameter we want
534  * @param string $type expected type of parameter
535  * @return mixed
536  * @throws coding_exception
537  */
538 function required_param($parname, $type) {
539     if (func_num_args() != 2 or empty($parname) or empty($type)) {
540         throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
541     }
542     // POST has precedence.
543     if (isset($_POST[$parname])) {
544         $param = $_POST[$parname];
545     } else if (isset($_GET[$parname])) {
546         $param = $_GET[$parname];
547     } else {
548         print_error('missingparam', '', '', $parname);
549     }
551     if (is_array($param)) {
552         debugging('Invalid array parameter detected in required_param(): '.$parname);
553         // TODO: switch to fatal error in Moodle 2.3.
554         return required_param_array($parname, $type);
555     }
557     return clean_param($param, $type);
560 /**
561  * Returns a particular array value for the named variable, taken from
562  * POST or GET.  If the parameter doesn't exist then an error is
563  * thrown because we require this variable.
564  *
565  * This function should be used to initialise all required values
566  * in a script that are based on parameters.  Usually it will be
567  * used like this:
568  *    $ids = required_param_array('ids', PARAM_INT);
569  *
570  *  Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
571  *
572  * @param string $parname the name of the page parameter we want
573  * @param string $type expected type of parameter
574  * @return array
575  * @throws coding_exception
576  */
577 function required_param_array($parname, $type) {
578     if (func_num_args() != 2 or empty($parname) or empty($type)) {
579         throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
580     }
581     // POST has precedence.
582     if (isset($_POST[$parname])) {
583         $param = $_POST[$parname];
584     } else if (isset($_GET[$parname])) {
585         $param = $_GET[$parname];
586     } else {
587         print_error('missingparam', '', '', $parname);
588     }
589     if (!is_array($param)) {
590         print_error('missingparam', '', '', $parname);
591     }
593     $result = array();
594     foreach ($param as $key => $value) {
595         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
596             debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
597             continue;
598         }
599         $result[$key] = clean_param($value, $type);
600     }
602     return $result;
605 /**
606  * Returns a particular value for the named variable, taken from
607  * POST or GET, otherwise returning a given default.
608  *
609  * This function should be used to initialise all optional values
610  * in a script that are based on parameters.  Usually it will be
611  * used like this:
612  *    $name = optional_param('name', 'Fred', PARAM_TEXT);
613  *
614  * Please note the $type parameter is now required and the value can not be array.
615  *
616  * @param string $parname the name of the page parameter we want
617  * @param mixed  $default the default value to return if nothing is found
618  * @param string $type expected type of parameter
619  * @return mixed
620  * @throws coding_exception
621  */
622 function optional_param($parname, $default, $type) {
623     if (func_num_args() != 3 or empty($parname) or empty($type)) {
624         throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
625     }
627     // POST has precedence.
628     if (isset($_POST[$parname])) {
629         $param = $_POST[$parname];
630     } else if (isset($_GET[$parname])) {
631         $param = $_GET[$parname];
632     } else {
633         return $default;
634     }
636     if (is_array($param)) {
637         debugging('Invalid array parameter detected in required_param(): '.$parname);
638         // TODO: switch to $default in Moodle 2.3.
639         return optional_param_array($parname, $default, $type);
640     }
642     return clean_param($param, $type);
645 /**
646  * Returns a particular array value for the named variable, taken from
647  * POST or GET, otherwise returning a given default.
648  *
649  * This function should be used to initialise all optional values
650  * in a script that are based on parameters.  Usually it will be
651  * used like this:
652  *    $ids = optional_param('id', array(), PARAM_INT);
653  *
654  * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
655  *
656  * @param string $parname the name of the page parameter we want
657  * @param mixed $default the default value to return if nothing is found
658  * @param string $type expected type of parameter
659  * @return array
660  * @throws coding_exception
661  */
662 function optional_param_array($parname, $default, $type) {
663     if (func_num_args() != 3 or empty($parname) or empty($type)) {
664         throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
665     }
667     // POST has precedence.
668     if (isset($_POST[$parname])) {
669         $param = $_POST[$parname];
670     } else if (isset($_GET[$parname])) {
671         $param = $_GET[$parname];
672     } else {
673         return $default;
674     }
675     if (!is_array($param)) {
676         debugging('optional_param_array() expects array parameters only: '.$parname);
677         return $default;
678     }
680     $result = array();
681     foreach ($param as $key => $value) {
682         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
683             debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
684             continue;
685         }
686         $result[$key] = clean_param($value, $type);
687     }
689     return $result;
692 /**
693  * Strict validation of parameter values, the values are only converted
694  * to requested PHP type. Internally it is using clean_param, the values
695  * before and after cleaning must be equal - otherwise
696  * an invalid_parameter_exception is thrown.
697  * Objects and classes are not accepted.
698  *
699  * @param mixed $param
700  * @param string $type PARAM_ constant
701  * @param bool $allownull are nulls valid value?
702  * @param string $debuginfo optional debug information
703  * @return mixed the $param value converted to PHP type
704  * @throws invalid_parameter_exception if $param is not of given type
705  */
706 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
707     if (is_null($param)) {
708         if ($allownull == NULL_ALLOWED) {
709             return null;
710         } else {
711             throw new invalid_parameter_exception($debuginfo);
712         }
713     }
714     if (is_array($param) or is_object($param)) {
715         throw new invalid_parameter_exception($debuginfo);
716     }
718     $cleaned = clean_param($param, $type);
720     if ($type == PARAM_FLOAT) {
721         // Do not detect precision loss here.
722         if (is_float($param) or is_int($param)) {
723             // These always fit.
724         } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
725             throw new invalid_parameter_exception($debuginfo);
726         }
727     } else if ((string)$param !== (string)$cleaned) {
728         // Conversion to string is usually lossless.
729         throw new invalid_parameter_exception($debuginfo);
730     }
732     return $cleaned;
735 /**
736  * Makes sure array contains only the allowed types, this function does not validate array key names!
737  *
738  * <code>
739  * $options = clean_param($options, PARAM_INT);
740  * </code>
741  *
742  * @param array $param the variable array we are cleaning
743  * @param string $type expected format of param after cleaning.
744  * @param bool $recursive clean recursive arrays
745  * @return array
746  * @throws coding_exception
747  */
748 function clean_param_array(array $param = null, $type, $recursive = false) {
749     // Convert null to empty array.
750     $param = (array)$param;
751     foreach ($param as $key => $value) {
752         if (is_array($value)) {
753             if ($recursive) {
754                 $param[$key] = clean_param_array($value, $type, true);
755             } else {
756                 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
757             }
758         } else {
759             $param[$key] = clean_param($value, $type);
760         }
761     }
762     return $param;
765 /**
766  * Used by {@link optional_param()} and {@link required_param()} to
767  * clean the variables and/or cast to specific types, based on
768  * an options field.
769  * <code>
770  * $course->format = clean_param($course->format, PARAM_ALPHA);
771  * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
772  * </code>
773  *
774  * @param mixed $param the variable we are cleaning
775  * @param string $type expected format of param after cleaning.
776  * @return mixed
777  * @throws coding_exception
778  */
779 function clean_param($param, $type) {
780     global $CFG;
782     if (is_array($param)) {
783         throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
784     } else if (is_object($param)) {
785         if (method_exists($param, '__toString')) {
786             $param = $param->__toString();
787         } else {
788             throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
789         }
790     }
792     switch ($type) {
793         case PARAM_RAW:
794             // No cleaning at all.
795             $param = fix_utf8($param);
796             return $param;
798         case PARAM_RAW_TRIMMED:
799             // No cleaning, but strip leading and trailing whitespace.
800             $param = fix_utf8($param);
801             return trim($param);
803         case PARAM_CLEAN:
804             // General HTML cleaning, try to use more specific type if possible this is deprecated!
805             // Please use more specific type instead.
806             if (is_numeric($param)) {
807                 return $param;
808             }
809             $param = fix_utf8($param);
810             // Sweep for scripts, etc.
811             return clean_text($param);
813         case PARAM_CLEANHTML:
814             // Clean html fragment.
815             $param = fix_utf8($param);
816             // Sweep for scripts, etc.
817             $param = clean_text($param, FORMAT_HTML);
818             return trim($param);
820         case PARAM_INT:
821             // Convert to integer.
822             return (int)$param;
824         case PARAM_FLOAT:
825             // Convert to float.
826             return (float)$param;
828         case PARAM_ALPHA:
829             // Remove everything not `a-z`.
830             return preg_replace('/[^a-zA-Z]/i', '', $param);
832         case PARAM_ALPHAEXT:
833             // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
834             return preg_replace('/[^a-zA-Z_-]/i', '', $param);
836         case PARAM_ALPHANUM:
837             // Remove everything not `a-zA-Z0-9`.
838             return preg_replace('/[^A-Za-z0-9]/i', '', $param);
840         case PARAM_ALPHANUMEXT:
841             // Remove everything not `a-zA-Z0-9_-`.
842             return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
844         case PARAM_SEQUENCE:
845             // Remove everything not `0-9,`.
846             return preg_replace('/[^0-9,]/i', '', $param);
848         case PARAM_BOOL:
849             // Convert to 1 or 0.
850             $tempstr = strtolower($param);
851             if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
852                 $param = 1;
853             } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
854                 $param = 0;
855             } else {
856                 $param = empty($param) ? 0 : 1;
857             }
858             return $param;
860         case PARAM_NOTAGS:
861             // Strip all tags.
862             $param = fix_utf8($param);
863             return strip_tags($param);
865         case PARAM_TEXT:
866             // Leave only tags needed for multilang.
867             $param = fix_utf8($param);
868             // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
869             // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
870             do {
871                 if (strpos($param, '</lang>') !== false) {
872                     // Old and future mutilang syntax.
873                     $param = strip_tags($param, '<lang>');
874                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
875                         break;
876                     }
877                     $open = false;
878                     foreach ($matches[0] as $match) {
879                         if ($match === '</lang>') {
880                             if ($open) {
881                                 $open = false;
882                                 continue;
883                             } else {
884                                 break 2;
885                             }
886                         }
887                         if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
888                             break 2;
889                         } else {
890                             $open = true;
891                         }
892                     }
893                     if ($open) {
894                         break;
895                     }
896                     return $param;
898                 } else if (strpos($param, '</span>') !== false) {
899                     // Current problematic multilang syntax.
900                     $param = strip_tags($param, '<span>');
901                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
902                         break;
903                     }
904                     $open = false;
905                     foreach ($matches[0] as $match) {
906                         if ($match === '</span>') {
907                             if ($open) {
908                                 $open = false;
909                                 continue;
910                             } else {
911                                 break 2;
912                             }
913                         }
914                         if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
915                             break 2;
916                         } else {
917                             $open = true;
918                         }
919                     }
920                     if ($open) {
921                         break;
922                     }
923                     return $param;
924                 }
925             } while (false);
926             // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
927             return strip_tags($param);
929         case PARAM_COMPONENT:
930             // We do not want any guessing here, either the name is correct or not
931             // please note only normalised component names are accepted.
932             if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
933                 return '';
934             }
935             if (strpos($param, '__') !== false) {
936                 return '';
937             }
938             if (strpos($param, 'mod_') === 0) {
939                 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
940                 if (substr_count($param, '_') != 1) {
941                     return '';
942                 }
943             }
944             return $param;
946         case PARAM_PLUGIN:
947         case PARAM_AREA:
948             // We do not want any guessing here, either the name is correct or not.
949             if (!is_valid_plugin_name($param)) {
950                 return '';
951             }
952             return $param;
954         case PARAM_SAFEDIR:
955             // Remove everything not a-zA-Z0-9_- .
956             return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
958         case PARAM_SAFEPATH:
959             // Remove everything not a-zA-Z0-9/_- .
960             return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
962         case PARAM_FILE:
963             // Strip all suspicious characters from filename.
964             $param = fix_utf8($param);
965             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
966             if ($param === '.' || $param === '..') {
967                 $param = '';
968             }
969             return $param;
971         case PARAM_PATH:
972             // Strip all suspicious characters from file path.
973             $param = fix_utf8($param);
974             $param = str_replace('\\', '/', $param);
976             // Explode the path and clean each element using the PARAM_FILE rules.
977             $breadcrumb = explode('/', $param);
978             foreach ($breadcrumb as $key => $crumb) {
979                 if ($crumb === '.' && $key === 0) {
980                     // Special condition to allow for relative current path such as ./currentdirfile.txt.
981                 } else {
982                     $crumb = clean_param($crumb, PARAM_FILE);
983                 }
984                 $breadcrumb[$key] = $crumb;
985             }
986             $param = implode('/', $breadcrumb);
988             // Remove multiple current path (./././) and multiple slashes (///).
989             $param = preg_replace('~//+~', '/', $param);
990             $param = preg_replace('~/(\./)+~', '/', $param);
991             return $param;
993         case PARAM_HOST:
994             // Allow FQDN or IPv4 dotted quad.
995             $param = preg_replace('/[^\.\d\w-]/', '', $param );
996             // Match ipv4 dotted quad.
997             if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
998                 // Confirm values are ok.
999                 if ( $match[0] > 255
1000                      || $match[1] > 255
1001                      || $match[3] > 255
1002                      || $match[4] > 255 ) {
1003                     // Hmmm, what kind of dotted quad is this?
1004                     $param = '';
1005                 }
1006             } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1007                        && !preg_match('/^[\.-]/',  $param) // No leading dots/hyphens.
1008                        && !preg_match('/[\.-]$/',  $param) // No trailing dots/hyphens.
1009                        ) {
1010                 // All is ok - $param is respected.
1011             } else {
1012                 // All is not ok...
1013                 $param='';
1014             }
1015             return $param;
1017         case PARAM_URL:          // Allow safe ftp, http, mailto urls.
1018             $param = fix_utf8($param);
1019             include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1020             if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1021                 // All is ok, param is respected.
1022             } else {
1023                 // Not really ok.
1024                 $param ='';
1025             }
1026             return $param;
1028         case PARAM_LOCALURL:
1029             // Allow http absolute, root relative and relative URLs within wwwroot.
1030             $param = clean_param($param, PARAM_URL);
1031             if (!empty($param)) {
1033                 // Simulate the HTTPS version of the site.
1034                 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1036                 if ($param === $CFG->wwwroot) {
1037                     // Exact match;
1038                 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1039                     // Exact match;
1040                 } else if (preg_match(':^/:', $param)) {
1041                     // Root-relative, ok!
1042                 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1043                     // Absolute, and matches our wwwroot.
1044                 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1045                     // Absolute, and matches our httpswwwroot.
1046                 } else {
1047                     // Relative - let's make sure there are no tricks.
1048                     if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1049                         // Looks ok.
1050                     } else {
1051                         $param = '';
1052                     }
1053                 }
1054             }
1055             return $param;
1057         case PARAM_PEM:
1058             $param = trim($param);
1059             // PEM formatted strings may contain letters/numbers and the symbols:
1060             //   forward slash: /
1061             //   plus sign:     +
1062             //   equal sign:    =
1063             //   , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1064             if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1065                 list($wholething, $body) = $matches;
1066                 unset($wholething, $matches);
1067                 $b64 = clean_param($body, PARAM_BASE64);
1068                 if (!empty($b64)) {
1069                     return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1070                 } else {
1071                     return '';
1072                 }
1073             }
1074             return '';
1076         case PARAM_BASE64:
1077             if (!empty($param)) {
1078                 // PEM formatted strings may contain letters/numbers and the symbols
1079                 //   forward slash: /
1080                 //   plus sign:     +
1081                 //   equal sign:    =.
1082                 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1083                     return '';
1084                 }
1085                 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1086                 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1087                 // than (or equal to) 64 characters long.
1088                 for ($i=0, $j=count($lines); $i < $j; $i++) {
1089                     if ($i + 1 == $j) {
1090                         if (64 < strlen($lines[$i])) {
1091                             return '';
1092                         }
1093                         continue;
1094                     }
1096                     if (64 != strlen($lines[$i])) {
1097                         return '';
1098                     }
1099                 }
1100                 return implode("\n", $lines);
1101             } else {
1102                 return '';
1103             }
1105         case PARAM_TAG:
1106             $param = fix_utf8($param);
1107             // Please note it is not safe to use the tag name directly anywhere,
1108             // it must be processed with s(), urlencode() before embedding anywhere.
1109             // Remove some nasties.
1110             $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1111             // Convert many whitespace chars into one.
1112             $param = preg_replace('/\s+/u', ' ', $param);
1113             $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1114             return $param;
1116         case PARAM_TAGLIST:
1117             $param = fix_utf8($param);
1118             $tags = explode(',', $param);
1119             $result = array();
1120             foreach ($tags as $tag) {
1121                 $res = clean_param($tag, PARAM_TAG);
1122                 if ($res !== '') {
1123                     $result[] = $res;
1124                 }
1125             }
1126             if ($result) {
1127                 return implode(',', $result);
1128             } else {
1129                 return '';
1130             }
1132         case PARAM_CAPABILITY:
1133             if (get_capability_info($param)) {
1134                 return $param;
1135             } else {
1136                 return '';
1137             }
1139         case PARAM_PERMISSION:
1140             $param = (int)$param;
1141             if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1142                 return $param;
1143             } else {
1144                 return CAP_INHERIT;
1145             }
1147         case PARAM_AUTH:
1148             $param = clean_param($param, PARAM_PLUGIN);
1149             if (empty($param)) {
1150                 return '';
1151             } else if (exists_auth_plugin($param)) {
1152                 return $param;
1153             } else {
1154                 return '';
1155             }
1157         case PARAM_LANG:
1158             $param = clean_param($param, PARAM_SAFEDIR);
1159             if (get_string_manager()->translation_exists($param)) {
1160                 return $param;
1161             } else {
1162                 // Specified language is not installed or param malformed.
1163                 return '';
1164             }
1166         case PARAM_THEME:
1167             $param = clean_param($param, PARAM_PLUGIN);
1168             if (empty($param)) {
1169                 return '';
1170             } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1171                 return $param;
1172             } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1173                 return $param;
1174             } else {
1175                 // Specified theme is not installed.
1176                 return '';
1177             }
1179         case PARAM_USERNAME:
1180             $param = fix_utf8($param);
1181             $param = trim($param);
1182             // Convert uppercase to lowercase MDL-16919.
1183             $param = core_text::strtolower($param);
1184             if (empty($CFG->extendedusernamechars)) {
1185                 $param = str_replace(" " , "", $param);
1186                 // Regular expression, eliminate all chars EXCEPT:
1187                 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1188                 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1189             }
1190             return $param;
1192         case PARAM_EMAIL:
1193             $param = fix_utf8($param);
1194             if (validate_email($param)) {
1195                 return $param;
1196             } else {
1197                 return '';
1198             }
1200         case PARAM_STRINGID:
1201             if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1202                 return $param;
1203             } else {
1204                 return '';
1205             }
1207         case PARAM_TIMEZONE:
1208             // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1209             $param = fix_utf8($param);
1210             $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1211             if (preg_match($timezonepattern, $param)) {
1212                 return $param;
1213             } else {
1214                 return '';
1215             }
1217         default:
1218             // Doh! throw error, switched parameters in optional_param or another serious problem.
1219             print_error("unknownparamtype", '', '', $type);
1220     }
1223 /**
1224  * Makes sure the data is using valid utf8, invalid characters are discarded.
1225  *
1226  * Note: this function is not intended for full objects with methods and private properties.
1227  *
1228  * @param mixed $value
1229  * @return mixed with proper utf-8 encoding
1230  */
1231 function fix_utf8($value) {
1232     if (is_null($value) or $value === '') {
1233         return $value;
1235     } else if (is_string($value)) {
1236         if ((string)(int)$value === $value) {
1237             // Shortcut.
1238             return $value;
1239         }
1240         // No null bytes expected in our data, so let's remove it.
1241         $value = str_replace("\0", '', $value);
1243         // Note: this duplicates min_fix_utf8() intentionally.
1244         static $buggyiconv = null;
1245         if ($buggyiconv === null) {
1246             $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1247         }
1249         if ($buggyiconv) {
1250             if (function_exists('mb_convert_encoding')) {
1251                 $subst = mb_substitute_character();
1252                 mb_substitute_character('');
1253                 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1254                 mb_substitute_character($subst);
1256             } else {
1257                 // Warn admins on admin/index.php page.
1258                 $result = $value;
1259             }
1261         } else {
1262             $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1263         }
1265         return $result;
1267     } else if (is_array($value)) {
1268         foreach ($value as $k => $v) {
1269             $value[$k] = fix_utf8($v);
1270         }
1271         return $value;
1273     } else if (is_object($value)) {
1274         // Do not modify original.
1275         $value = clone($value);
1276         foreach ($value as $k => $v) {
1277             $value->$k = fix_utf8($v);
1278         }
1279         return $value;
1281     } else {
1282         // This is some other type, no utf-8 here.
1283         return $value;
1284     }
1287 /**
1288  * Return true if given value is integer or string with integer value
1289  *
1290  * @param mixed $value String or Int
1291  * @return bool true if number, false if not
1292  */
1293 function is_number($value) {
1294     if (is_int($value)) {
1295         return true;
1296     } else if (is_string($value)) {
1297         return ((string)(int)$value) === $value;
1298     } else {
1299         return false;
1300     }
1303 /**
1304  * Returns host part from url.
1305  *
1306  * @param string $url full url
1307  * @return string host, null if not found
1308  */
1309 function get_host_from_url($url) {
1310     preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1311     if ($matches) {
1312         return $matches[1];
1313     }
1314     return null;
1317 /**
1318  * Tests whether anything was returned by text editor
1319  *
1320  * This function is useful for testing whether something you got back from
1321  * the HTML editor actually contains anything. Sometimes the HTML editor
1322  * appear to be empty, but actually you get back a <br> tag or something.
1323  *
1324  * @param string $string a string containing HTML.
1325  * @return boolean does the string contain any actual content - that is text,
1326  * images, objects, etc.
1327  */
1328 function html_is_blank($string) {
1329     return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1332 /**
1333  * Set a key in global configuration
1334  *
1335  * Set a key/value pair in both this session's {@link $CFG} global variable
1336  * and in the 'config' database table for future sessions.
1337  *
1338  * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1339  * In that case it doesn't affect $CFG.
1340  *
1341  * A NULL value will delete the entry.
1342  *
1343  * NOTE: this function is called from lib/db/upgrade.php
1344  *
1345  * @param string $name the key to set
1346  * @param string $value the value to set (without magic quotes)
1347  * @param string $plugin (optional) the plugin scope, default null
1348  * @return bool true or exception
1349  */
1350 function set_config($name, $value, $plugin=null) {
1351     global $CFG, $DB;
1353     if (empty($plugin)) {
1354         if (!array_key_exists($name, $CFG->config_php_settings)) {
1355             // So it's defined for this invocation at least.
1356             if (is_null($value)) {
1357                 unset($CFG->$name);
1358             } else {
1359                 // Settings from db are always strings.
1360                 $CFG->$name = (string)$value;
1361             }
1362         }
1364         if ($DB->get_field('config', 'name', array('name' => $name))) {
1365             if ($value === null) {
1366                 $DB->delete_records('config', array('name' => $name));
1367             } else {
1368                 $DB->set_field('config', 'value', $value, array('name' => $name));
1369             }
1370         } else {
1371             if ($value !== null) {
1372                 $config = new stdClass();
1373                 $config->name  = $name;
1374                 $config->value = $value;
1375                 $DB->insert_record('config', $config, false);
1376             }
1377         }
1378         if ($name === 'siteidentifier') {
1379             cache_helper::update_site_identifier($value);
1380         }
1381         cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1382     } else {
1383         // Plugin scope.
1384         if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1385             if ($value===null) {
1386                 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1387             } else {
1388                 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1389             }
1390         } else {
1391             if ($value !== null) {
1392                 $config = new stdClass();
1393                 $config->plugin = $plugin;
1394                 $config->name   = $name;
1395                 $config->value  = $value;
1396                 $DB->insert_record('config_plugins', $config, false);
1397             }
1398         }
1399         cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1400     }
1402     return true;
1405 /**
1406  * Get configuration values from the global config table
1407  * or the config_plugins table.
1408  *
1409  * If called with one parameter, it will load all the config
1410  * variables for one plugin, and return them as an object.
1411  *
1412  * If called with 2 parameters it will return a string single
1413  * value or false if the value is not found.
1414  *
1415  * NOTE: this function is called from lib/db/upgrade.php
1416  *
1417  * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1418  *     that we need only fetch it once per request.
1419  * @param string $plugin full component name
1420  * @param string $name default null
1421  * @return mixed hash-like object or single value, return false no config found
1422  * @throws dml_exception
1423  */
1424 function get_config($plugin, $name = null) {
1425     global $CFG, $DB;
1427     static $siteidentifier = null;
1429     if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1430         $forced =& $CFG->config_php_settings;
1431         $iscore = true;
1432         $plugin = 'core';
1433     } else {
1434         if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1435             $forced =& $CFG->forced_plugin_settings[$plugin];
1436         } else {
1437             $forced = array();
1438         }
1439         $iscore = false;
1440     }
1442     if ($siteidentifier === null) {
1443         try {
1444             // This may fail during installation.
1445             // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1446             // install the database.
1447             $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1448         } catch (dml_exception $ex) {
1449             // Set siteidentifier to false. We don't want to trip this continually.
1450             $siteidentifier = false;
1451             throw $ex;
1452         }
1453     }
1455     if (!empty($name)) {
1456         if (array_key_exists($name, $forced)) {
1457             return (string)$forced[$name];
1458         } else if ($name === 'siteidentifier' && $plugin == 'core') {
1459             return $siteidentifier;
1460         }
1461     }
1463     $cache = cache::make('core', 'config');
1464     $result = $cache->get($plugin);
1465     if ($result === false) {
1466         // The user is after a recordset.
1467         if (!$iscore) {
1468             $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1469         } else {
1470             // This part is not really used any more, but anyway...
1471             $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1472         }
1473         $cache->set($plugin, $result);
1474     }
1476     if (!empty($name)) {
1477         if (array_key_exists($name, $result)) {
1478             return $result[$name];
1479         }
1480         return false;
1481     }
1483     if ($plugin === 'core') {
1484         $result['siteidentifier'] = $siteidentifier;
1485     }
1487     foreach ($forced as $key => $value) {
1488         if (is_null($value) or is_array($value) or is_object($value)) {
1489             // We do not want any extra mess here, just real settings that could be saved in db.
1490             unset($result[$key]);
1491         } else {
1492             // Convert to string as if it went through the DB.
1493             $result[$key] = (string)$value;
1494         }
1495     }
1497     return (object)$result;
1500 /**
1501  * Removes a key from global configuration.
1502  *
1503  * NOTE: this function is called from lib/db/upgrade.php
1504  *
1505  * @param string $name the key to set
1506  * @param string $plugin (optional) the plugin scope
1507  * @return boolean whether the operation succeeded.
1508  */
1509 function unset_config($name, $plugin=null) {
1510     global $CFG, $DB;
1512     if (empty($plugin)) {
1513         unset($CFG->$name);
1514         $DB->delete_records('config', array('name' => $name));
1515         cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1516     } else {
1517         $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1518         cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1519     }
1521     return true;
1524 /**
1525  * Remove all the config variables for a given plugin.
1526  *
1527  * NOTE: this function is called from lib/db/upgrade.php
1528  *
1529  * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1530  * @return boolean whether the operation succeeded.
1531  */
1532 function unset_all_config_for_plugin($plugin) {
1533     global $DB;
1534     // Delete from the obvious config_plugins first.
1535     $DB->delete_records('config_plugins', array('plugin' => $plugin));
1536     // Next delete any suspect settings from config.
1537     $like = $DB->sql_like('name', '?', true, true, false, '|');
1538     $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1539     $DB->delete_records_select('config', $like, $params);
1540     // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1541     cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1543     return true;
1546 /**
1547  * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1548  *
1549  * All users are verified if they still have the necessary capability.
1550  *
1551  * @param string $value the value of the config setting.
1552  * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1553  * @param bool $includeadmins include administrators.
1554  * @return array of user objects.
1555  */
1556 function get_users_from_config($value, $capability, $includeadmins = true) {
1557     if (empty($value) or $value === '$@NONE@$') {
1558         return array();
1559     }
1561     // We have to make sure that users still have the necessary capability,
1562     // it should be faster to fetch them all first and then test if they are present
1563     // instead of validating them one-by-one.
1564     $users = get_users_by_capability(context_system::instance(), $capability);
1565     if ($includeadmins) {
1566         $admins = get_admins();
1567         foreach ($admins as $admin) {
1568             $users[$admin->id] = $admin;
1569         }
1570     }
1572     if ($value === '$@ALL@$') {
1573         return $users;
1574     }
1576     $result = array(); // Result in correct order.
1577     $allowed = explode(',', $value);
1578     foreach ($allowed as $uid) {
1579         if (isset($users[$uid])) {
1580             $user = $users[$uid];
1581             $result[$user->id] = $user;
1582         }
1583     }
1585     return $result;
1589 /**
1590  * Invalidates browser caches and cached data in temp.
1591  *
1592  * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1593  * {@link phpunit_util::reset_dataroot()}
1594  *
1595  * @return void
1596  */
1597 function purge_all_caches() {
1598     global $CFG, $DB;
1600     reset_text_filters_cache();
1601     js_reset_all_caches();
1602     theme_reset_all_caches();
1603     get_string_manager()->reset_caches();
1604     core_text::reset_caches();
1605     if (class_exists('core_plugin_manager')) {
1606         core_plugin_manager::reset_caches();
1607     }
1609     // Bump up cacherev field for all courses.
1610     try {
1611         increment_revision_number('course', 'cacherev', '');
1612     } catch (moodle_exception $e) {
1613         // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1614     }
1616     $DB->reset_caches();
1617     cache_helper::purge_all();
1619     // Purge all other caches: rss, simplepie, etc.
1620     remove_dir($CFG->cachedir.'', true);
1622     // Make sure cache dir is writable, throws exception if not.
1623     make_cache_directory('');
1625     // This is the only place where we purge local caches, we are only adding files there.
1626     // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1627     remove_dir($CFG->localcachedir, true);
1628     set_config('localcachedirpurged', time());
1629     make_localcache_directory('', true);
1630     \core\task\manager::clear_static_caches();
1633 /**
1634  * Get volatile flags
1635  *
1636  * @param string $type
1637  * @param int $changedsince default null
1638  * @return array records array
1639  */
1640 function get_cache_flags($type, $changedsince = null) {
1641     global $DB;
1643     $params = array('type' => $type, 'expiry' => time());
1644     $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1645     if ($changedsince !== null) {
1646         $params['changedsince'] = $changedsince;
1647         $sqlwhere .= " AND timemodified > :changedsince";
1648     }
1649     $cf = array();
1650     if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1651         foreach ($flags as $flag) {
1652             $cf[$flag->name] = $flag->value;
1653         }
1654     }
1655     return $cf;
1658 /**
1659  * Get volatile flags
1660  *
1661  * @param string $type
1662  * @param string $name
1663  * @param int $changedsince default null
1664  * @return string|false The cache flag value or false
1665  */
1666 function get_cache_flag($type, $name, $changedsince=null) {
1667     global $DB;
1669     $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1671     $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1672     if ($changedsince !== null) {
1673         $params['changedsince'] = $changedsince;
1674         $sqlwhere .= " AND timemodified > :changedsince";
1675     }
1677     return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1680 /**
1681  * Set a volatile flag
1682  *
1683  * @param string $type the "type" namespace for the key
1684  * @param string $name the key to set
1685  * @param string $value the value to set (without magic quotes) - null will remove the flag
1686  * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1687  * @return bool Always returns true
1688  */
1689 function set_cache_flag($type, $name, $value, $expiry = null) {
1690     global $DB;
1692     $timemodified = time();
1693     if ($expiry === null || $expiry < $timemodified) {
1694         $expiry = $timemodified + 24 * 60 * 60;
1695     } else {
1696         $expiry = (int)$expiry;
1697     }
1699     if ($value === null) {
1700         unset_cache_flag($type, $name);
1701         return true;
1702     }
1704     if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1705         // This is a potential problem in DEBUG_DEVELOPER.
1706         if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1707             return true; // No need to update.
1708         }
1709         $f->value        = $value;
1710         $f->expiry       = $expiry;
1711         $f->timemodified = $timemodified;
1712         $DB->update_record('cache_flags', $f);
1713     } else {
1714         $f = new stdClass();
1715         $f->flagtype     = $type;
1716         $f->name         = $name;
1717         $f->value        = $value;
1718         $f->expiry       = $expiry;
1719         $f->timemodified = $timemodified;
1720         $DB->insert_record('cache_flags', $f);
1721     }
1722     return true;
1725 /**
1726  * Removes a single volatile flag
1727  *
1728  * @param string $type the "type" namespace for the key
1729  * @param string $name the key to set
1730  * @return bool
1731  */
1732 function unset_cache_flag($type, $name) {
1733     global $DB;
1734     $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1735     return true;
1738 /**
1739  * Garbage-collect volatile flags
1740  *
1741  * @return bool Always returns true
1742  */
1743 function gc_cache_flags() {
1744     global $DB;
1745     $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1746     return true;
1749 // USER PREFERENCE API.
1751 /**
1752  * Refresh user preference cache. This is used most often for $USER
1753  * object that is stored in session, but it also helps with performance in cron script.
1754  *
1755  * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1756  *
1757  * @package  core
1758  * @category preference
1759  * @access   public
1760  * @param    stdClass         $user          User object. Preferences are preloaded into 'preference' property
1761  * @param    int              $cachelifetime Cache life time on the current page (in seconds)
1762  * @throws   coding_exception
1763  * @return   null
1764  */
1765 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1766     global $DB;
1767     // Static cache, we need to check on each page load, not only every 2 minutes.
1768     static $loadedusers = array();
1770     if (!isset($user->id)) {
1771         throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1772     }
1774     if (empty($user->id) or isguestuser($user->id)) {
1775         // No permanent storage for not-logged-in users and guest.
1776         if (!isset($user->preference)) {
1777             $user->preference = array();
1778         }
1779         return;
1780     }
1782     $timenow = time();
1784     if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1785         // Already loaded at least once on this page. Are we up to date?
1786         if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1787             // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1788             return;
1790         } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1791             // No change since the lastcheck on this page.
1792             $user->preference['_lastloaded'] = $timenow;
1793             return;
1794         }
1795     }
1797     // OK, so we have to reload all preferences.
1798     $loadedusers[$user->id] = true;
1799     $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1800     $user->preference['_lastloaded'] = $timenow;
1803 /**
1804  * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1805  *
1806  * NOTE: internal function, do not call from other code.
1807  *
1808  * @package core
1809  * @access private
1810  * @param integer $userid the user whose prefs were changed.
1811  */
1812 function mark_user_preferences_changed($userid) {
1813     global $CFG;
1815     if (empty($userid) or isguestuser($userid)) {
1816         // No cache flags for guest and not-logged-in users.
1817         return;
1818     }
1820     set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1823 /**
1824  * Sets a preference for the specified user.
1825  *
1826  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1827  *
1828  * @package  core
1829  * @category preference
1830  * @access   public
1831  * @param    string            $name  The key to set as preference for the specified user
1832  * @param    string            $value The value to set for the $name key in the specified user's
1833  *                                    record, null means delete current value.
1834  * @param    stdClass|int|null $user  A moodle user object or id, null means current user
1835  * @throws   coding_exception
1836  * @return   bool                     Always true or exception
1837  */
1838 function set_user_preference($name, $value, $user = null) {
1839     global $USER, $DB;
1841     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1842         throw new coding_exception('Invalid preference name in set_user_preference() call');
1843     }
1845     if (is_null($value)) {
1846         // Null means delete current.
1847         return unset_user_preference($name, $user);
1848     } else if (is_object($value)) {
1849         throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1850     } else if (is_array($value)) {
1851         throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1852     }
1853     // Value column maximum length is 1333 characters.
1854     $value = (string)$value;
1855     if (core_text::strlen($value) > 1333) {
1856         throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1857     }
1859     if (is_null($user)) {
1860         $user = $USER;
1861     } else if (isset($user->id)) {
1862         // It is a valid object.
1863     } else if (is_numeric($user)) {
1864         $user = (object)array('id' => (int)$user);
1865     } else {
1866         throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1867     }
1869     check_user_preferences_loaded($user);
1871     if (empty($user->id) or isguestuser($user->id)) {
1872         // No permanent storage for not-logged-in users and guest.
1873         $user->preference[$name] = $value;
1874         return true;
1875     }
1877     if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1878         if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1879             // Preference already set to this value.
1880             return true;
1881         }
1882         $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1884     } else {
1885         $preference = new stdClass();
1886         $preference->userid = $user->id;
1887         $preference->name   = $name;
1888         $preference->value  = $value;
1889         $DB->insert_record('user_preferences', $preference);
1890     }
1892     // Update value in cache.
1893     $user->preference[$name] = $value;
1895     // Set reload flag for other sessions.
1896     mark_user_preferences_changed($user->id);
1898     return true;
1901 /**
1902  * Sets a whole array of preferences for the current user
1903  *
1904  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1905  *
1906  * @package  core
1907  * @category preference
1908  * @access   public
1909  * @param    array             $prefarray An array of key/value pairs to be set
1910  * @param    stdClass|int|null $user      A moodle user object or id, null means current user
1911  * @return   bool                         Always true or exception
1912  */
1913 function set_user_preferences(array $prefarray, $user = null) {
1914     foreach ($prefarray as $name => $value) {
1915         set_user_preference($name, $value, $user);
1916     }
1917     return true;
1920 /**
1921  * Unsets a preference completely by deleting it from the database
1922  *
1923  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1924  *
1925  * @package  core
1926  * @category preference
1927  * @access   public
1928  * @param    string            $name The key to unset as preference for the specified user
1929  * @param    stdClass|int|null $user A moodle user object or id, null means current user
1930  * @throws   coding_exception
1931  * @return   bool                    Always true or exception
1932  */
1933 function unset_user_preference($name, $user = null) {
1934     global $USER, $DB;
1936     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1937         throw new coding_exception('Invalid preference name in unset_user_preference() call');
1938     }
1940     if (is_null($user)) {
1941         $user = $USER;
1942     } else if (isset($user->id)) {
1943         // It is a valid object.
1944     } else if (is_numeric($user)) {
1945         $user = (object)array('id' => (int)$user);
1946     } else {
1947         throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1948     }
1950     check_user_preferences_loaded($user);
1952     if (empty($user->id) or isguestuser($user->id)) {
1953         // No permanent storage for not-logged-in user and guest.
1954         unset($user->preference[$name]);
1955         return true;
1956     }
1958     // Delete from DB.
1959     $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1961     // Delete the preference from cache.
1962     unset($user->preference[$name]);
1964     // Set reload flag for other sessions.
1965     mark_user_preferences_changed($user->id);
1967     return true;
1970 /**
1971  * Used to fetch user preference(s)
1972  *
1973  * If no arguments are supplied this function will return
1974  * all of the current user preferences as an array.
1975  *
1976  * If a name is specified then this function
1977  * attempts to return that particular preference value.  If
1978  * none is found, then the optional value $default is returned,
1979  * otherwise null.
1980  *
1981  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1982  *
1983  * @package  core
1984  * @category preference
1985  * @access   public
1986  * @param    string            $name    Name of the key to use in finding a preference value
1987  * @param    mixed|null        $default Value to be returned if the $name key is not set in the user preferences
1988  * @param    stdClass|int|null $user    A moodle user object or id, null means current user
1989  * @throws   coding_exception
1990  * @return   string|mixed|null          A string containing the value of a single preference. An
1991  *                                      array with all of the preferences or null
1992  */
1993 function get_user_preferences($name = null, $default = null, $user = null) {
1994     global $USER;
1996     if (is_null($name)) {
1997         // All prefs.
1998     } else if (is_numeric($name) or $name === '_lastloaded') {
1999         throw new coding_exception('Invalid preference name in get_user_preferences() call');
2000     }
2002     if (is_null($user)) {
2003         $user = $USER;
2004     } else if (isset($user->id)) {
2005         // Is a valid object.
2006     } else if (is_numeric($user)) {
2007         $user = (object)array('id' => (int)$user);
2008     } else {
2009         throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2010     }
2012     check_user_preferences_loaded($user);
2014     if (empty($name)) {
2015         // All values.
2016         return $user->preference;
2017     } else if (isset($user->preference[$name])) {
2018         // The single string value.
2019         return $user->preference[$name];
2020     } else {
2021         // Default value (null if not specified).
2022         return $default;
2023     }
2026 // FUNCTIONS FOR HANDLING TIME.
2028 /**
2029  * Given Gregorian date parts in user time produce a GMT timestamp.
2030  *
2031  * @package core
2032  * @category time
2033  * @param int $year The year part to create timestamp of
2034  * @param int $month The month part to create timestamp of
2035  * @param int $day The day part to create timestamp of
2036  * @param int $hour The hour part to create timestamp of
2037  * @param int $minute The minute part to create timestamp of
2038  * @param int $second The second part to create timestamp of
2039  * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2040  *             if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2041  * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2042  *             applied only if timezone is 99 or string.
2043  * @return int GMT timestamp
2044  */
2045 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2046     $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2047     $date->setDate((int)$year, (int)$month, (int)$day);
2048     $date->setTime((int)$hour, (int)$minute, (int)$second);
2050     $time = $date->getTimestamp();
2052     // Moodle BC DST stuff.
2053     if (!$applydst) {
2054         $time += dst_offset_on($time, $timezone);
2055     }
2057     return $time;
2061 /**
2062  * Format a date/time (seconds) as weeks, days, hours etc as needed
2063  *
2064  * Given an amount of time in seconds, returns string
2065  * formatted nicely as weeks, days, hours etc as needed
2066  *
2067  * @package core
2068  * @category time
2069  * @uses MINSECS
2070  * @uses HOURSECS
2071  * @uses DAYSECS
2072  * @uses YEARSECS
2073  * @param int $totalsecs Time in seconds
2074  * @param stdClass $str Should be a time object
2075  * @return string A nicely formatted date/time string
2076  */
2077 function format_time($totalsecs, $str = null) {
2079     $totalsecs = abs($totalsecs);
2081     if (!$str) {
2082         // Create the str structure the slow way.
2083         $str = new stdClass();
2084         $str->day   = get_string('day');
2085         $str->days  = get_string('days');
2086         $str->hour  = get_string('hour');
2087         $str->hours = get_string('hours');
2088         $str->min   = get_string('min');
2089         $str->mins  = get_string('mins');
2090         $str->sec   = get_string('sec');
2091         $str->secs  = get_string('secs');
2092         $str->year  = get_string('year');
2093         $str->years = get_string('years');
2094     }
2096     $years     = floor($totalsecs/YEARSECS);
2097     $remainder = $totalsecs - ($years*YEARSECS);
2098     $days      = floor($remainder/DAYSECS);
2099     $remainder = $totalsecs - ($days*DAYSECS);
2100     $hours     = floor($remainder/HOURSECS);
2101     $remainder = $remainder - ($hours*HOURSECS);
2102     $mins      = floor($remainder/MINSECS);
2103     $secs      = $remainder - ($mins*MINSECS);
2105     $ss = ($secs == 1)  ? $str->sec  : $str->secs;
2106     $sm = ($mins == 1)  ? $str->min  : $str->mins;
2107     $sh = ($hours == 1) ? $str->hour : $str->hours;
2108     $sd = ($days == 1)  ? $str->day  : $str->days;
2109     $sy = ($years == 1)  ? $str->year  : $str->years;
2111     $oyears = '';
2112     $odays = '';
2113     $ohours = '';
2114     $omins = '';
2115     $osecs = '';
2117     if ($years) {
2118         $oyears  = $years .' '. $sy;
2119     }
2120     if ($days) {
2121         $odays  = $days .' '. $sd;
2122     }
2123     if ($hours) {
2124         $ohours = $hours .' '. $sh;
2125     }
2126     if ($mins) {
2127         $omins  = $mins .' '. $sm;
2128     }
2129     if ($secs) {
2130         $osecs  = $secs .' '. $ss;
2131     }
2133     if ($years) {
2134         return trim($oyears .' '. $odays);
2135     }
2136     if ($days) {
2137         return trim($odays .' '. $ohours);
2138     }
2139     if ($hours) {
2140         return trim($ohours .' '. $omins);
2141     }
2142     if ($mins) {
2143         return trim($omins .' '. $osecs);
2144     }
2145     if ($secs) {
2146         return $osecs;
2147     }
2148     return get_string('now');
2151 /**
2152  * Returns a formatted string that represents a date in user time.
2153  *
2154  * @package core
2155  * @category time
2156  * @param int $date the timestamp in UTC, as obtained from the database.
2157  * @param string $format strftime format. You should probably get this using
2158  *        get_string('strftime...', 'langconfig');
2159  * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2160  *        not 99 then daylight saving will not be added.
2161  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2162  * @param bool $fixday If true (default) then the leading zero from %d is removed.
2163  *        If false then the leading zero is maintained.
2164  * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2165  * @return string the formatted date/time.
2166  */
2167 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2168     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2169     return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2172 /**
2173  * Returns a formatted date ensuring it is UTF-8.
2174  *
2175  * If we are running under Windows convert to Windows encoding and then back to UTF-8
2176  * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2177  *
2178  * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2179  * @param string $format strftime format.
2180  * @param int|float|string $tz the user timezone
2181  * @return string the formatted date/time.
2182  * @since Moodle 2.3.3
2183  */
2184 function date_format_string($date, $format, $tz = 99) {
2185     global $CFG;
2187     $localewincharset = null;
2188     // Get the calendar type user is using.
2189     if ($CFG->ostype == 'WINDOWS') {
2190         $calendartype = \core_calendar\type_factory::get_calendar_instance();
2191         $localewincharset = $calendartype->locale_win_charset();
2192     }
2194     if ($localewincharset) {
2195         $format = core_text::convert($format, 'utf-8', $localewincharset);
2196     }
2198     date_default_timezone_set(core_date::get_user_timezone($tz));
2199     $datestring = strftime($format, $date);
2200     core_date::set_default_server_timezone();
2202     if ($localewincharset) {
2203         $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2204     }
2206     return $datestring;
2209 /**
2210  * Given a $time timestamp in GMT (seconds since epoch),
2211  * returns an array that represents the Gregorian date in user time
2212  *
2213  * @package core
2214  * @category time
2215  * @param int $time Timestamp in GMT
2216  * @param float|int|string $timezone user timezone
2217  * @return array An array that represents the date in user time
2218  */
2219 function usergetdate($time, $timezone=99) {
2220     date_default_timezone_set(core_date::get_user_timezone($timezone));
2221     $result = getdate($time);
2222     core_date::set_default_server_timezone();
2224     return $result;
2227 /**
2228  * Given a GMT timestamp (seconds since epoch), offsets it by
2229  * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2230  *
2231  * NOTE: this function does not include DST properly,
2232  *       you should use the PHP date stuff instead!
2233  *
2234  * @package core
2235  * @category time
2236  * @param int $date Timestamp in GMT
2237  * @param float|int|string $timezone user timezone
2238  * @return int
2239  */
2240 function usertime($date, $timezone=99) {
2241     $userdate = new DateTime('@' . $date);
2242     $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2243     $dst = dst_offset_on($date, $timezone);
2245     return $date - $userdate->getOffset() + $dst;
2248 /**
2249  * Given a time, return the GMT timestamp of the most recent midnight
2250  * for the current user.
2251  *
2252  * @package core
2253  * @category time
2254  * @param int $date Timestamp in GMT
2255  * @param float|int|string $timezone user timezone
2256  * @return int Returns a GMT timestamp
2257  */
2258 function usergetmidnight($date, $timezone=99) {
2260     $userdate = usergetdate($date, $timezone);
2262     // Time of midnight of this user's day, in GMT.
2263     return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2267 /**
2268  * Returns a string that prints the user's timezone
2269  *
2270  * @package core
2271  * @category time
2272  * @param float|int|string $timezone user timezone
2273  * @return string
2274  */
2275 function usertimezone($timezone=99) {
2276     $tz = core_date::get_user_timezone($timezone);
2277     return core_date::get_localised_timezone($tz);
2280 /**
2281  * Returns a float or a string which denotes the user's timezone
2282  * 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)
2283  * means that for this timezone there are also DST rules to be taken into account
2284  * Checks various settings and picks the most dominant of those which have a value
2285  *
2286  * @package core
2287  * @category time
2288  * @param float|int|string $tz timezone to calculate GMT time offset before
2289  *        calculating user timezone, 99 is default user timezone
2290  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2291  * @return float|string
2292  */
2293 function get_user_timezone($tz = 99) {
2294     global $USER, $CFG;
2296     $timezones = array(
2297         $tz,
2298         isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2299         isset($USER->timezone) ? $USER->timezone : 99,
2300         isset($CFG->timezone) ? $CFG->timezone : 99,
2301         );
2303     $tz = 99;
2305     // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2306     while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2307         $tz = $next['value'];
2308     }
2309     return is_numeric($tz) ? (float) $tz : $tz;
2312 /**
2313  * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2314  * - Note: Daylight saving only works for string timezones and not for float.
2315  *
2316  * @package core
2317  * @category time
2318  * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2319  * @param int|float|string $strtimezone user timezone
2320  * @return int
2321  */
2322 function dst_offset_on($time, $strtimezone = null) {
2323     $tz = core_date::get_user_timezone($strtimezone);
2324     $date = new DateTime('@' . $time);
2325     $date->setTimezone(new DateTimeZone($tz));
2326     if ($date->format('I') == '1') {
2327         if ($tz === 'Australia/Lord_Howe') {
2328             return 1800;
2329         }
2330         return 3600;
2331     }
2332     return 0;
2335 /**
2336  * Calculates when the day appears in specific month
2337  *
2338  * @package core
2339  * @category time
2340  * @param int $startday starting day of the month
2341  * @param int $weekday The day when week starts (normally taken from user preferences)
2342  * @param int $month The month whose day is sought
2343  * @param int $year The year of the month whose day is sought
2344  * @return int
2345  */
2346 function find_day_in_month($startday, $weekday, $month, $year) {
2347     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2349     $daysinmonth = days_in_month($month, $year);
2350     $daysinweek = count($calendartype->get_weekdays());
2352     if ($weekday == -1) {
2353         // Don't care about weekday, so return:
2354         //    abs($startday) if $startday != -1
2355         //    $daysinmonth otherwise.
2356         return ($startday == -1) ? $daysinmonth : abs($startday);
2357     }
2359     // From now on we 're looking for a specific weekday.
2360     // Give "end of month" its actual value, since we know it.
2361     if ($startday == -1) {
2362         $startday = -1 * $daysinmonth;
2363     }
2365     // Starting from day $startday, the sign is the direction.
2366     if ($startday < 1) {
2367         $startday = abs($startday);
2368         $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2370         // This is the last such weekday of the month.
2371         $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2372         if ($lastinmonth > $daysinmonth) {
2373             $lastinmonth -= $daysinweek;
2374         }
2376         // Find the first such weekday <= $startday.
2377         while ($lastinmonth > $startday) {
2378             $lastinmonth -= $daysinweek;
2379         }
2381         return $lastinmonth;
2382     } else {
2383         $indexweekday = dayofweek($startday, $month, $year);
2385         $diff = $weekday - $indexweekday;
2386         if ($diff < 0) {
2387             $diff += $daysinweek;
2388         }
2390         // This is the first such weekday of the month equal to or after $startday.
2391         $firstfromindex = $startday + $diff;
2393         return $firstfromindex;
2394     }
2397 /**
2398  * Calculate the number of days in a given month
2399  *
2400  * @package core
2401  * @category time
2402  * @param int $month The month whose day count is sought
2403  * @param int $year The year of the month whose day count is sought
2404  * @return int
2405  */
2406 function days_in_month($month, $year) {
2407     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2408     return $calendartype->get_num_days_in_month($year, $month);
2411 /**
2412  * Calculate the position in the week of a specific calendar day
2413  *
2414  * @package core
2415  * @category time
2416  * @param int $day The day of the date whose position in the week is sought
2417  * @param int $month The month of the date whose position in the week is sought
2418  * @param int $year The year of the date whose position in the week is sought
2419  * @return int
2420  */
2421 function dayofweek($day, $month, $year) {
2422     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2423     return $calendartype->get_weekday($year, $month, $day);
2426 // USER AUTHENTICATION AND LOGIN.
2428 /**
2429  * Returns full login url.
2430  *
2431  * @return string login url
2432  */
2433 function get_login_url() {
2434     global $CFG;
2436     $url = "$CFG->wwwroot/login/index.php";
2438     if (!empty($CFG->loginhttps)) {
2439         $url = str_replace('http:', 'https:', $url);
2440     }
2442     return $url;
2445 /**
2446  * This function checks that the current user is logged in and has the
2447  * required privileges
2448  *
2449  * This function checks that the current user is logged in, and optionally
2450  * whether they are allowed to be in a particular course and view a particular
2451  * course module.
2452  * If they are not logged in, then it redirects them to the site login unless
2453  * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2454  * case they are automatically logged in as guests.
2455  * If $courseid is given and the user is not enrolled in that course then the
2456  * user is redirected to the course enrolment page.
2457  * If $cm is given and the course module is hidden and the user is not a teacher
2458  * in the course then the user is redirected to the course home page.
2459  *
2460  * When $cm parameter specified, this function sets page layout to 'module'.
2461  * You need to change it manually later if some other layout needed.
2462  *
2463  * @package    core_access
2464  * @category   access
2465  *
2466  * @param mixed $courseorid id of the course or course object
2467  * @param bool $autologinguest default true
2468  * @param object $cm course module object
2469  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2470  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2471  *             in order to keep redirects working properly. MDL-14495
2472  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2473  * @return mixed Void, exit, and die depending on path
2474  * @throws coding_exception
2475  * @throws require_login_exception
2476  */
2477 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2478     global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2480     // Must not redirect when byteserving already started.
2481     if (!empty($_SERVER['HTTP_RANGE'])) {
2482         $preventredirect = true;
2483     }
2485     if (AJAX_SCRIPT) {
2486         // We cannot redirect for AJAX scripts either.
2487         $preventredirect = true;
2488     }
2490     // Setup global $COURSE, themes, language and locale.
2491     if (!empty($courseorid)) {
2492         if (is_object($courseorid)) {
2493             $course = $courseorid;
2494         } else if ($courseorid == SITEID) {
2495             $course = clone($SITE);
2496         } else {
2497             $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2498         }
2499         if ($cm) {
2500             if ($cm->course != $course->id) {
2501                 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2502             }
2503             // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2504             if (!($cm instanceof cm_info)) {
2505                 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2506                 // db queries so this is not really a performance concern, however it is obviously
2507                 // better if you use get_fast_modinfo to get the cm before calling this.
2508                 $modinfo = get_fast_modinfo($course);
2509                 $cm = $modinfo->get_cm($cm->id);
2510             }
2511         }
2512     } else {
2513         // Do not touch global $COURSE via $PAGE->set_course(),
2514         // the reasons is we need to be able to call require_login() at any time!!
2515         $course = $SITE;
2516         if ($cm) {
2517             throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2518         }
2519     }
2521     // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2522     // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2523     // risk leading the user back to the AJAX request URL.
2524     if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2525         $setwantsurltome = false;
2526     }
2528     // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2529     if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2530         if ($preventredirect) {
2531             throw new require_login_session_timeout_exception();
2532         } else {
2533             if ($setwantsurltome) {
2534                 $SESSION->wantsurl = qualified_me();
2535             }
2536             redirect(get_login_url());
2537         }
2538     }
2540     // If the user is not even logged in yet then make sure they are.
2541     if (!isloggedin()) {
2542         if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2543             if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2544                 // Misconfigured site guest, just redirect to login page.
2545                 redirect(get_login_url());
2546                 exit; // Never reached.
2547             }
2548             $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2549             complete_user_login($guest);
2550             $USER->autologinguest = true;
2551             $SESSION->lang = $lang;
2552         } else {
2553             // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2554             if ($preventredirect) {
2555                 throw new require_login_exception('You are not logged in');
2556             }
2558             if ($setwantsurltome) {
2559                 $SESSION->wantsurl = qualified_me();
2560             }
2562             $referer = get_local_referer(false);
2563             if (!empty($referer)) {
2564                 $SESSION->fromurl = $referer;
2565             }
2567             // Give auth plugins an opportunity to authenticate or redirect to an external login page
2568             $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2569             foreach($authsequence as $authname) {
2570                 $authplugin = get_auth_plugin($authname);
2571                 $authplugin->pre_loginpage_hook();
2572                 if (isloggedin()) {
2573                     break;
2574                 }
2575             }
2577             // If we're still not logged in then go to the login page
2578             if (!isloggedin()) {
2579                 redirect(get_login_url());
2580                 exit; // Never reached.
2581             }
2582         }
2583     }
2585     // Loginas as redirection if needed.
2586     if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2587         if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2588             if ($USER->loginascontext->instanceid != $course->id) {
2589                 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2590             }
2591         }
2592     }
2594     // Check whether the user should be changing password (but only if it is REALLY them).
2595     if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2596         $userauth = get_auth_plugin($USER->auth);
2597         if ($userauth->can_change_password() and !$preventredirect) {
2598             if ($setwantsurltome) {
2599                 $SESSION->wantsurl = qualified_me();
2600             }
2601             if ($changeurl = $userauth->change_password_url()) {
2602                 // Use plugin custom url.
2603                 redirect($changeurl);
2604             } else {
2605                 // Use moodle internal method.
2606                 if (empty($CFG->loginhttps)) {
2607                     redirect($CFG->wwwroot .'/login/change_password.php');
2608                 } else {
2609                     $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2610                     redirect($wwwroot .'/login/change_password.php');
2611                 }
2612             }
2613         } else {
2614             print_error('nopasswordchangeforced', 'auth');
2615         }
2616     }
2618     // Check that the user account is properly set up.
2619     if (user_not_fully_set_up($USER)) {
2620         if ($preventredirect) {
2621             throw new require_login_exception('User not fully set-up');
2622         }
2623         if ($setwantsurltome) {
2624             $SESSION->wantsurl = qualified_me();
2625         }
2626         redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2627     }
2629     // Make sure the USER has a sesskey set up. Used for CSRF protection.
2630     sesskey();
2632     // Do not bother admins with any formalities.
2633     if (is_siteadmin()) {
2634         // Set the global $COURSE.
2635         if ($cm) {
2636             $PAGE->set_cm($cm, $course);
2637             $PAGE->set_pagelayout('incourse');
2638         } else if (!empty($courseorid)) {
2639             $PAGE->set_course($course);
2640         }
2641         // Set accesstime or the user will appear offline which messes up messaging.
2642         user_accesstime_log($course->id);
2643         return;
2644     }
2646     // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2647     if (!$USER->policyagreed and !is_siteadmin()) {
2648         if (!empty($CFG->sitepolicy) and !isguestuser()) {
2649             if ($preventredirect) {
2650                 throw new require_login_exception('Policy not agreed');
2651             }
2652             if ($setwantsurltome) {
2653                 $SESSION->wantsurl = qualified_me();
2654             }
2655             redirect($CFG->wwwroot .'/user/policy.php');
2656         } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2657             if ($preventredirect) {
2658                 throw new require_login_exception('Policy not agreed');
2659             }
2660             if ($setwantsurltome) {
2661                 $SESSION->wantsurl = qualified_me();
2662             }
2663             redirect($CFG->wwwroot .'/user/policy.php');
2664         }
2665     }
2667     // Fetch the system context, the course context, and prefetch its child contexts.
2668     $sysctx = context_system::instance();
2669     $coursecontext = context_course::instance($course->id, MUST_EXIST);
2670     if ($cm) {
2671         $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2672     } else {
2673         $cmcontext = null;
2674     }
2676     // If the site is currently under maintenance, then print a message.
2677     if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2678         if ($preventredirect) {
2679             throw new require_login_exception('Maintenance in progress');
2680         }
2682         print_maintenance_message();
2683     }
2685     // Make sure the course itself is not hidden.
2686     if ($course->id == SITEID) {
2687         // Frontpage can not be hidden.
2688     } else {
2689         if (is_role_switched($course->id)) {
2690             // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2691         } else {
2692             if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2693                 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2694                 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2695                 if ($preventredirect) {
2696                     throw new require_login_exception('Course is hidden');
2697                 }
2698                 $PAGE->set_context(null);
2699                 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2700                 // the navigation will mess up when trying to find it.
2701                 navigation_node::override_active_url(new moodle_url('/'));
2702                 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2703             }
2704         }
2705     }
2707     // Is the user enrolled?
2708     if ($course->id == SITEID) {
2709         // Everybody is enrolled on the frontpage.
2710     } else {
2711         if (\core\session\manager::is_loggedinas()) {
2712             // Make sure the REAL person can access this course first.
2713             $realuser = \core\session\manager::get_realuser();
2714             if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2715                 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2716                 if ($preventredirect) {
2717                     throw new require_login_exception('Invalid course login-as access');
2718                 }
2719                 $PAGE->set_context(null);
2720                 echo $OUTPUT->header();
2721                 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2722             }
2723         }
2725         $access = false;
2727         if (is_role_switched($course->id)) {
2728             // Ok, user had to be inside this course before the switch.
2729             $access = true;
2731         } else if (is_viewing($coursecontext, $USER)) {
2732             // Ok, no need to mess with enrol.
2733             $access = true;
2735         } else {
2736             if (isset($USER->enrol['enrolled'][$course->id])) {
2737                 if ($USER->enrol['enrolled'][$course->id] > time()) {
2738                     $access = true;
2739                     if (isset($USER->enrol['tempguest'][$course->id])) {
2740                         unset($USER->enrol['tempguest'][$course->id]);
2741                         remove_temp_course_roles($coursecontext);
2742                     }
2743                 } else {
2744                     // Expired.
2745                     unset($USER->enrol['enrolled'][$course->id]);
2746                 }
2747             }
2748             if (isset($USER->enrol['tempguest'][$course->id])) {
2749                 if ($USER->enrol['tempguest'][$course->id] == 0) {
2750                     $access = true;
2751                 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2752                     $access = true;
2753                 } else {
2754                     // Expired.
2755                     unset($USER->enrol['tempguest'][$course->id]);
2756                     remove_temp_course_roles($coursecontext);
2757                 }
2758             }
2760             if (!$access) {
2761                 // Cache not ok.
2762                 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2763                 if ($until !== false) {
2764                     // Active participants may always access, a timestamp in the future, 0 (always) or false.
2765                     if ($until == 0) {
2766                         $until = ENROL_MAX_TIMESTAMP;
2767                     }
2768                     $USER->enrol['enrolled'][$course->id] = $until;
2769                     $access = true;
2771                 } else {
2772                     $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2773                     $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2774                     $enrols = enrol_get_plugins(true);
2775                     // First ask all enabled enrol instances in course if they want to auto enrol user.
2776                     foreach ($instances as $instance) {
2777                         if (!isset($enrols[$instance->enrol])) {
2778                             continue;
2779                         }
2780                         // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2781                         $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2782                         if ($until !== false) {
2783                             if ($until == 0) {
2784                                 $until = ENROL_MAX_TIMESTAMP;
2785                             }
2786                             $USER->enrol['enrolled'][$course->id] = $until;
2787                             $access = true;
2788                             break;
2789                         }
2790                     }
2791                     // If not enrolled yet try to gain temporary guest access.
2792                     if (!$access) {
2793                         foreach ($instances as $instance) {
2794                             if (!isset($enrols[$instance->enrol])) {
2795                                 continue;
2796                             }
2797                             // Get a duration for the guest access, a timestamp in the future or false.
2798                             $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2799                             if ($until !== false and $until > time()) {
2800                                 $USER->enrol['tempguest'][$course->id] = $until;
2801                                 $access = true;
2802                                 break;
2803                             }
2804                         }
2805                     }
2806                 }
2807             }
2808         }
2810         if (!$access) {
2811             if ($preventredirect) {
2812                 throw new require_login_exception('Not enrolled');
2813             }
2814             if ($setwantsurltome) {
2815                 $SESSION->wantsurl = qualified_me();
2816             }
2817             redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2818         }
2819     }
2821     // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2822     if ($cm && !$cm->uservisible) {
2823         if ($preventredirect) {
2824             throw new require_login_exception('Activity is hidden');
2825         }
2826         if ($course->id != SITEID) {
2827             $url = new moodle_url('/course/view.php', array('id' => $course->id));
2828         } else {
2829             $url = new moodle_url('/');
2830         }
2831         redirect($url, get_string('activityiscurrentlyhidden'));
2832     }
2834     // Set the global $COURSE.
2835     if ($cm) {
2836         $PAGE->set_cm($cm, $course);
2837         $PAGE->set_pagelayout('incourse');
2838     } else if (!empty($courseorid)) {
2839         $PAGE->set_course($course);
2840     }
2842     // Finally access granted, update lastaccess times.
2843     user_accesstime_log($course->id);
2847 /**
2848  * This function just makes sure a user is logged out.
2849  *
2850  * @package    core_access
2851  * @category   access
2852  */
2853 function require_logout() {
2854     global $USER, $DB;
2856     if (!isloggedin()) {
2857         // This should not happen often, no need for hooks or events here.
2858         \core\session\manager::terminate_current();
2859         return;
2860     }
2862     // Execute hooks before action.
2863     $authplugins = array();
2864     $authsequence = get_enabled_auth_plugins();
2865     foreach ($authsequence as $authname) {
2866         $authplugins[$authname] = get_auth_plugin($authname);
2867         $authplugins[$authname]->prelogout_hook();
2868     }
2870     // Store info that gets removed during logout.
2871     $sid = session_id();
2872     $event = \core\event\user_loggedout::create(
2873         array(
2874             'userid' => $USER->id,
2875             'objectid' => $USER->id,
2876             'other' => array('sessionid' => $sid),
2877         )
2878     );
2879     if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2880         $event->add_record_snapshot('sessions', $session);
2881     }
2883     // Clone of $USER object to be used by auth plugins.
2884     $user = fullclone($USER);
2886     // Delete session record and drop $_SESSION content.
2887     \core\session\manager::terminate_current();
2889     // Trigger event AFTER action.
2890     $event->trigger();
2892     // Hook to execute auth plugins redirection after event trigger.
2893     foreach ($authplugins as $authplugin) {
2894         $authplugin->postlogout_hook($user);
2895     }
2898 /**
2899  * Weaker version of require_login()
2900  *
2901  * This is a weaker version of {@link require_login()} which only requires login
2902  * when called from within a course rather than the site page, unless
2903  * the forcelogin option is turned on.
2904  * @see require_login()
2905  *
2906  * @package    core_access
2907  * @category   access
2908  *
2909  * @param mixed $courseorid The course object or id in question
2910  * @param bool $autologinguest Allow autologin guests if that is wanted
2911  * @param object $cm Course activity module if known
2912  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2913  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2914  *             in order to keep redirects working properly. MDL-14495
2915  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2916  * @return void
2917  * @throws coding_exception
2918  */
2919 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2920     global $CFG, $PAGE, $SITE;
2921     $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2922           or (!is_object($courseorid) and $courseorid == SITEID));
2923     if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2924         // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2925         // db queries so this is not really a performance concern, however it is obviously
2926         // better if you use get_fast_modinfo to get the cm before calling this.
2927         if (is_object($courseorid)) {
2928             $course = $courseorid;
2929         } else {
2930             $course = clone($SITE);
2931         }
2932         $modinfo = get_fast_modinfo($course);
2933         $cm = $modinfo->get_cm($cm->id);
2934     }
2935     if (!empty($CFG->forcelogin)) {
2936         // Login required for both SITE and courses.
2937         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2939     } else if ($issite && !empty($cm) and !$cm->uservisible) {
2940         // Always login for hidden activities.
2941         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2943     } else if ($issite) {
2944         // Login for SITE not required.
2945         // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
2946         if (!empty($courseorid)) {
2947             if (is_object($courseorid)) {
2948                 $course = $courseorid;
2949             } else {
2950                 $course = clone $SITE;
2951             }
2952             if ($cm) {
2953                 if ($cm->course != $course->id) {
2954                     throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2955                 }
2956                 $PAGE->set_cm($cm, $course);
2957                 $PAGE->set_pagelayout('incourse');
2958             } else {
2959                 $PAGE->set_course($course);
2960             }
2961         } else {
2962             // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
2963             $PAGE->set_course($PAGE->course);
2964         }
2965         user_accesstime_log(SITEID);
2966         return;
2968     } else {
2969         // Course login always required.
2970         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2971     }
2974 /**
2975  * Require key login. Function terminates with error if key not found or incorrect.
2976  *
2977  * @uses NO_MOODLE_COOKIES
2978  * @uses PARAM_ALPHANUM
2979  * @param string $script unique script identifier
2980  * @param int $instance optional instance id
2981  * @return int Instance ID
2982  */
2983 function require_user_key_login($script, $instance=null) {
2984     global $DB;
2986     if (!NO_MOODLE_COOKIES) {
2987         print_error('sessioncookiesdisable');
2988     }
2990     // Extra safety.
2991     \core\session\manager::write_close();
2993     $keyvalue = required_param('key', PARAM_ALPHANUM);
2995     if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
2996         print_error('invalidkey');
2997     }
2999     if (!empty($key->validuntil) and $key->validuntil < time()) {
3000         print_error('expiredkey');
3001     }
3003     if ($key->iprestriction) {
3004         $remoteaddr = getremoteaddr(null);
3005         if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3006             print_error('ipmismatch');
3007         }
3008     }
3010     if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3011         print_error('invaliduserid');
3012     }
3014     // Emulate normal session.
3015     enrol_check_plugins($user);
3016     \core\session\manager::set_user($user);
3018     // Note we are not using normal login.
3019     if (!defined('USER_KEY_LOGIN')) {
3020         define('USER_KEY_LOGIN', true);
3021     }
3023     // Return instance id - it might be empty.
3024     return $key->instance;
3027 /**
3028  * Creates a new private user access key.
3029  *
3030  * @param string $script unique target identifier
3031  * @param int $userid
3032  * @param int $instance optional instance id
3033  * @param string $iprestriction optional ip restricted access
3034  * @param timestamp $validuntil key valid only until given data
3035  * @return string access key value
3036  */
3037 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3038     global $DB;
3040     $key = new stdClass();
3041     $key->script        = $script;
3042     $key->userid        = $userid;
3043     $key->instance      = $instance;
3044     $key->iprestriction = $iprestriction;
3045     $key->validuntil    = $validuntil;
3046     $key->timecreated   = time();
3048     // Something long and unique.
3049     $key->value         = md5($userid.'_'.time().random_string(40));
3050     while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3051         // Must be unique.
3052         $key->value     = md5($userid.'_'.time().random_string(40));
3053     }
3054     $DB->insert_record('user_private_key', $key);
3055     return $key->value;
3058 /**
3059  * Delete the user's new private user access keys for a particular script.
3060  *
3061  * @param string $script unique target identifier
3062  * @param int $userid
3063  * @return void
3064  */
3065 function delete_user_key($script, $userid) {
3066     global $DB;
3067     $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3070 /**
3071  * Gets a private user access key (and creates one if one doesn't exist).
3072  *
3073  * @param string $script unique target identifier
3074  * @param int $userid
3075  * @param int $instance optional instance id
3076  * @param string $iprestriction optional ip restricted access
3077  * @param timestamp $validuntil key valid only until given data
3078  * @return string access key value
3079  */
3080 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3081     global $DB;
3083     if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3084                                                          'instance' => $instance, 'iprestriction' => $iprestriction,
3085                                                          'validuntil' => $validuntil))) {
3086         return $key->value;
3087     } else {
3088         return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3089     }
3093 /**
3094  * Modify the user table by setting the currently logged in user's last login to now.
3095  *
3096  * @return bool Always returns true
3097  */
3098 function update_user_login_times() {
3099     global $USER, $DB;
3101     if (isguestuser()) {
3102         // Do not update guest access times/ips for performance.
3103         return true;
3104     }
3106     $now = time();
3108     $user = new stdClass();
3109     $user->id = $USER->id;
3111     // Make sure all users that logged in have some firstaccess.
3112     if ($USER->firstaccess == 0) {
3113         $USER->firstaccess = $user->firstaccess = $now;
3114     }
3116     // Store the previous current as lastlogin.
3117     $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3119     $USER->currentlogin = $user->currentlogin = $now;
3121     // Function user_accesstime_log() may not update immediately, better do it here.
3122     $USER->lastaccess = $user->lastaccess = $now;
3123     $USER->lastip = $user->lastip = getremoteaddr();
3125     // Note: do not call user_update_user() here because this is part of the login process,
3126     //       the login event means that these fields were updated.
3127     $DB->update_record('user', $user);
3128     return true;
3131 /**
3132  * Determines if a user has completed setting up their account.
3133  *
3134  * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3135  * @return bool
3136  */
3137 function user_not_fully_set_up($user) {
3138     if (isguestuser($user)) {
3139         return false;
3140     }
3141     return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3144 /**
3145  * Check whether the user has exceeded the bounce threshold
3146  *
3147  * @param stdClass $user A {@link $USER} object
3148  * @return bool true => User has exceeded bounce threshold
3149  */
3150 function over_bounce_threshold($user) {
3151     global $CFG, $DB;
3153     if (empty($CFG->handlebounces)) {
3154         return false;
3155     }
3157     if (empty($user->id)) {
3158         // No real (DB) user, nothing to do here.
3159         return false;
3160     }
3162     // Set sensible defaults.
3163     if (empty($CFG->minbounces)) {
3164         $CFG->minbounces = 10;
3165     }
3166     if (empty($CFG->bounceratio)) {
3167         $CFG->bounceratio = .20;
3168     }
3169     $bouncecount = 0;
3170     $sendcount = 0;
3171     if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3172         $bouncecount = $bounce->value;
3173     }
3174     if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3175         $sendcount = $send->value;
3176     }
3177     return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3180 /**
3181  * Used to increment or reset email sent count
3182  *
3183  * @param stdClass $user object containing an id
3184  * @param bool $reset will reset the count to 0
3185  * @return void
3186  */
3187 function set_send_count($user, $reset=false) {
3188     global $DB;
3190     if (empty($user->id)) {
3191         // No real (DB) user, nothing to do here.
3192         return;
3193     }
3195     if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3196         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3197         $DB->update_record('user_preferences', $pref);
3198     } else if (!empty($reset)) {
3199         // If it's not there and we're resetting, don't bother. Make a new one.
3200         $pref = new stdClass();
3201         $pref->name   = 'email_send_count';
3202         $pref->value  = 1;
3203         $pref->userid = $user->id;
3204         $DB->insert_record('user_preferences', $pref, false);
3205     }
3208 /**
3209  * Increment or reset user's email bounce count
3210  *
3211  * @param stdClass $user object containing an id
3212  * @param bool $reset will reset the count to 0
3213  */
3214 function set_bounce_count($user, $reset=false) {
3215     global $DB;
3217     if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3218         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3219         $DB->update_record('user_preferences', $pref);
3220     } else if (!empty($reset)) {
3221         // If it's not there and we're resetting, don't bother. Make a new one.
3222         $pref = new stdClass();
3223         $pref->name   = 'email_bounce_count';
3224         $pref->value  = 1;
3225         $pref->userid = $user->id;
3226         $DB->insert_record('user_preferences', $pref, false);
3227     }
3230 /**
3231  * Determines if the logged in user is currently moving an activity
3232  *
3233  * @param int $courseid The id of the course being tested
3234  * @return bool
3235  */
3236 function ismoving($courseid) {
3237     global $USER;
3239     if (!empty($USER->activitycopy)) {
3240         return ($USER->activitycopycourse == $courseid);
3241     }
3242     return false;
3245 /**
3246  * Returns a persons full name
3247  *
3248  * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3249  * The result may depend on system settings or language.  'override' will force both names to be used even if system settings
3250  * specify one.
3251  *
3252  * @param stdClass $user A {@link $USER} object to get full name of.
3253  * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3254  * @return string
3255  */
3256 function fullname($user, $override=false) {
3257     global $CFG, $SESSION;
3259     if (!isset($user->firstname) and !isset($user->lastname)) {
3260         return '';
3261     }
3263     // Get all of the name fields.
3264     $allnames = get_all_user_name_fields();
3265     if ($CFG->debugdeveloper) {
3266         foreach ($allnames as $allname) {
3267             if (!property_exists($user, $allname)) {
3268                 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3269                 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3270                 // Message has been sent, no point in sending the message multiple times.
3271                 break;
3272             }
3273         }
3274     }
3276     if (!$override) {
3277         if (!empty($CFG->forcefirstname)) {
3278             $user->firstname = $CFG->forcefirstname;
3279         }
3280         if (!empty($CFG->forcelastname)) {
3281             $user->lastname = $CFG->forcelastname;
3282         }
3283     }
3285     if (!empty($SESSION->fullnamedisplay)) {
3286         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3287     }
3289     $template = null;
3290     // If the fullnamedisplay setting is available, set the template to that.
3291     if (isset($CFG->fullnamedisplay)) {
3292         $template = $CFG->fullnamedisplay;
3293     }
3294     // If the template is empty, or set to language, return the language string.
3295     if ((empty($template) || $template == 'language') && !$override) {
3296         return get_string('fullnamedisplay', null, $user);
3297     }
3299     // Check to see if we are displaying according to the alternative full name format.
3300     if ($override) {
3301         if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3302             // Default to show just the user names according to the fullnamedisplay string.
3303             return get_string('fullnamedisplay', null, $user);
3304         } else {
3305             // If the override is true, then change the template to use the complete name.
3306             $template = $CFG->alternativefullnameformat;
3307         }
3308     }
3310     $requirednames = array();
3311     // With each name, see if it is in the display name template, and add it to the required names array if it is.
3312     foreach ($allnames as $allname) {
3313         if (strpos($template, $allname) !== false) {
3314             $requirednames[] = $allname;
3315         }
3316     }
3318     $displayname = $template;
3319     // Switch in the actual data into the template.
3320     foreach ($requirednames as $altname) {
3321         if (isset($user->$altname)) {
3322             // Using empty() on the below if statement causes breakages.
3323             if ((string)$user->$altname == '') {
3324                 $displayname = str_replace($altname, 'EMPTY', $displayname);
3325             } else {
3326                 $displayname = str_replace($altname, $user->$altname, $displayname);
3327             }
3328         } else {
3329             $displayname = str_replace($altname, 'EMPTY', $displayname);
3330         }
3331     }
3332     // Tidy up any misc. characters (Not perfect, but gets most characters).
3333     // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3334     // katakana and parenthesis.
3335     $patterns = array();
3336     // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3337     // filled in by a user.
3338     // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3339     $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3340     // This regular expression is to remove any double spaces in the display name.
3341     $patterns[] = '/\s{2,}/u';
3342     foreach ($patterns as $pattern) {
3343         $displayname = preg_replace($pattern, ' ', $displayname);
3344     }
3346     // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3347     $displayname = trim($displayname);
3348     if (empty($displayname)) {
3349         // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3350         // people in general feel is a good setting to fall back on.
3351         $displayname = $user->firstname;
3352     }
3353     return $displayname;
3356 /**
3357  * A centralised location for the all name fields. Returns an array / sql string snippet.
3358  *
3359  * @param bool $returnsql True for an sql select field snippet.
3360  * @param string $tableprefix table query prefix to use in front of each field.
3361  * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3362  * @param string $fieldprefix sql field prefix e.g. id AS userid.
3363  * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3364  * @return array|string All name fields.
3365  */
3366 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3367     // This array is provided in this order because when called by fullname() (above) if firstname is before
3368     // firstnamephonetic str_replace() will change the wrong placeholder.
3369     $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3370                             'lastnamephonetic' => 'lastnamephonetic',
3371                             'middlename' => 'middlename',
3372                             'alternatename' => 'alternatename',
3373                             'firstname' => 'firstname',
3374                             'lastname' => 'lastname');
3376     // Let's add a prefix to the array of user name fields if provided.
3377     if ($prefix) {
3378         foreach ($alternatenames as $key => $altname) {
3379             $alternatenames[$key] = $prefix . $altname;
3380         }
3381     }
3383     // If we want the end result to have firstname and lastname at the front / top of the result.
3384     if ($order) {
3385         // Move the last two elements (firstname, lastname) off the array and put them at the top.
3386         for ($i = 0; $i < 2; $i++) {
3387             // Get the last element.
3388             $lastelement = end($alternatenames);
3389             // Remove it from the array.
3390             unset($alternatenames[$lastelement]);
3391             // Put the element back on the top of the array.
3392             $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3393         }
3394     }
3396     // Create an sql field snippet if requested.
3397     if ($returnsql) {
3398         if ($tableprefix) {
3399             if ($fieldprefix) {
3400                 foreach ($alternatenames as $key => $altname) {
3401                     $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3402                 }
3403             } else {
3404                 foreach ($alternatenames as $key => $altname) {
3405                     $alternatenames[$key] = $tableprefix . '.' . $altname;
3406                 }
3407             }
3408         }
3409         $alternatenames = implode(',', $alternatenames);
3410     }
3411     return $alternatenames;
3414 /**
3415  * Reduces lines of duplicated code for getting user name fields.
3416  *
3417  * See also {@link user_picture::unalias()}
3418  *
3419  * @param object $addtoobject Object to add user name fields to.
3420  * @param object $secondobject Object that contains user name field information.
3421  * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3422  * @param array $additionalfields Additional fields to be matched with data in the second object.
3423  * The key can be set to the user table field name.
3424  * @return object User name fields.
3425  */
3426 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3427     $fields = get_all_user_name_fields(false, null, $prefix);
3428     if ($additionalfields) {
3429         // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3430         // the key is a number and then sets the key to the array value.
3431         foreach ($additionalfields as $key => $value) {
3432             if (is_numeric($key)) {
3433                 $additionalfields[$value] = $prefix . $value;
3434                 unset($additionalfields[$key]);
3435             } else {
3436                 $additionalfields[$key] = $prefix . $value;
3437             }
3438         }
3439         $fields = array_merge($fields, $additionalfields);
3440     }
3441     foreach ($fields as $key => $field) {
3442         // Important that we have all of the user name fields present in the object that we are sending back.
3443         $addtoobject->$key = '';
3444         if (isset($secondobject->$field)) {
3445             $addtoobject->$key = $secondobject->$field;
3446         }
3447     }
3448     return $addtoobject;
3451 /**
3452  * Returns an array of values in order of occurance in a provided string.
3453  * The key in the result is the character postion in the string.
3454  *
3455  * @param array $values Values to be found in the string format
3456  * @param string $stringformat The string which may contain values being searched for.
3457  * @return array An array of values in order according to placement in the string format.
3458  */
3459 function order_in_string($values, $stringformat) {
3460     $valuearray = array();
3461     foreach ($values as $value) {
3462         $pattern = "/$value\b/";
3463         // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3464         if (preg_match($pattern, $stringformat)) {
3465             $replacement = "thing";
3466             // Replace the value with something more unique to ensure we get the right position when using strpos().
3467             $newformat = preg_replace($pattern, $replacement, $stringformat);
3468             $position = strpos($newformat, $replacement);
3469             $valuearray[$position] = $value;
3470         }
3471     }
3472     ksort($valuearray);
3473     return $valuearray;
3476 /**
3477  * Checks if current user is shown any extra fields when listing users.
3478  *
3479  * @param object $context Context
3480  * @param array $already Array of fields that we're going to show anyway
3481  *   so don't bother listing them
3482  * @return array Array of field names from user table, not including anything
3483  *   listed in $already
3484  */
3485 function get_extra_user_fields($context, $already = array()) {
3486     global $CFG;
3488     // Only users with permission get the extra fields.
3489     if (!has_capability('moodle/site:viewuseridentity', $context)) {
3490         return array();
3491     }
3493     // Split showuseridentity on comma.
3494     if (empty($CFG->showuseridentity)) {
3495         // Explode gives wrong result with empty string.
3496         $extra = array();
3497     } else {
3498         $extra =  explode(',', $CFG->showuseridentity);
3499     }
3500     $renumber = false;
3501     foreach ($extra as $key => $field) {
3502         if (in_array($field, $already)) {
3503             unset($extra[$key]);
3504             $renumber = true;
3505         }
3506     }
3507     if ($renumber) {
3508         // For consistency, if entries are removed from array, renumber it
3509         // so they are numbered as you would expect.
3510         $extra = array_merge($extra);
3511     }
3512     return $extra;
3515 /**
3516  * If the current user is to be shown extra user fields when listing or
3517  * selecting users, returns a string suitable for including in an SQL select
3518  * clause to retrieve those fields.
3519  *
3520  * @param context $context Context
3521  * @param string $alias Alias of user table, e.g. 'u' (default none)
3522  * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3523  * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3524  * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3525  */
3526 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3527     $fields = get_extra_user_fields($context, $already);
3528     $result = '';
3529     // Add punctuation for alias.
3530     if ($alias !== '') {
3531         $alias .= '.';
3532     }
3533     foreach ($fields as $field) {
3534         $result .= ', ' . $alias . $field;
3535         if ($prefix) {
3536             $result .= ' AS ' . $prefix . $field;
3537         }
3538     }
3539     return $result;
3542 /**
3543  * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3544  * @param string $field Field name, e.g. 'phone1'
3545  * @return string Text description taken from language file, e.g. 'Phone number'
3546  */
3547 function get_user_field_name($field) {
3548     // Some fields have language strings which are not the same as field name.
3549     switch ($field) {
3550         case 'url' : {
3551             return get_string('webpage');
3552         }
3553         case 'icq' : {
3554             return get_string('icqnumber');
3555         }
3556         case 'skype' : {
3557             return get_string('skypeid');
3558         }
3559         case 'aim' : {
3560             return get_string('aimid');
3561         }
3562         case 'yahoo' : {
3563             return get_string('yahooid');
3564         }
3565         case 'msn' : {
3566             return get_string('msnid');
3567         }
3568     }
3569     // Otherwise just use the same lang string.
3570     return get_string($field);
3573 /**
3574  * Returns whether a given authentication plugin exists.
3575  *
3576  * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3577  * @return boolean Whether the plugin is available.
3578  */
3579 function exists_auth_plugin($auth) {
3580     global $CFG;
3582     if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3583         return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3584     }
3585     return false;
3588 /**
3589  * Checks if a given plugin is in the list of enabled authentication plugins.
3590  *
3591  * @param string $auth Authentication plugin.
3592  * @return boolean Whether the plugin is enabled.
3593  */
3594 function is_enabled_auth($auth) {
3595     if (empty($auth)) {
3596         return false;
3597     }
3599     $enabled = get_enabled_auth_plugins();
3601     return in_array($auth, $enabled);
3604 /**
3605  * Returns an authentication plugin instance.
3606  *
3607  * @param string $auth name of authentication plugin
3608  * @return auth_plugin_base An instance of the required authentication plugin.
3609  */
3610 function get_auth_plugin($auth) {
3611     global $CFG;
3613     // Check the plugin exists first.
3614     if (! exists_auth_plugin($auth)) {
3615         print_error('authpluginnotfound', 'debug', '', $auth);
3616     }
3618     // Return auth plugin instance.
3619     require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3620     $class = "auth_plugin_$auth";
3621     return new $class;
3624 /**
3625  * Returns array of active auth plugins.
3626  *
3627  * @param bool $fix fix $CFG->auth if needed
3628  * @return array
3629  */
3630 function get_enabled_auth_plugins($fix=false) {
3631     global $CFG;
3633     $default = array('manual', 'nologin');
3635     if (empty($CFG->auth)) {
3636         $auths = array();
3637     } else {
3638         $auths = explode(',', $CFG->auth);
3639     }
3641     if ($fix) {
3642         $auths = array_unique($auths);
3643         foreach ($auths as $k => $authname) {
3644             if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3645                 unset($auths[$k]);
3646             }
3647         }
3648         $newconfig = implode(',', $auths);
3649         if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3650             set_config('auth', $newconfig);
3651         }
3652     }