9e57b24751ae8f2bb3cd283a9fb8c789bd42ccae
[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 /**
452  * Return this from modname_get_types callback to use default display in activity chooser.
453  * Deprecated, will be removed in 3.5, TODO MDL-53697.
454  * @deprecated since Moodle 3.1
455  */
456 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
458 /**
459  * Security token used for allowing access
460  * from external application such as web services.
461  * Scripts do not use any session, performance is relatively
462  * low because we need to load access info in each request.
463  * Scripts are executed in parallel.
464  */
465 define('EXTERNAL_TOKEN_PERMANENT', 0);
467 /**
468  * Security token used for allowing access
469  * of embedded applications, the code is executed in the
470  * active user session. Token is invalidated after user logs out.
471  * Scripts are executed serially - normal session locking is used.
472  */
473 define('EXTERNAL_TOKEN_EMBEDDED', 1);
475 /**
476  * The home page should be the site home
477  */
478 define('HOMEPAGE_SITE', 0);
479 /**
480  * The home page should be the users my page
481  */
482 define('HOMEPAGE_MY', 1);
483 /**
484  * The home page can be chosen by the user
485  */
486 define('HOMEPAGE_USER', 2);
488 /**
489  * Hub directory url (should be moodle.org)
490  */
491 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
494 /**
495  * Moodle.org url (should be moodle.org)
496  */
497 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
499 /**
500  * Moodle mobile app service name
501  */
502 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
504 /**
505  * Indicates the user has the capabilities required to ignore activity and course file size restrictions
506  */
507 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
509 /**
510  * Course display settings: display all sections on one page.
511  */
512 define('COURSE_DISPLAY_SINGLEPAGE', 0);
513 /**
514  * Course display settings: split pages into a page per section.
515  */
516 define('COURSE_DISPLAY_MULTIPAGE', 1);
518 /**
519  * Authentication constant: String used in password field when password is not stored.
520  */
521 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
523 // PARAMETER HANDLING.
525 /**
526  * Returns a particular value for the named variable, taken from
527  * POST or GET.  If the parameter doesn't exist then an error is
528  * thrown because we require this variable.
529  *
530  * This function should be used to initialise all required values
531  * in a script that are based on parameters.  Usually it will be
532  * used like this:
533  *    $id = required_param('id', PARAM_INT);
534  *
535  * Please note the $type parameter is now required and the value can not be array.
536  *
537  * @param string $parname the name of the page parameter we want
538  * @param string $type expected type of parameter
539  * @return mixed
540  * @throws coding_exception
541  */
542 function required_param($parname, $type) {
543     if (func_num_args() != 2 or empty($parname) or empty($type)) {
544         throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
545     }
546     // POST has precedence.
547     if (isset($_POST[$parname])) {
548         $param = $_POST[$parname];
549     } else if (isset($_GET[$parname])) {
550         $param = $_GET[$parname];
551     } else {
552         print_error('missingparam', '', '', $parname);
553     }
555     if (is_array($param)) {
556         debugging('Invalid array parameter detected in required_param(): '.$parname);
557         // TODO: switch to fatal error in Moodle 2.3.
558         return required_param_array($parname, $type);
559     }
561     return clean_param($param, $type);
564 /**
565  * Returns a particular array value for the named variable, taken from
566  * POST or GET.  If the parameter doesn't exist then an error is
567  * thrown because we require this variable.
568  *
569  * This function should be used to initialise all required values
570  * in a script that are based on parameters.  Usually it will be
571  * used like this:
572  *    $ids = required_param_array('ids', PARAM_INT);
573  *
574  *  Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
575  *
576  * @param string $parname the name of the page parameter we want
577  * @param string $type expected type of parameter
578  * @return array
579  * @throws coding_exception
580  */
581 function required_param_array($parname, $type) {
582     if (func_num_args() != 2 or empty($parname) or empty($type)) {
583         throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
584     }
585     // POST has precedence.
586     if (isset($_POST[$parname])) {
587         $param = $_POST[$parname];
588     } else if (isset($_GET[$parname])) {
589         $param = $_GET[$parname];
590     } else {
591         print_error('missingparam', '', '', $parname);
592     }
593     if (!is_array($param)) {
594         print_error('missingparam', '', '', $parname);
595     }
597     $result = array();
598     foreach ($param as $key => $value) {
599         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
600             debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
601             continue;
602         }
603         $result[$key] = clean_param($value, $type);
604     }
606     return $result;
609 /**
610  * Returns a particular value for the named variable, taken from
611  * POST or GET, otherwise returning a given default.
612  *
613  * This function should be used to initialise all optional values
614  * in a script that are based on parameters.  Usually it will be
615  * used like this:
616  *    $name = optional_param('name', 'Fred', PARAM_TEXT);
617  *
618  * Please note the $type parameter is now required and the value can not be array.
619  *
620  * @param string $parname the name of the page parameter we want
621  * @param mixed  $default the default value to return if nothing is found
622  * @param string $type expected type of parameter
623  * @return mixed
624  * @throws coding_exception
625  */
626 function optional_param($parname, $default, $type) {
627     if (func_num_args() != 3 or empty($parname) or empty($type)) {
628         throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
629     }
631     // POST has precedence.
632     if (isset($_POST[$parname])) {
633         $param = $_POST[$parname];
634     } else if (isset($_GET[$parname])) {
635         $param = $_GET[$parname];
636     } else {
637         return $default;
638     }
640     if (is_array($param)) {
641         debugging('Invalid array parameter detected in required_param(): '.$parname);
642         // TODO: switch to $default in Moodle 2.3.
643         return optional_param_array($parname, $default, $type);
644     }
646     return clean_param($param, $type);
649 /**
650  * Returns a particular array value for the named variable, taken from
651  * POST or GET, otherwise returning a given default.
652  *
653  * This function should be used to initialise all optional values
654  * in a script that are based on parameters.  Usually it will be
655  * used like this:
656  *    $ids = optional_param('id', array(), PARAM_INT);
657  *
658  * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
659  *
660  * @param string $parname the name of the page parameter we want
661  * @param mixed $default the default value to return if nothing is found
662  * @param string $type expected type of parameter
663  * @return array
664  * @throws coding_exception
665  */
666 function optional_param_array($parname, $default, $type) {
667     if (func_num_args() != 3 or empty($parname) or empty($type)) {
668         throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
669     }
671     // POST has precedence.
672     if (isset($_POST[$parname])) {
673         $param = $_POST[$parname];
674     } else if (isset($_GET[$parname])) {
675         $param = $_GET[$parname];
676     } else {
677         return $default;
678     }
679     if (!is_array($param)) {
680         debugging('optional_param_array() expects array parameters only: '.$parname);
681         return $default;
682     }
684     $result = array();
685     foreach ($param as $key => $value) {
686         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
687             debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
688             continue;
689         }
690         $result[$key] = clean_param($value, $type);
691     }
693     return $result;
696 /**
697  * Strict validation of parameter values, the values are only converted
698  * to requested PHP type. Internally it is using clean_param, the values
699  * before and after cleaning must be equal - otherwise
700  * an invalid_parameter_exception is thrown.
701  * Objects and classes are not accepted.
702  *
703  * @param mixed $param
704  * @param string $type PARAM_ constant
705  * @param bool $allownull are nulls valid value?
706  * @param string $debuginfo optional debug information
707  * @return mixed the $param value converted to PHP type
708  * @throws invalid_parameter_exception if $param is not of given type
709  */
710 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
711     if (is_null($param)) {
712         if ($allownull == NULL_ALLOWED) {
713             return null;
714         } else {
715             throw new invalid_parameter_exception($debuginfo);
716         }
717     }
718     if (is_array($param) or is_object($param)) {
719         throw new invalid_parameter_exception($debuginfo);
720     }
722     $cleaned = clean_param($param, $type);
724     if ($type == PARAM_FLOAT) {
725         // Do not detect precision loss here.
726         if (is_float($param) or is_int($param)) {
727             // These always fit.
728         } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
729             throw new invalid_parameter_exception($debuginfo);
730         }
731     } else if ((string)$param !== (string)$cleaned) {
732         // Conversion to string is usually lossless.
733         throw new invalid_parameter_exception($debuginfo);
734     }
736     return $cleaned;
739 /**
740  * Makes sure array contains only the allowed types, this function does not validate array key names!
741  *
742  * <code>
743  * $options = clean_param($options, PARAM_INT);
744  * </code>
745  *
746  * @param array $param the variable array we are cleaning
747  * @param string $type expected format of param after cleaning.
748  * @param bool $recursive clean recursive arrays
749  * @return array
750  * @throws coding_exception
751  */
752 function clean_param_array(array $param = null, $type, $recursive = false) {
753     // Convert null to empty array.
754     $param = (array)$param;
755     foreach ($param as $key => $value) {
756         if (is_array($value)) {
757             if ($recursive) {
758                 $param[$key] = clean_param_array($value, $type, true);
759             } else {
760                 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
761             }
762         } else {
763             $param[$key] = clean_param($value, $type);
764         }
765     }
766     return $param;
769 /**
770  * Used by {@link optional_param()} and {@link required_param()} to
771  * clean the variables and/or cast to specific types, based on
772  * an options field.
773  * <code>
774  * $course->format = clean_param($course->format, PARAM_ALPHA);
775  * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
776  * </code>
777  *
778  * @param mixed $param the variable we are cleaning
779  * @param string $type expected format of param after cleaning.
780  * @return mixed
781  * @throws coding_exception
782  */
783 function clean_param($param, $type) {
784     global $CFG;
786     if (is_array($param)) {
787         throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
788     } else if (is_object($param)) {
789         if (method_exists($param, '__toString')) {
790             $param = $param->__toString();
791         } else {
792             throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
793         }
794     }
796     switch ($type) {
797         case PARAM_RAW:
798             // No cleaning at all.
799             $param = fix_utf8($param);
800             return $param;
802         case PARAM_RAW_TRIMMED:
803             // No cleaning, but strip leading and trailing whitespace.
804             $param = fix_utf8($param);
805             return trim($param);
807         case PARAM_CLEAN:
808             // General HTML cleaning, try to use more specific type if possible this is deprecated!
809             // Please use more specific type instead.
810             if (is_numeric($param)) {
811                 return $param;
812             }
813             $param = fix_utf8($param);
814             // Sweep for scripts, etc.
815             return clean_text($param);
817         case PARAM_CLEANHTML:
818             // Clean html fragment.
819             $param = fix_utf8($param);
820             // Sweep for scripts, etc.
821             $param = clean_text($param, FORMAT_HTML);
822             return trim($param);
824         case PARAM_INT:
825             // Convert to integer.
826             return (int)$param;
828         case PARAM_FLOAT:
829             // Convert to float.
830             return (float)$param;
832         case PARAM_ALPHA:
833             // Remove everything not `a-z`.
834             return preg_replace('/[^a-zA-Z]/i', '', $param);
836         case PARAM_ALPHAEXT:
837             // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
838             return preg_replace('/[^a-zA-Z_-]/i', '', $param);
840         case PARAM_ALPHANUM:
841             // Remove everything not `a-zA-Z0-9`.
842             return preg_replace('/[^A-Za-z0-9]/i', '', $param);
844         case PARAM_ALPHANUMEXT:
845             // Remove everything not `a-zA-Z0-9_-`.
846             return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
848         case PARAM_SEQUENCE:
849             // Remove everything not `0-9,`.
850             return preg_replace('/[^0-9,]/i', '', $param);
852         case PARAM_BOOL:
853             // Convert to 1 or 0.
854             $tempstr = strtolower($param);
855             if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
856                 $param = 1;
857             } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
858                 $param = 0;
859             } else {
860                 $param = empty($param) ? 0 : 1;
861             }
862             return $param;
864         case PARAM_NOTAGS:
865             // Strip all tags.
866             $param = fix_utf8($param);
867             return strip_tags($param);
869         case PARAM_TEXT:
870             // Leave only tags needed for multilang.
871             $param = fix_utf8($param);
872             // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
873             // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
874             do {
875                 if (strpos($param, '</lang>') !== false) {
876                     // Old and future mutilang syntax.
877                     $param = strip_tags($param, '<lang>');
878                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
879                         break;
880                     }
881                     $open = false;
882                     foreach ($matches[0] as $match) {
883                         if ($match === '</lang>') {
884                             if ($open) {
885                                 $open = false;
886                                 continue;
887                             } else {
888                                 break 2;
889                             }
890                         }
891                         if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
892                             break 2;
893                         } else {
894                             $open = true;
895                         }
896                     }
897                     if ($open) {
898                         break;
899                     }
900                     return $param;
902                 } else if (strpos($param, '</span>') !== false) {
903                     // Current problematic multilang syntax.
904                     $param = strip_tags($param, '<span>');
905                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
906                         break;
907                     }
908                     $open = false;
909                     foreach ($matches[0] as $match) {
910                         if ($match === '</span>') {
911                             if ($open) {
912                                 $open = false;
913                                 continue;
914                             } else {
915                                 break 2;
916                             }
917                         }
918                         if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
919                             break 2;
920                         } else {
921                             $open = true;
922                         }
923                     }
924                     if ($open) {
925                         break;
926                     }
927                     return $param;
928                 }
929             } while (false);
930             // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
931             return strip_tags($param);
933         case PARAM_COMPONENT:
934             // We do not want any guessing here, either the name is correct or not
935             // please note only normalised component names are accepted.
936             if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
937                 return '';
938             }
939             if (strpos($param, '__') !== false) {
940                 return '';
941             }
942             if (strpos($param, 'mod_') === 0) {
943                 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
944                 if (substr_count($param, '_') != 1) {
945                     return '';
946                 }
947             }
948             return $param;
950         case PARAM_PLUGIN:
951         case PARAM_AREA:
952             // We do not want any guessing here, either the name is correct or not.
953             if (!is_valid_plugin_name($param)) {
954                 return '';
955             }
956             return $param;
958         case PARAM_SAFEDIR:
959             // Remove everything not a-zA-Z0-9_- .
960             return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
962         case PARAM_SAFEPATH:
963             // Remove everything not a-zA-Z0-9/_- .
964             return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
966         case PARAM_FILE:
967             // Strip all suspicious characters from filename.
968             $param = fix_utf8($param);
969             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
970             if ($param === '.' || $param === '..') {
971                 $param = '';
972             }
973             return $param;
975         case PARAM_PATH:
976             // Strip all suspicious characters from file path.
977             $param = fix_utf8($param);
978             $param = str_replace('\\', '/', $param);
980             // Explode the path and clean each element using the PARAM_FILE rules.
981             $breadcrumb = explode('/', $param);
982             foreach ($breadcrumb as $key => $crumb) {
983                 if ($crumb === '.' && $key === 0) {
984                     // Special condition to allow for relative current path such as ./currentdirfile.txt.
985                 } else {
986                     $crumb = clean_param($crumb, PARAM_FILE);
987                 }
988                 $breadcrumb[$key] = $crumb;
989             }
990             $param = implode('/', $breadcrumb);
992             // Remove multiple current path (./././) and multiple slashes (///).
993             $param = preg_replace('~//+~', '/', $param);
994             $param = preg_replace('~/(\./)+~', '/', $param);
995             return $param;
997         case PARAM_HOST:
998             // Allow FQDN or IPv4 dotted quad.
999             $param = preg_replace('/[^\.\d\w-]/', '', $param );
1000             // Match ipv4 dotted quad.
1001             if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1002                 // Confirm values are ok.
1003                 if ( $match[0] > 255
1004                      || $match[1] > 255
1005                      || $match[3] > 255
1006                      || $match[4] > 255 ) {
1007                     // Hmmm, what kind of dotted quad is this?
1008                     $param = '';
1009                 }
1010             } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1011                        && !preg_match('/^[\.-]/',  $param) // No leading dots/hyphens.
1012                        && !preg_match('/[\.-]$/',  $param) // No trailing dots/hyphens.
1013                        ) {
1014                 // All is ok - $param is respected.
1015             } else {
1016                 // All is not ok...
1017                 $param='';
1018             }
1019             return $param;
1021         case PARAM_URL:          // Allow safe ftp, http, mailto urls.
1022             $param = fix_utf8($param);
1023             include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1024             if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1025                 // All is ok, param is respected.
1026             } else {
1027                 // Not really ok.
1028                 $param ='';
1029             }
1030             return $param;
1032         case PARAM_LOCALURL:
1033             // Allow http absolute, root relative and relative URLs within wwwroot.
1034             $param = clean_param($param, PARAM_URL);
1035             if (!empty($param)) {
1037                 // Simulate the HTTPS version of the site.
1038                 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1040                 if ($param === $CFG->wwwroot) {
1041                     // Exact match;
1042                 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1043                     // Exact match;
1044                 } else if (preg_match(':^/:', $param)) {
1045                     // Root-relative, ok!
1046                 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1047                     // Absolute, and matches our wwwroot.
1048                 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1049                     // Absolute, and matches our httpswwwroot.
1050                 } else {
1051                     // Relative - let's make sure there are no tricks.
1052                     if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1053                         // Looks ok.
1054                     } else {
1055                         $param = '';
1056                     }
1057                 }
1058             }
1059             return $param;
1061         case PARAM_PEM:
1062             $param = trim($param);
1063             // PEM formatted strings may contain letters/numbers and the symbols:
1064             //   forward slash: /
1065             //   plus sign:     +
1066             //   equal sign:    =
1067             //   , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1068             if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1069                 list($wholething, $body) = $matches;
1070                 unset($wholething, $matches);
1071                 $b64 = clean_param($body, PARAM_BASE64);
1072                 if (!empty($b64)) {
1073                     return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1074                 } else {
1075                     return '';
1076                 }
1077             }
1078             return '';
1080         case PARAM_BASE64:
1081             if (!empty($param)) {
1082                 // PEM formatted strings may contain letters/numbers and the symbols
1083                 //   forward slash: /
1084                 //   plus sign:     +
1085                 //   equal sign:    =.
1086                 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1087                     return '';
1088                 }
1089                 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1090                 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1091                 // than (or equal to) 64 characters long.
1092                 for ($i=0, $j=count($lines); $i < $j; $i++) {
1093                     if ($i + 1 == $j) {
1094                         if (64 < strlen($lines[$i])) {
1095                             return '';
1096                         }
1097                         continue;
1098                     }
1100                     if (64 != strlen($lines[$i])) {
1101                         return '';
1102                     }
1103                 }
1104                 return implode("\n", $lines);
1105             } else {
1106                 return '';
1107             }
1109         case PARAM_TAG:
1110             $param = fix_utf8($param);
1111             // Please note it is not safe to use the tag name directly anywhere,
1112             // it must be processed with s(), urlencode() before embedding anywhere.
1113             // Remove some nasties.
1114             $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1115             // Convert many whitespace chars into one.
1116             $param = preg_replace('/\s+/u', ' ', $param);
1117             $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1118             return $param;
1120         case PARAM_TAGLIST:
1121             $param = fix_utf8($param);
1122             $tags = explode(',', $param);
1123             $result = array();
1124             foreach ($tags as $tag) {
1125                 $res = clean_param($tag, PARAM_TAG);
1126                 if ($res !== '') {
1127                     $result[] = $res;
1128                 }
1129             }
1130             if ($result) {
1131                 return implode(',', $result);
1132             } else {
1133                 return '';
1134             }
1136         case PARAM_CAPABILITY:
1137             if (get_capability_info($param)) {
1138                 return $param;
1139             } else {
1140                 return '';
1141             }
1143         case PARAM_PERMISSION:
1144             $param = (int)$param;
1145             if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1146                 return $param;
1147             } else {
1148                 return CAP_INHERIT;
1149             }
1151         case PARAM_AUTH:
1152             $param = clean_param($param, PARAM_PLUGIN);
1153             if (empty($param)) {
1154                 return '';
1155             } else if (exists_auth_plugin($param)) {
1156                 return $param;
1157             } else {
1158                 return '';
1159             }
1161         case PARAM_LANG:
1162             $param = clean_param($param, PARAM_SAFEDIR);
1163             if (get_string_manager()->translation_exists($param)) {
1164                 return $param;
1165             } else {
1166                 // Specified language is not installed or param malformed.
1167                 return '';
1168             }
1170         case PARAM_THEME:
1171             $param = clean_param($param, PARAM_PLUGIN);
1172             if (empty($param)) {
1173                 return '';
1174             } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1175                 return $param;
1176             } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1177                 return $param;
1178             } else {
1179                 // Specified theme is not installed.
1180                 return '';
1181             }
1183         case PARAM_USERNAME:
1184             $param = fix_utf8($param);
1185             $param = trim($param);
1186             // Convert uppercase to lowercase MDL-16919.
1187             $param = core_text::strtolower($param);
1188             if (empty($CFG->extendedusernamechars)) {
1189                 $param = str_replace(" " , "", $param);
1190                 // Regular expression, eliminate all chars EXCEPT:
1191                 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1192                 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1193             }
1194             return $param;
1196         case PARAM_EMAIL:
1197             $param = fix_utf8($param);
1198             if (validate_email($param)) {
1199                 return $param;
1200             } else {
1201                 return '';
1202             }
1204         case PARAM_STRINGID:
1205             if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1206                 return $param;
1207             } else {
1208                 return '';
1209             }
1211         case PARAM_TIMEZONE:
1212             // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1213             $param = fix_utf8($param);
1214             $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1215             if (preg_match($timezonepattern, $param)) {
1216                 return $param;
1217             } else {
1218                 return '';
1219             }
1221         default:
1222             // Doh! throw error, switched parameters in optional_param or another serious problem.
1223             print_error("unknownparamtype", '', '', $type);
1224     }
1227 /**
1228  * Makes sure the data is using valid utf8, invalid characters are discarded.
1229  *
1230  * Note: this function is not intended for full objects with methods and private properties.
1231  *
1232  * @param mixed $value
1233  * @return mixed with proper utf-8 encoding
1234  */
1235 function fix_utf8($value) {
1236     if (is_null($value) or $value === '') {
1237         return $value;
1239     } else if (is_string($value)) {
1240         if ((string)(int)$value === $value) {
1241             // Shortcut.
1242             return $value;
1243         }
1244         // No null bytes expected in our data, so let's remove it.
1245         $value = str_replace("\0", '', $value);
1247         // Note: this duplicates min_fix_utf8() intentionally.
1248         static $buggyiconv = null;
1249         if ($buggyiconv === null) {
1250             $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1251         }
1253         if ($buggyiconv) {
1254             if (function_exists('mb_convert_encoding')) {
1255                 $subst = mb_substitute_character();
1256                 mb_substitute_character('');
1257                 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1258                 mb_substitute_character($subst);
1260             } else {
1261                 // Warn admins on admin/index.php page.
1262                 $result = $value;
1263             }
1265         } else {
1266             $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1267         }
1269         return $result;
1271     } else if (is_array($value)) {
1272         foreach ($value as $k => $v) {
1273             $value[$k] = fix_utf8($v);
1274         }
1275         return $value;
1277     } else if (is_object($value)) {
1278         // Do not modify original.
1279         $value = clone($value);
1280         foreach ($value as $k => $v) {
1281             $value->$k = fix_utf8($v);
1282         }
1283         return $value;
1285     } else {
1286         // This is some other type, no utf-8 here.
1287         return $value;
1288     }
1291 /**
1292  * Return true if given value is integer or string with integer value
1293  *
1294  * @param mixed $value String or Int
1295  * @return bool true if number, false if not
1296  */
1297 function is_number($value) {
1298     if (is_int($value)) {
1299         return true;
1300     } else if (is_string($value)) {
1301         return ((string)(int)$value) === $value;
1302     } else {
1303         return false;
1304     }
1307 /**
1308  * Returns host part from url.
1309  *
1310  * @param string $url full url
1311  * @return string host, null if not found
1312  */
1313 function get_host_from_url($url) {
1314     preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1315     if ($matches) {
1316         return $matches[1];
1317     }
1318     return null;
1321 /**
1322  * Tests whether anything was returned by text editor
1323  *
1324  * This function is useful for testing whether something you got back from
1325  * the HTML editor actually contains anything. Sometimes the HTML editor
1326  * appear to be empty, but actually you get back a <br> tag or something.
1327  *
1328  * @param string $string a string containing HTML.
1329  * @return boolean does the string contain any actual content - that is text,
1330  * images, objects, etc.
1331  */
1332 function html_is_blank($string) {
1333     return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1336 /**
1337  * Set a key in global configuration
1338  *
1339  * Set a key/value pair in both this session's {@link $CFG} global variable
1340  * and in the 'config' database table for future sessions.
1341  *
1342  * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1343  * In that case it doesn't affect $CFG.
1344  *
1345  * A NULL value will delete the entry.
1346  *
1347  * NOTE: this function is called from lib/db/upgrade.php
1348  *
1349  * @param string $name the key to set
1350  * @param string $value the value to set (without magic quotes)
1351  * @param string $plugin (optional) the plugin scope, default null
1352  * @return bool true or exception
1353  */
1354 function set_config($name, $value, $plugin=null) {
1355     global $CFG, $DB;
1357     if (empty($plugin)) {
1358         if (!array_key_exists($name, $CFG->config_php_settings)) {
1359             // So it's defined for this invocation at least.
1360             if (is_null($value)) {
1361                 unset($CFG->$name);
1362             } else {
1363                 // Settings from db are always strings.
1364                 $CFG->$name = (string)$value;
1365             }
1366         }
1368         if ($DB->get_field('config', 'name', array('name' => $name))) {
1369             if ($value === null) {
1370                 $DB->delete_records('config', array('name' => $name));
1371             } else {
1372                 $DB->set_field('config', 'value', $value, array('name' => $name));
1373             }
1374         } else {
1375             if ($value !== null) {
1376                 $config = new stdClass();
1377                 $config->name  = $name;
1378                 $config->value = $value;
1379                 $DB->insert_record('config', $config, false);
1380             }
1381         }
1382         if ($name === 'siteidentifier') {
1383             cache_helper::update_site_identifier($value);
1384         }
1385         cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1386     } else {
1387         // Plugin scope.
1388         if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1389             if ($value===null) {
1390                 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1391             } else {
1392                 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1393             }
1394         } else {
1395             if ($value !== null) {
1396                 $config = new stdClass();
1397                 $config->plugin = $plugin;
1398                 $config->name   = $name;
1399                 $config->value  = $value;
1400                 $DB->insert_record('config_plugins', $config, false);
1401             }
1402         }
1403         cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1404     }
1406     return true;
1409 /**
1410  * Get configuration values from the global config table
1411  * or the config_plugins table.
1412  *
1413  * If called with one parameter, it will load all the config
1414  * variables for one plugin, and return them as an object.
1415  *
1416  * If called with 2 parameters it will return a string single
1417  * value or false if the value is not found.
1418  *
1419  * NOTE: this function is called from lib/db/upgrade.php
1420  *
1421  * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1422  *     that we need only fetch it once per request.
1423  * @param string $plugin full component name
1424  * @param string $name default null
1425  * @return mixed hash-like object or single value, return false no config found
1426  * @throws dml_exception
1427  */
1428 function get_config($plugin, $name = null) {
1429     global $CFG, $DB;
1431     static $siteidentifier = null;
1433     if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1434         $forced =& $CFG->config_php_settings;
1435         $iscore = true;
1436         $plugin = 'core';
1437     } else {
1438         if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1439             $forced =& $CFG->forced_plugin_settings[$plugin];
1440         } else {
1441             $forced = array();
1442         }
1443         $iscore = false;
1444     }
1446     if ($siteidentifier === null) {
1447         try {
1448             // This may fail during installation.
1449             // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1450             // install the database.
1451             $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1452         } catch (dml_exception $ex) {
1453             // Set siteidentifier to false. We don't want to trip this continually.
1454             $siteidentifier = false;
1455             throw $ex;
1456         }
1457     }
1459     if (!empty($name)) {
1460         if (array_key_exists($name, $forced)) {
1461             return (string)$forced[$name];
1462         } else if ($name === 'siteidentifier' && $plugin == 'core') {
1463             return $siteidentifier;
1464         }
1465     }
1467     $cache = cache::make('core', 'config');
1468     $result = $cache->get($plugin);
1469     if ($result === false) {
1470         // The user is after a recordset.
1471         if (!$iscore) {
1472             $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1473         } else {
1474             // This part is not really used any more, but anyway...
1475             $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1476         }
1477         $cache->set($plugin, $result);
1478     }
1480     if (!empty($name)) {
1481         if (array_key_exists($name, $result)) {
1482             return $result[$name];
1483         }
1484         return false;
1485     }
1487     if ($plugin === 'core') {
1488         $result['siteidentifier'] = $siteidentifier;
1489     }
1491     foreach ($forced as $key => $value) {
1492         if (is_null($value) or is_array($value) or is_object($value)) {
1493             // We do not want any extra mess here, just real settings that could be saved in db.
1494             unset($result[$key]);
1495         } else {
1496             // Convert to string as if it went through the DB.
1497             $result[$key] = (string)$value;
1498         }
1499     }
1501     return (object)$result;
1504 /**
1505  * Removes a key from global configuration.
1506  *
1507  * NOTE: this function is called from lib/db/upgrade.php
1508  *
1509  * @param string $name the key to set
1510  * @param string $plugin (optional) the plugin scope
1511  * @return boolean whether the operation succeeded.
1512  */
1513 function unset_config($name, $plugin=null) {
1514     global $CFG, $DB;
1516     if (empty($plugin)) {
1517         unset($CFG->$name);
1518         $DB->delete_records('config', array('name' => $name));
1519         cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1520     } else {
1521         $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1522         cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1523     }
1525     return true;
1528 /**
1529  * Remove all the config variables for a given plugin.
1530  *
1531  * NOTE: this function is called from lib/db/upgrade.php
1532  *
1533  * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1534  * @return boolean whether the operation succeeded.
1535  */
1536 function unset_all_config_for_plugin($plugin) {
1537     global $DB;
1538     // Delete from the obvious config_plugins first.
1539     $DB->delete_records('config_plugins', array('plugin' => $plugin));
1540     // Next delete any suspect settings from config.
1541     $like = $DB->sql_like('name', '?', true, true, false, '|');
1542     $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1543     $DB->delete_records_select('config', $like, $params);
1544     // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1545     cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1547     return true;
1550 /**
1551  * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1552  *
1553  * All users are verified if they still have the necessary capability.
1554  *
1555  * @param string $value the value of the config setting.
1556  * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1557  * @param bool $includeadmins include administrators.
1558  * @return array of user objects.
1559  */
1560 function get_users_from_config($value, $capability, $includeadmins = true) {
1561     if (empty($value) or $value === '$@NONE@$') {
1562         return array();
1563     }
1565     // We have to make sure that users still have the necessary capability,
1566     // it should be faster to fetch them all first and then test if they are present
1567     // instead of validating them one-by-one.
1568     $users = get_users_by_capability(context_system::instance(), $capability);
1569     if ($includeadmins) {
1570         $admins = get_admins();
1571         foreach ($admins as $admin) {
1572             $users[$admin->id] = $admin;
1573         }
1574     }
1576     if ($value === '$@ALL@$') {
1577         return $users;
1578     }
1580     $result = array(); // Result in correct order.
1581     $allowed = explode(',', $value);
1582     foreach ($allowed as $uid) {
1583         if (isset($users[$uid])) {
1584             $user = $users[$uid];
1585             $result[$user->id] = $user;
1586         }
1587     }
1589     return $result;
1593 /**
1594  * Invalidates browser caches and cached data in temp.
1595  *
1596  * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1597  * {@link phpunit_util::reset_dataroot()}
1598  *
1599  * @return void
1600  */
1601 function purge_all_caches() {
1602     global $CFG, $DB;
1604     reset_text_filters_cache();
1605     js_reset_all_caches();
1606     theme_reset_all_caches();
1607     get_string_manager()->reset_caches();
1608     core_text::reset_caches();
1609     if (class_exists('core_plugin_manager')) {
1610         core_plugin_manager::reset_caches();
1611     }
1613     // Bump up cacherev field for all courses.
1614     try {
1615         increment_revision_number('course', 'cacherev', '');
1616     } catch (moodle_exception $e) {
1617         // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1618     }
1620     $DB->reset_caches();
1621     cache_helper::purge_all();
1623     // Purge all other caches: rss, simplepie, etc.
1624     remove_dir($CFG->cachedir.'', true);
1626     // Make sure cache dir is writable, throws exception if not.
1627     make_cache_directory('');
1629     // This is the only place where we purge local caches, we are only adding files there.
1630     // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1631     remove_dir($CFG->localcachedir, true);
1632     set_config('localcachedirpurged', time());
1633     make_localcache_directory('', true);
1634     \core\task\manager::clear_static_caches();
1637 /**
1638  * Get volatile flags
1639  *
1640  * @param string $type
1641  * @param int $changedsince default null
1642  * @return array records array
1643  */
1644 function get_cache_flags($type, $changedsince = null) {
1645     global $DB;
1647     $params = array('type' => $type, 'expiry' => time());
1648     $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1649     if ($changedsince !== null) {
1650         $params['changedsince'] = $changedsince;
1651         $sqlwhere .= " AND timemodified > :changedsince";
1652     }
1653     $cf = array();
1654     if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1655         foreach ($flags as $flag) {
1656             $cf[$flag->name] = $flag->value;
1657         }
1658     }
1659     return $cf;
1662 /**
1663  * Get volatile flags
1664  *
1665  * @param string $type
1666  * @param string $name
1667  * @param int $changedsince default null
1668  * @return string|false The cache flag value or false
1669  */
1670 function get_cache_flag($type, $name, $changedsince=null) {
1671     global $DB;
1673     $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1675     $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1676     if ($changedsince !== null) {
1677         $params['changedsince'] = $changedsince;
1678         $sqlwhere .= " AND timemodified > :changedsince";
1679     }
1681     return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1684 /**
1685  * Set a volatile flag
1686  *
1687  * @param string $type the "type" namespace for the key
1688  * @param string $name the key to set
1689  * @param string $value the value to set (without magic quotes) - null will remove the flag
1690  * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1691  * @return bool Always returns true
1692  */
1693 function set_cache_flag($type, $name, $value, $expiry = null) {
1694     global $DB;
1696     $timemodified = time();
1697     if ($expiry === null || $expiry < $timemodified) {
1698         $expiry = $timemodified + 24 * 60 * 60;
1699     } else {
1700         $expiry = (int)$expiry;
1701     }
1703     if ($value === null) {
1704         unset_cache_flag($type, $name);
1705         return true;
1706     }
1708     if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1709         // This is a potential problem in DEBUG_DEVELOPER.
1710         if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1711             return true; // No need to update.
1712         }
1713         $f->value        = $value;
1714         $f->expiry       = $expiry;
1715         $f->timemodified = $timemodified;
1716         $DB->update_record('cache_flags', $f);
1717     } else {
1718         $f = new stdClass();
1719         $f->flagtype     = $type;
1720         $f->name         = $name;
1721         $f->value        = $value;
1722         $f->expiry       = $expiry;
1723         $f->timemodified = $timemodified;
1724         $DB->insert_record('cache_flags', $f);
1725     }
1726     return true;
1729 /**
1730  * Removes a single volatile flag
1731  *
1732  * @param string $type the "type" namespace for the key
1733  * @param string $name the key to set
1734  * @return bool
1735  */
1736 function unset_cache_flag($type, $name) {
1737     global $DB;
1738     $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1739     return true;
1742 /**
1743  * Garbage-collect volatile flags
1744  *
1745  * @return bool Always returns true
1746  */
1747 function gc_cache_flags() {
1748     global $DB;
1749     $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1750     return true;
1753 // USER PREFERENCE API.
1755 /**
1756  * Refresh user preference cache. This is used most often for $USER
1757  * object that is stored in session, but it also helps with performance in cron script.
1758  *
1759  * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1760  *
1761  * @package  core
1762  * @category preference
1763  * @access   public
1764  * @param    stdClass         $user          User object. Preferences are preloaded into 'preference' property
1765  * @param    int              $cachelifetime Cache life time on the current page (in seconds)
1766  * @throws   coding_exception
1767  * @return   null
1768  */
1769 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1770     global $DB;
1771     // Static cache, we need to check on each page load, not only every 2 minutes.
1772     static $loadedusers = array();
1774     if (!isset($user->id)) {
1775         throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1776     }
1778     if (empty($user->id) or isguestuser($user->id)) {
1779         // No permanent storage for not-logged-in users and guest.
1780         if (!isset($user->preference)) {
1781             $user->preference = array();
1782         }
1783         return;
1784     }
1786     $timenow = time();
1788     if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1789         // Already loaded at least once on this page. Are we up to date?
1790         if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1791             // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1792             return;
1794         } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1795             // No change since the lastcheck on this page.
1796             $user->preference['_lastloaded'] = $timenow;
1797             return;
1798         }
1799     }
1801     // OK, so we have to reload all preferences.
1802     $loadedusers[$user->id] = true;
1803     $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1804     $user->preference['_lastloaded'] = $timenow;
1807 /**
1808  * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1809  *
1810  * NOTE: internal function, do not call from other code.
1811  *
1812  * @package core
1813  * @access private
1814  * @param integer $userid the user whose prefs were changed.
1815  */
1816 function mark_user_preferences_changed($userid) {
1817     global $CFG;
1819     if (empty($userid) or isguestuser($userid)) {
1820         // No cache flags for guest and not-logged-in users.
1821         return;
1822     }
1824     set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1827 /**
1828  * Sets a preference for the specified user.
1829  *
1830  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1831  *
1832  * @package  core
1833  * @category preference
1834  * @access   public
1835  * @param    string            $name  The key to set as preference for the specified user
1836  * @param    string            $value The value to set for the $name key in the specified user's
1837  *                                    record, null means delete current value.
1838  * @param    stdClass|int|null $user  A moodle user object or id, null means current user
1839  * @throws   coding_exception
1840  * @return   bool                     Always true or exception
1841  */
1842 function set_user_preference($name, $value, $user = null) {
1843     global $USER, $DB;
1845     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1846         throw new coding_exception('Invalid preference name in set_user_preference() call');
1847     }
1849     if (is_null($value)) {
1850         // Null means delete current.
1851         return unset_user_preference($name, $user);
1852     } else if (is_object($value)) {
1853         throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1854     } else if (is_array($value)) {
1855         throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1856     }
1857     // Value column maximum length is 1333 characters.
1858     $value = (string)$value;
1859     if (core_text::strlen($value) > 1333) {
1860         throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1861     }
1863     if (is_null($user)) {
1864         $user = $USER;
1865     } else if (isset($user->id)) {
1866         // It is a valid object.
1867     } else if (is_numeric($user)) {
1868         $user = (object)array('id' => (int)$user);
1869     } else {
1870         throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1871     }
1873     check_user_preferences_loaded($user);
1875     if (empty($user->id) or isguestuser($user->id)) {
1876         // No permanent storage for not-logged-in users and guest.
1877         $user->preference[$name] = $value;
1878         return true;
1879     }
1881     if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1882         if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1883             // Preference already set to this value.
1884             return true;
1885         }
1886         $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1888     } else {
1889         $preference = new stdClass();
1890         $preference->userid = $user->id;
1891         $preference->name   = $name;
1892         $preference->value  = $value;
1893         $DB->insert_record('user_preferences', $preference);
1894     }
1896     // Update value in cache.
1897     $user->preference[$name] = $value;
1899     // Set reload flag for other sessions.
1900     mark_user_preferences_changed($user->id);
1902     return true;
1905 /**
1906  * Sets a whole array of preferences for the current user
1907  *
1908  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1909  *
1910  * @package  core
1911  * @category preference
1912  * @access   public
1913  * @param    array             $prefarray An array of key/value pairs to be set
1914  * @param    stdClass|int|null $user      A moodle user object or id, null means current user
1915  * @return   bool                         Always true or exception
1916  */
1917 function set_user_preferences(array $prefarray, $user = null) {
1918     foreach ($prefarray as $name => $value) {
1919         set_user_preference($name, $value, $user);
1920     }
1921     return true;
1924 /**
1925  * Unsets a preference completely by deleting it from the database
1926  *
1927  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1928  *
1929  * @package  core
1930  * @category preference
1931  * @access   public
1932  * @param    string            $name The key to unset as preference for the specified user
1933  * @param    stdClass|int|null $user A moodle user object or id, null means current user
1934  * @throws   coding_exception
1935  * @return   bool                    Always true or exception
1936  */
1937 function unset_user_preference($name, $user = null) {
1938     global $USER, $DB;
1940     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1941         throw new coding_exception('Invalid preference name in unset_user_preference() call');
1942     }
1944     if (is_null($user)) {
1945         $user = $USER;
1946     } else if (isset($user->id)) {
1947         // It is a valid object.
1948     } else if (is_numeric($user)) {
1949         $user = (object)array('id' => (int)$user);
1950     } else {
1951         throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1952     }
1954     check_user_preferences_loaded($user);
1956     if (empty($user->id) or isguestuser($user->id)) {
1957         // No permanent storage for not-logged-in user and guest.
1958         unset($user->preference[$name]);
1959         return true;
1960     }
1962     // Delete from DB.
1963     $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1965     // Delete the preference from cache.
1966     unset($user->preference[$name]);
1968     // Set reload flag for other sessions.
1969     mark_user_preferences_changed($user->id);
1971     return true;
1974 /**
1975  * Used to fetch user preference(s)
1976  *
1977  * If no arguments are supplied this function will return
1978  * all of the current user preferences as an array.
1979  *
1980  * If a name is specified then this function
1981  * attempts to return that particular preference value.  If
1982  * none is found, then the optional value $default is returned,
1983  * otherwise null.
1984  *
1985  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1986  *
1987  * @package  core
1988  * @category preference
1989  * @access   public
1990  * @param    string            $name    Name of the key to use in finding a preference value
1991  * @param    mixed|null        $default Value to be returned if the $name key is not set in the user preferences
1992  * @param    stdClass|int|null $user    A moodle user object or id, null means current user
1993  * @throws   coding_exception
1994  * @return   string|mixed|null          A string containing the value of a single preference. An
1995  *                                      array with all of the preferences or null
1996  */
1997 function get_user_preferences($name = null, $default = null, $user = null) {
1998     global $USER;
2000     if (is_null($name)) {
2001         // All prefs.
2002     } else if (is_numeric($name) or $name === '_lastloaded') {
2003         throw new coding_exception('Invalid preference name in get_user_preferences() call');
2004     }
2006     if (is_null($user)) {
2007         $user = $USER;
2008     } else if (isset($user->id)) {
2009         // Is a valid object.
2010     } else if (is_numeric($user)) {
2011         $user = (object)array('id' => (int)$user);
2012     } else {
2013         throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2014     }
2016     check_user_preferences_loaded($user);
2018     if (empty($name)) {
2019         // All values.
2020         return $user->preference;
2021     } else if (isset($user->preference[$name])) {
2022         // The single string value.
2023         return $user->preference[$name];
2024     } else {
2025         // Default value (null if not specified).
2026         return $default;
2027     }
2030 // FUNCTIONS FOR HANDLING TIME.
2032 /**
2033  * Given Gregorian date parts in user time produce a GMT timestamp.
2034  *
2035  * @package core
2036  * @category time
2037  * @param int $year The year part to create timestamp of
2038  * @param int $month The month part to create timestamp of
2039  * @param int $day The day part to create timestamp of
2040  * @param int $hour The hour part to create timestamp of
2041  * @param int $minute The minute part to create timestamp of
2042  * @param int $second The second part to create timestamp of
2043  * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2044  *             if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2045  * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2046  *             applied only if timezone is 99 or string.
2047  * @return int GMT timestamp
2048  */
2049 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2050     $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2051     $date->setDate((int)$year, (int)$month, (int)$day);
2052     $date->setTime((int)$hour, (int)$minute, (int)$second);
2054     $time = $date->getTimestamp();
2056     if ($time === false) {
2057         throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2058             ' This can fail if year is more than 2038 and OS is 32 bit windows');
2059     }
2061     // Moodle BC DST stuff.
2062     if (!$applydst) {
2063         $time += dst_offset_on($time, $timezone);
2064     }
2066     return $time;
2070 /**
2071  * Format a date/time (seconds) as weeks, days, hours etc as needed
2072  *
2073  * Given an amount of time in seconds, returns string
2074  * formatted nicely as weeks, days, hours etc as needed
2075  *
2076  * @package core
2077  * @category time
2078  * @uses MINSECS
2079  * @uses HOURSECS
2080  * @uses DAYSECS
2081  * @uses YEARSECS
2082  * @param int $totalsecs Time in seconds
2083  * @param stdClass $str Should be a time object
2084  * @return string A nicely formatted date/time string
2085  */
2086 function format_time($totalsecs, $str = null) {
2088     $totalsecs = abs($totalsecs);
2090     if (!$str) {
2091         // Create the str structure the slow way.
2092         $str = new stdClass();
2093         $str->day   = get_string('day');
2094         $str->days  = get_string('days');
2095         $str->hour  = get_string('hour');
2096         $str->hours = get_string('hours');
2097         $str->min   = get_string('min');
2098         $str->mins  = get_string('mins');
2099         $str->sec   = get_string('sec');
2100         $str->secs  = get_string('secs');
2101         $str->year  = get_string('year');
2102         $str->years = get_string('years');
2103     }
2105     $years     = floor($totalsecs/YEARSECS);
2106     $remainder = $totalsecs - ($years*YEARSECS);
2107     $days      = floor($remainder/DAYSECS);
2108     $remainder = $totalsecs - ($days*DAYSECS);
2109     $hours     = floor($remainder/HOURSECS);
2110     $remainder = $remainder - ($hours*HOURSECS);
2111     $mins      = floor($remainder/MINSECS);
2112     $secs      = $remainder - ($mins*MINSECS);
2114     $ss = ($secs == 1)  ? $str->sec  : $str->secs;
2115     $sm = ($mins == 1)  ? $str->min  : $str->mins;
2116     $sh = ($hours == 1) ? $str->hour : $str->hours;
2117     $sd = ($days == 1)  ? $str->day  : $str->days;
2118     $sy = ($years == 1)  ? $str->year  : $str->years;
2120     $oyears = '';
2121     $odays = '';
2122     $ohours = '';
2123     $omins = '';
2124     $osecs = '';
2126     if ($years) {
2127         $oyears  = $years .' '. $sy;
2128     }
2129     if ($days) {
2130         $odays  = $days .' '. $sd;
2131     }
2132     if ($hours) {
2133         $ohours = $hours .' '. $sh;
2134     }
2135     if ($mins) {
2136         $omins  = $mins .' '. $sm;
2137     }
2138     if ($secs) {
2139         $osecs  = $secs .' '. $ss;
2140     }
2142     if ($years) {
2143         return trim($oyears .' '. $odays);
2144     }
2145     if ($days) {
2146         return trim($odays .' '. $ohours);
2147     }
2148     if ($hours) {
2149         return trim($ohours .' '. $omins);
2150     }
2151     if ($mins) {
2152         return trim($omins .' '. $osecs);
2153     }
2154     if ($secs) {
2155         return $osecs;
2156     }
2157     return get_string('now');
2160 /**
2161  * Returns a formatted string that represents a date in user time.
2162  *
2163  * @package core
2164  * @category time
2165  * @param int $date the timestamp in UTC, as obtained from the database.
2166  * @param string $format strftime format. You should probably get this using
2167  *        get_string('strftime...', 'langconfig');
2168  * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2169  *        not 99 then daylight saving will not be added.
2170  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2171  * @param bool $fixday If true (default) then the leading zero from %d is removed.
2172  *        If false then the leading zero is maintained.
2173  * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2174  * @return string the formatted date/time.
2175  */
2176 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2177     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2178     return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2181 /**
2182  * Returns a formatted date ensuring it is UTF-8.
2183  *
2184  * If we are running under Windows convert to Windows encoding and then back to UTF-8
2185  * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2186  *
2187  * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2188  * @param string $format strftime format.
2189  * @param int|float|string $tz the user timezone
2190  * @return string the formatted date/time.
2191  * @since Moodle 2.3.3
2192  */
2193 function date_format_string($date, $format, $tz = 99) {
2194     global $CFG;
2196     $localewincharset = null;
2197     // Get the calendar type user is using.
2198     if ($CFG->ostype == 'WINDOWS') {
2199         $calendartype = \core_calendar\type_factory::get_calendar_instance();
2200         $localewincharset = $calendartype->locale_win_charset();
2201     }
2203     if ($localewincharset) {
2204         $format = core_text::convert($format, 'utf-8', $localewincharset);
2205     }
2207     date_default_timezone_set(core_date::get_user_timezone($tz));
2208     $datestring = strftime($format, $date);
2209     core_date::set_default_server_timezone();
2211     if ($localewincharset) {
2212         $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2213     }
2215     return $datestring;
2218 /**
2219  * Given a $time timestamp in GMT (seconds since epoch),
2220  * returns an array that represents the Gregorian date in user time
2221  *
2222  * @package core
2223  * @category time
2224  * @param int $time Timestamp in GMT
2225  * @param float|int|string $timezone user timezone
2226  * @return array An array that represents the date in user time
2227  */
2228 function usergetdate($time, $timezone=99) {
2229     date_default_timezone_set(core_date::get_user_timezone($timezone));
2230     $result = getdate($time);
2231     core_date::set_default_server_timezone();
2233     return $result;
2236 /**
2237  * Given a GMT timestamp (seconds since epoch), offsets it by
2238  * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2239  *
2240  * NOTE: this function does not include DST properly,
2241  *       you should use the PHP date stuff instead!
2242  *
2243  * @package core
2244  * @category time
2245  * @param int $date Timestamp in GMT
2246  * @param float|int|string $timezone user timezone
2247  * @return int
2248  */
2249 function usertime($date, $timezone=99) {
2250     $userdate = new DateTime('@' . $date);
2251     $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2252     $dst = dst_offset_on($date, $timezone);
2254     return $date - $userdate->getOffset() + $dst;
2257 /**
2258  * Given a time, return the GMT timestamp of the most recent midnight
2259  * for the current user.
2260  *
2261  * @package core
2262  * @category time
2263  * @param int $date Timestamp in GMT
2264  * @param float|int|string $timezone user timezone
2265  * @return int Returns a GMT timestamp
2266  */
2267 function usergetmidnight($date, $timezone=99) {
2269     $userdate = usergetdate($date, $timezone);
2271     // Time of midnight of this user's day, in GMT.
2272     return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2276 /**
2277  * Returns a string that prints the user's timezone
2278  *
2279  * @package core
2280  * @category time
2281  * @param float|int|string $timezone user timezone
2282  * @return string
2283  */
2284 function usertimezone($timezone=99) {
2285     $tz = core_date::get_user_timezone($timezone);
2286     return core_date::get_localised_timezone($tz);
2289 /**
2290  * Returns a float or a string which denotes the user's timezone
2291  * 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)
2292  * means that for this timezone there are also DST rules to be taken into account
2293  * Checks various settings and picks the most dominant of those which have a value
2294  *
2295  * @package core
2296  * @category time
2297  * @param float|int|string $tz timezone to calculate GMT time offset before
2298  *        calculating user timezone, 99 is default user timezone
2299  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2300  * @return float|string
2301  */
2302 function get_user_timezone($tz = 99) {
2303     global $USER, $CFG;
2305     $timezones = array(
2306         $tz,
2307         isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2308         isset($USER->timezone) ? $USER->timezone : 99,
2309         isset($CFG->timezone) ? $CFG->timezone : 99,
2310         );
2312     $tz = 99;
2314     // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2315     while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2316         $tz = $next['value'];
2317     }
2318     return is_numeric($tz) ? (float) $tz : $tz;
2321 /**
2322  * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2323  * - Note: Daylight saving only works for string timezones and not for float.
2324  *
2325  * @package core
2326  * @category time
2327  * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2328  * @param int|float|string $strtimezone user timezone
2329  * @return int
2330  */
2331 function dst_offset_on($time, $strtimezone = null) {
2332     $tz = core_date::get_user_timezone($strtimezone);
2333     $date = new DateTime('@' . $time);
2334     $date->setTimezone(new DateTimeZone($tz));
2335     if ($date->format('I') == '1') {
2336         if ($tz === 'Australia/Lord_Howe') {
2337             return 1800;
2338         }
2339         return 3600;
2340     }
2341     return 0;
2344 /**
2345  * Calculates when the day appears in specific month
2346  *
2347  * @package core
2348  * @category time
2349  * @param int $startday starting day of the month
2350  * @param int $weekday The day when week starts (normally taken from user preferences)
2351  * @param int $month The month whose day is sought
2352  * @param int $year The year of the month whose day is sought
2353  * @return int
2354  */
2355 function find_day_in_month($startday, $weekday, $month, $year) {
2356     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2358     $daysinmonth = days_in_month($month, $year);
2359     $daysinweek = count($calendartype->get_weekdays());
2361     if ($weekday == -1) {
2362         // Don't care about weekday, so return:
2363         //    abs($startday) if $startday != -1
2364         //    $daysinmonth otherwise.
2365         return ($startday == -1) ? $daysinmonth : abs($startday);
2366     }
2368     // From now on we 're looking for a specific weekday.
2369     // Give "end of month" its actual value, since we know it.
2370     if ($startday == -1) {
2371         $startday = -1 * $daysinmonth;
2372     }
2374     // Starting from day $startday, the sign is the direction.
2375     if ($startday < 1) {
2376         $startday = abs($startday);
2377         $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2379         // This is the last such weekday of the month.
2380         $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2381         if ($lastinmonth > $daysinmonth) {
2382             $lastinmonth -= $daysinweek;
2383         }
2385         // Find the first such weekday <= $startday.
2386         while ($lastinmonth > $startday) {
2387             $lastinmonth -= $daysinweek;
2388         }
2390         return $lastinmonth;
2391     } else {
2392         $indexweekday = dayofweek($startday, $month, $year);
2394         $diff = $weekday - $indexweekday;
2395         if ($diff < 0) {
2396             $diff += $daysinweek;
2397         }
2399         // This is the first such weekday of the month equal to or after $startday.
2400         $firstfromindex = $startday + $diff;
2402         return $firstfromindex;
2403     }
2406 /**
2407  * Calculate the number of days in a given month
2408  *
2409  * @package core
2410  * @category time
2411  * @param int $month The month whose day count is sought
2412  * @param int $year The year of the month whose day count is sought
2413  * @return int
2414  */
2415 function days_in_month($month, $year) {
2416     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2417     return $calendartype->get_num_days_in_month($year, $month);
2420 /**
2421  * Calculate the position in the week of a specific calendar day
2422  *
2423  * @package core
2424  * @category time
2425  * @param int $day The day of the date whose position in the week is sought
2426  * @param int $month The month of the date whose position in the week is sought
2427  * @param int $year The year of the date whose position in the week is sought
2428  * @return int
2429  */
2430 function dayofweek($day, $month, $year) {
2431     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2432     return $calendartype->get_weekday($year, $month, $day);
2435 // USER AUTHENTICATION AND LOGIN.
2437 /**
2438  * Returns full login url.
2439  *
2440  * @return string login url
2441  */
2442 function get_login_url() {
2443     global $CFG;
2445     $url = "$CFG->wwwroot/login/index.php";
2447     if (!empty($CFG->loginhttps)) {
2448         $url = str_replace('http:', 'https:', $url);
2449     }
2451     return $url;
2454 /**
2455  * This function checks that the current user is logged in and has the
2456  * required privileges
2457  *
2458  * This function checks that the current user is logged in, and optionally
2459  * whether they are allowed to be in a particular course and view a particular
2460  * course module.
2461  * If they are not logged in, then it redirects them to the site login unless
2462  * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2463  * case they are automatically logged in as guests.
2464  * If $courseid is given and the user is not enrolled in that course then the
2465  * user is redirected to the course enrolment page.
2466  * If $cm is given and the course module is hidden and the user is not a teacher
2467  * in the course then the user is redirected to the course home page.
2468  *
2469  * When $cm parameter specified, this function sets page layout to 'module'.
2470  * You need to change it manually later if some other layout needed.
2471  *
2472  * @package    core_access
2473  * @category   access
2474  *
2475  * @param mixed $courseorid id of the course or course object
2476  * @param bool $autologinguest default true
2477  * @param object $cm course module object
2478  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2479  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2480  *             in order to keep redirects working properly. MDL-14495
2481  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2482  * @return mixed Void, exit, and die depending on path
2483  * @throws coding_exception
2484  * @throws require_login_exception
2485  */
2486 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2487     global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2489     // Must not redirect when byteserving already started.
2490     if (!empty($_SERVER['HTTP_RANGE'])) {
2491         $preventredirect = true;
2492     }
2494     if (AJAX_SCRIPT) {
2495         // We cannot redirect for AJAX scripts either.
2496         $preventredirect = true;
2497     }
2499     // Setup global $COURSE, themes, language and locale.
2500     if (!empty($courseorid)) {
2501         if (is_object($courseorid)) {
2502             $course = $courseorid;
2503         } else if ($courseorid == SITEID) {
2504             $course = clone($SITE);
2505         } else {
2506             $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2507         }
2508         if ($cm) {
2509             if ($cm->course != $course->id) {
2510                 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2511             }
2512             // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2513             if (!($cm instanceof cm_info)) {
2514                 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2515                 // db queries so this is not really a performance concern, however it is obviously
2516                 // better if you use get_fast_modinfo to get the cm before calling this.
2517                 $modinfo = get_fast_modinfo($course);
2518                 $cm = $modinfo->get_cm($cm->id);
2519             }
2520         }
2521     } else {
2522         // Do not touch global $COURSE via $PAGE->set_course(),
2523         // the reasons is we need to be able to call require_login() at any time!!
2524         $course = $SITE;
2525         if ($cm) {
2526             throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2527         }
2528     }
2530     // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2531     // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2532     // risk leading the user back to the AJAX request URL.
2533     if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2534         $setwantsurltome = false;
2535     }
2537     // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2538     if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2539         if ($preventredirect) {
2540             throw new require_login_session_timeout_exception();
2541         } else {
2542             if ($setwantsurltome) {
2543                 $SESSION->wantsurl = qualified_me();
2544             }
2545             redirect(get_login_url());
2546         }
2547     }
2549     // If the user is not even logged in yet then make sure they are.
2550     if (!isloggedin()) {
2551         if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2552             if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2553                 // Misconfigured site guest, just redirect to login page.
2554                 redirect(get_login_url());
2555                 exit; // Never reached.
2556             }
2557             $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2558             complete_user_login($guest);
2559             $USER->autologinguest = true;
2560             $SESSION->lang = $lang;
2561         } else {
2562             // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2563             if ($preventredirect) {
2564                 throw new require_login_exception('You are not logged in');
2565             }
2567             if ($setwantsurltome) {
2568                 $SESSION->wantsurl = qualified_me();
2569             }
2571             $referer = get_local_referer(false);
2572             if (!empty($referer)) {
2573                 $SESSION->fromurl = $referer;
2574             }
2576             // Give auth plugins an opportunity to authenticate or redirect to an external login page
2577             $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2578             foreach($authsequence as $authname) {
2579                 $authplugin = get_auth_plugin($authname);
2580                 $authplugin->pre_loginpage_hook();
2581                 if (isloggedin()) {
2582                     break;
2583                 }
2584             }
2586             // If we're still not logged in then go to the login page
2587             if (!isloggedin()) {
2588                 redirect(get_login_url());
2589                 exit; // Never reached.
2590             }
2591         }
2592     }
2594     // Loginas as redirection if needed.
2595     if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2596         if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2597             if ($USER->loginascontext->instanceid != $course->id) {
2598                 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2599             }
2600         }
2601     }
2603     // Check whether the user should be changing password (but only if it is REALLY them).
2604     if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2605         $userauth = get_auth_plugin($USER->auth);
2606         if ($userauth->can_change_password() and !$preventredirect) {
2607             if ($setwantsurltome) {
2608                 $SESSION->wantsurl = qualified_me();
2609             }
2610             if ($changeurl = $userauth->change_password_url()) {
2611                 // Use plugin custom url.
2612                 redirect($changeurl);
2613             } else {
2614                 // Use moodle internal method.
2615                 if (empty($CFG->loginhttps)) {
2616                     redirect($CFG->wwwroot .'/login/change_password.php');
2617                 } else {
2618                     $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2619                     redirect($wwwroot .'/login/change_password.php');
2620                 }
2621             }
2622         } else {
2623             print_error('nopasswordchangeforced', 'auth');
2624         }
2625     }
2627     // Check that the user account is properly set up.
2628     if (user_not_fully_set_up($USER)) {
2629         if ($preventredirect) {
2630             throw new require_login_exception('User not fully set-up');
2631         }
2632         if ($setwantsurltome) {
2633             $SESSION->wantsurl = qualified_me();
2634         }
2635         redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2636     }
2638     // Make sure the USER has a sesskey set up. Used for CSRF protection.
2639     sesskey();
2641     // Do not bother admins with any formalities.
2642     if (is_siteadmin()) {
2643         // Set the global $COURSE.
2644         if ($cm) {
2645             $PAGE->set_cm($cm, $course);
2646             $PAGE->set_pagelayout('incourse');
2647         } else if (!empty($courseorid)) {
2648             $PAGE->set_course($course);
2649         }
2650         // Set accesstime or the user will appear offline which messes up messaging.
2651         user_accesstime_log($course->id);
2652         return;
2653     }
2655     // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2656     if (!$USER->policyagreed and !is_siteadmin()) {
2657         if (!empty($CFG->sitepolicy) and !isguestuser()) {
2658             if ($preventredirect) {
2659                 throw new require_login_exception('Policy not agreed');
2660             }
2661             if ($setwantsurltome) {
2662                 $SESSION->wantsurl = qualified_me();
2663             }
2664             redirect($CFG->wwwroot .'/user/policy.php');
2665         } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2666             if ($preventredirect) {
2667                 throw new require_login_exception('Policy not agreed');
2668             }
2669             if ($setwantsurltome) {
2670                 $SESSION->wantsurl = qualified_me();
2671             }
2672             redirect($CFG->wwwroot .'/user/policy.php');
2673         }
2674     }
2676     // Fetch the system context, the course context, and prefetch its child contexts.
2677     $sysctx = context_system::instance();
2678     $coursecontext = context_course::instance($course->id, MUST_EXIST);
2679     if ($cm) {
2680         $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2681     } else {
2682         $cmcontext = null;
2683     }
2685     // If the site is currently under maintenance, then print a message.
2686     if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2687         if ($preventredirect) {
2688             throw new require_login_exception('Maintenance in progress');
2689         }
2691         print_maintenance_message();
2692     }
2694     // Make sure the course itself is not hidden.
2695     if ($course->id == SITEID) {
2696         // Frontpage can not be hidden.
2697     } else {
2698         if (is_role_switched($course->id)) {
2699             // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2700         } else {
2701             if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2702                 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2703                 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2704                 if ($preventredirect) {
2705                     throw new require_login_exception('Course is hidden');
2706                 }
2707                 $PAGE->set_context(null);
2708                 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2709                 // the navigation will mess up when trying to find it.
2710                 navigation_node::override_active_url(new moodle_url('/'));
2711                 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2712             }
2713         }
2714     }
2716     // Is the user enrolled?
2717     if ($course->id == SITEID) {
2718         // Everybody is enrolled on the frontpage.
2719     } else {
2720         if (\core\session\manager::is_loggedinas()) {
2721             // Make sure the REAL person can access this course first.
2722             $realuser = \core\session\manager::get_realuser();
2723             if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2724                 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2725                 if ($preventredirect) {
2726                     throw new require_login_exception('Invalid course login-as access');
2727                 }
2728                 $PAGE->set_context(null);
2729                 echo $OUTPUT->header();
2730                 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2731             }
2732         }
2734         $access = false;
2736         if (is_role_switched($course->id)) {
2737             // Ok, user had to be inside this course before the switch.
2738             $access = true;
2740         } else if (is_viewing($coursecontext, $USER)) {
2741             // Ok, no need to mess with enrol.
2742             $access = true;
2744         } else {
2745             if (isset($USER->enrol['enrolled'][$course->id])) {
2746                 if ($USER->enrol['enrolled'][$course->id] > time()) {
2747                     $access = true;
2748                     if (isset($USER->enrol['tempguest'][$course->id])) {
2749                         unset($USER->enrol['tempguest'][$course->id]);
2750                         remove_temp_course_roles($coursecontext);
2751                     }
2752                 } else {
2753                     // Expired.
2754                     unset($USER->enrol['enrolled'][$course->id]);
2755                 }
2756             }
2757             if (isset($USER->enrol['tempguest'][$course->id])) {
2758                 if ($USER->enrol['tempguest'][$course->id] == 0) {
2759                     $access = true;
2760                 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2761                     $access = true;
2762                 } else {
2763                     // Expired.
2764                     unset($USER->enrol['tempguest'][$course->id]);
2765                     remove_temp_course_roles($coursecontext);
2766                 }
2767             }
2769             if (!$access) {
2770                 // Cache not ok.
2771                 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2772                 if ($until !== false) {
2773                     // Active participants may always access, a timestamp in the future, 0 (always) or false.
2774                     if ($until == 0) {
2775                         $until = ENROL_MAX_TIMESTAMP;
2776                     }
2777                     $USER->enrol['enrolled'][$course->id] = $until;
2778                     $access = true;
2780                 } else {
2781                     $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2782                     $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2783                     $enrols = enrol_get_plugins(true);
2784                     // First ask all enabled enrol instances in course if they want to auto enrol user.
2785                     foreach ($instances as $instance) {
2786                         if (!isset($enrols[$instance->enrol])) {
2787                             continue;
2788                         }
2789                         // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2790                         $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2791                         if ($until !== false) {
2792                             if ($until == 0) {
2793                                 $until = ENROL_MAX_TIMESTAMP;
2794                             }
2795                             $USER->enrol['enrolled'][$course->id] = $until;
2796                             $access = true;
2797                             break;
2798                         }
2799                     }
2800                     // If not enrolled yet try to gain temporary guest access.
2801                     if (!$access) {
2802                         foreach ($instances as $instance) {
2803                             if (!isset($enrols[$instance->enrol])) {
2804                                 continue;
2805                             }
2806                             // Get a duration for the guest access, a timestamp in the future or false.
2807                             $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2808                             if ($until !== false and $until > time()) {
2809                                 $USER->enrol['tempguest'][$course->id] = $until;
2810                                 $access = true;
2811                                 break;
2812                             }
2813                         }
2814                     }
2815                 }
2816             }
2817         }
2819         if (!$access) {
2820             if ($preventredirect) {
2821                 throw new require_login_exception('Not enrolled');
2822             }
2823             if ($setwantsurltome) {
2824                 $SESSION->wantsurl = qualified_me();
2825             }
2826             redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2827         }
2828     }
2830     // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2831     if ($cm && !$cm->uservisible) {
2832         if ($preventredirect) {
2833             throw new require_login_exception('Activity is hidden');
2834         }
2835         if ($course->id != SITEID) {
2836             $url = new moodle_url('/course/view.php', array('id' => $course->id));
2837         } else {
2838             $url = new moodle_url('/');
2839         }
2840         redirect($url, get_string('activityiscurrentlyhidden'));
2841     }
2843     // Set the global $COURSE.
2844     if ($cm) {
2845         $PAGE->set_cm($cm, $course);
2846         $PAGE->set_pagelayout('incourse');
2847     } else if (!empty($courseorid)) {
2848         $PAGE->set_course($course);
2849     }
2851     // Finally access granted, update lastaccess times.
2852     user_accesstime_log($course->id);
2856 /**
2857  * This function just makes sure a user is logged out.
2858  *
2859  * @package    core_access
2860  * @category   access
2861  */
2862 function require_logout() {
2863     global $USER, $DB;
2865     if (!isloggedin()) {
2866         // This should not happen often, no need for hooks or events here.
2867         \core\session\manager::terminate_current();
2868         return;
2869     }
2871     // Execute hooks before action.
2872     $authplugins = array();
2873     $authsequence = get_enabled_auth_plugins();
2874     foreach ($authsequence as $authname) {
2875         $authplugins[$authname] = get_auth_plugin($authname);
2876         $authplugins[$authname]->prelogout_hook();
2877     }
2879     // Store info that gets removed during logout.
2880     $sid = session_id();
2881     $event = \core\event\user_loggedout::create(
2882         array(
2883             'userid' => $USER->id,
2884             'objectid' => $USER->id,
2885             'other' => array('sessionid' => $sid),
2886         )
2887     );
2888     if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2889         $event->add_record_snapshot('sessions', $session);
2890     }
2892     // Clone of $USER object to be used by auth plugins.
2893     $user = fullclone($USER);
2895     // Delete session record and drop $_SESSION content.
2896     \core\session\manager::terminate_current();
2898     // Trigger event AFTER action.
2899     $event->trigger();
2901     // Hook to execute auth plugins redirection after event trigger.
2902     foreach ($authplugins as $authplugin) {
2903         $authplugin->postlogout_hook($user);
2904     }
2907 /**
2908  * Weaker version of require_login()
2909  *
2910  * This is a weaker version of {@link require_login()} which only requires login
2911  * when called from within a course rather than the site page, unless
2912  * the forcelogin option is turned on.
2913  * @see require_login()
2914  *
2915  * @package    core_access
2916  * @category   access
2917  *
2918  * @param mixed $courseorid The course object or id in question
2919  * @param bool $autologinguest Allow autologin guests if that is wanted
2920  * @param object $cm Course activity module if known
2921  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2922  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2923  *             in order to keep redirects working properly. MDL-14495
2924  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2925  * @return void
2926  * @throws coding_exception
2927  */
2928 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2929     global $CFG, $PAGE, $SITE;
2930     $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2931           or (!is_object($courseorid) and $courseorid == SITEID));
2932     if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2933         // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2934         // db queries so this is not really a performance concern, however it is obviously
2935         // better if you use get_fast_modinfo to get the cm before calling this.
2936         if (is_object($courseorid)) {
2937             $course = $courseorid;
2938         } else {
2939             $course = clone($SITE);
2940         }
2941         $modinfo = get_fast_modinfo($course);
2942         $cm = $modinfo->get_cm($cm->id);
2943     }
2944     if (!empty($CFG->forcelogin)) {
2945         // Login required for both SITE and courses.
2946         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2948     } else if ($issite && !empty($cm) and !$cm->uservisible) {
2949         // Always login for hidden activities.
2950         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2952     } else if ($issite) {
2953         // Login for SITE not required.
2954         // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
2955         if (!empty($courseorid)) {
2956             if (is_object($courseorid)) {
2957                 $course = $courseorid;
2958             } else {
2959                 $course = clone $SITE;
2960             }
2961             if ($cm) {
2962                 if ($cm->course != $course->id) {
2963                     throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2964                 }
2965                 $PAGE->set_cm($cm, $course);
2966                 $PAGE->set_pagelayout('incourse');
2967             } else {
2968                 $PAGE->set_course($course);
2969             }
2970         } else {
2971             // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
2972             $PAGE->set_course($PAGE->course);
2973         }
2974         user_accesstime_log(SITEID);
2975         return;
2977     } else {
2978         // Course login always required.
2979         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2980     }
2983 /**
2984  * Require key login. Function terminates with error if key not found or incorrect.
2985  *
2986  * @uses NO_MOODLE_COOKIES
2987  * @uses PARAM_ALPHANUM
2988  * @param string $script unique script identifier
2989  * @param int $instance optional instance id
2990  * @return int Instance ID
2991  */
2992 function require_user_key_login($script, $instance=null) {
2993     global $DB;
2995     if (!NO_MOODLE_COOKIES) {
2996         print_error('sessioncookiesdisable');
2997     }
2999     // Extra safety.
3000     \core\session\manager::write_close();
3002     $keyvalue = required_param('key', PARAM_ALPHANUM);
3004     if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3005         print_error('invalidkey');
3006     }
3008     if (!empty($key->validuntil) and $key->validuntil < time()) {
3009         print_error('expiredkey');
3010     }
3012     if ($key->iprestriction) {
3013         $remoteaddr = getremoteaddr(null);
3014         if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3015             print_error('ipmismatch');
3016         }
3017     }
3019     if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3020         print_error('invaliduserid');
3021     }
3023     // Emulate normal session.
3024     enrol_check_plugins($user);
3025     \core\session\manager::set_user($user);
3027     // Note we are not using normal login.
3028     if (!defined('USER_KEY_LOGIN')) {
3029         define('USER_KEY_LOGIN', true);
3030     }
3032     // Return instance id - it might be empty.
3033     return $key->instance;
3036 /**
3037  * Creates a new private user access key.
3038  *
3039  * @param string $script unique target identifier
3040  * @param int $userid
3041  * @param int $instance optional instance id
3042  * @param string $iprestriction optional ip restricted access
3043  * @param int $validuntil key valid only until given data
3044  * @return string access key value
3045  */
3046 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3047     global $DB;
3049     $key = new stdClass();
3050     $key->script        = $script;
3051     $key->userid        = $userid;
3052     $key->instance      = $instance;
3053     $key->iprestriction = $iprestriction;
3054     $key->validuntil    = $validuntil;
3055     $key->timecreated   = time();
3057     // Something long and unique.
3058     $key->value         = md5($userid.'_'.time().random_string(40));
3059     while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3060         // Must be unique.
3061         $key->value     = md5($userid.'_'.time().random_string(40));
3062     }
3063     $DB->insert_record('user_private_key', $key);
3064     return $key->value;
3067 /**
3068  * Delete the user's new private user access keys for a particular script.
3069  *
3070  * @param string $script unique target identifier
3071  * @param int $userid
3072  * @return void
3073  */
3074 function delete_user_key($script, $userid) {
3075     global $DB;
3076     $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3079 /**
3080  * Gets a private user access key (and creates one if one doesn't exist).
3081  *
3082  * @param string $script unique target identifier
3083  * @param int $userid
3084  * @param int $instance optional instance id
3085  * @param string $iprestriction optional ip restricted access
3086  * @param int $validuntil key valid only until given date
3087  * @return string access key value
3088  */
3089 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3090     global $DB;
3092     if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3093                                                          'instance' => $instance, 'iprestriction' => $iprestriction,
3094                                                          'validuntil' => $validuntil))) {
3095         return $key->value;
3096     } else {
3097         return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3098     }
3102 /**
3103  * Modify the user table by setting the currently logged in user's last login to now.
3104  *
3105  * @return bool Always returns true
3106  */
3107 function update_user_login_times() {
3108     global $USER, $DB;
3110     if (isguestuser()) {
3111         // Do not update guest access times/ips for performance.
3112         return true;
3113     }
3115     $now = time();
3117     $user = new stdClass();
3118     $user->id = $USER->id;
3120     // Make sure all users that logged in have some firstaccess.
3121     if ($USER->firstaccess == 0) {
3122         $USER->firstaccess = $user->firstaccess = $now;
3123     }
3125     // Store the previous current as lastlogin.
3126     $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3128     $USER->currentlogin = $user->currentlogin = $now;
3130     // Function user_accesstime_log() may not update immediately, better do it here.
3131     $USER->lastaccess = $user->lastaccess = $now;
3132     $USER->lastip = $user->lastip = getremoteaddr();
3134     // Note: do not call user_update_user() here because this is part of the login process,
3135     //       the login event means that these fields were updated.
3136     $DB->update_record('user', $user);
3137     return true;
3140 /**
3141  * Determines if a user has completed setting up their account.
3142  *
3143  * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3144  * @return bool
3145  */
3146 function user_not_fully_set_up($user) {
3147     if (isguestuser($user)) {
3148         return false;
3149     }
3150     return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3153 /**
3154  * Check whether the user has exceeded the bounce threshold
3155  *
3156  * @param stdClass $user A {@link $USER} object
3157  * @return bool true => User has exceeded bounce threshold
3158  */
3159 function over_bounce_threshold($user) {
3160     global $CFG, $DB;
3162     if (empty($CFG->handlebounces)) {
3163         return false;
3164     }
3166     if (empty($user->id)) {
3167         // No real (DB) user, nothing to do here.
3168         return false;
3169     }
3171     // Set sensible defaults.
3172     if (empty($CFG->minbounces)) {
3173         $CFG->minbounces = 10;
3174     }
3175     if (empty($CFG->bounceratio)) {
3176         $CFG->bounceratio = .20;
3177     }
3178     $bouncecount = 0;
3179     $sendcount = 0;
3180     if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3181         $bouncecount = $bounce->value;
3182     }
3183     if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3184         $sendcount = $send->value;
3185     }
3186     return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3189 /**
3190  * Used to increment or reset email sent count
3191  *
3192  * @param stdClass $user object containing an id
3193  * @param bool $reset will reset the count to 0
3194  * @return void
3195  */
3196 function set_send_count($user, $reset=false) {
3197     global $DB;
3199     if (empty($user->id)) {
3200         // No real (DB) user, nothing to do here.
3201         return;
3202     }
3204     if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3205         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3206         $DB->update_record('user_preferences', $pref);
3207     } else if (!empty($reset)) {
3208         // If it's not there and we're resetting, don't bother. Make a new one.
3209         $pref = new stdClass();
3210         $pref->name   = 'email_send_count';
3211         $pref->value  = 1;
3212         $pref->userid = $user->id;
3213         $DB->insert_record('user_preferences', $pref, false);
3214     }
3217 /**
3218  * Increment or reset user's email bounce count
3219  *
3220  * @param stdClass $user object containing an id
3221  * @param bool $reset will reset the count to 0
3222  */
3223 function set_bounce_count($user, $reset=false) {
3224     global $DB;
3226     if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3227         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3228         $DB->update_record('user_preferences', $pref);
3229     } else if (!empty($reset)) {
3230         // If it's not there and we're resetting, don't bother. Make a new one.
3231         $pref = new stdClass();
3232         $pref->name   = 'email_bounce_count';
3233         $pref->value  = 1;
3234         $pref->userid = $user->id;
3235         $DB->insert_record('user_preferences', $pref, false);
3236     }
3239 /**
3240  * Determines if the logged in user is currently moving an activity
3241  *
3242  * @param int $courseid The id of the course being tested
3243  * @return bool
3244  */
3245 function ismoving($courseid) {
3246     global $USER;
3248     if (!empty($USER->activitycopy)) {
3249         return ($USER->activitycopycourse == $courseid);
3250     }
3251     return false;
3254 /**
3255  * Returns a persons full name
3256  *
3257  * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3258  * The result may depend on system settings or language.  'override' will force both names to be used even if system settings
3259  * specify one.
3260  *
3261  * @param stdClass $user A {@link $USER} object to get full name of.
3262  * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3263  * @return string
3264  */
3265 function fullname($user, $override=false) {
3266     global $CFG, $SESSION;
3268     if (!isset($user->firstname) and !isset($user->lastname)) {
3269         return '';
3270     }
3272     // Get all of the name fields.
3273     $allnames = get_all_user_name_fields();
3274     if ($CFG->debugdeveloper) {
3275         foreach ($allnames as $allname) {
3276             if (!property_exists($user, $allname)) {
3277                 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3278                 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3279                 // Message has been sent, no point in sending the message multiple times.
3280                 break;
3281             }
3282         }
3283     }
3285     if (!$override) {
3286         if (!empty($CFG->forcefirstname)) {
3287             $user->firstname = $CFG->forcefirstname;
3288         }
3289         if (!empty($CFG->forcelastname)) {
3290             $user->lastname = $CFG->forcelastname;
3291         }
3292     }
3294     if (!empty($SESSION->fullnamedisplay)) {
3295         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3296     }
3298     $template = null;
3299     // If the fullnamedisplay setting is available, set the template to that.
3300     if (isset($CFG->fullnamedisplay)) {
3301         $template = $CFG->fullnamedisplay;
3302     }
3303     // If the template is empty, or set to language, return the language string.
3304     if ((empty($template) || $template == 'language') && !$override) {
3305         return get_string('fullnamedisplay', null, $user);
3306     }
3308     // Check to see if we are displaying according to the alternative full name format.
3309     if ($override) {
3310         if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3311             // Default to show just the user names according to the fullnamedisplay string.
3312             return get_string('fullnamedisplay', null, $user);
3313         } else {
3314             // If the override is true, then change the template to use the complete name.
3315             $template = $CFG->alternativefullnameformat;
3316         }
3317     }
3319     $requirednames = array();
3320     // With each name, see if it is in the display name template, and add it to the required names array if it is.
3321     foreach ($allnames as $allname) {
3322         if (strpos($template, $allname) !== false) {
3323             $requirednames[] = $allname;
3324         }
3325     }
3327     $displayname = $template;
3328     // Switch in the actual data into the template.
3329     foreach ($requirednames as $altname) {
3330         if (isset($user->$altname)) {
3331             // Using empty() on the below if statement causes breakages.
3332             if ((string)$user->$altname == '') {
3333                 $displayname = str_replace($altname, 'EMPTY', $displayname);
3334             } else {
3335                 $displayname = str_replace($altname, $user->$altname, $displayname);
3336             }
3337         } else {
3338             $displayname = str_replace($altname, 'EMPTY', $displayname);
3339         }
3340     }
3341     // Tidy up any misc. characters (Not perfect, but gets most characters).
3342     // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3343     // katakana and parenthesis.
3344     $patterns = array();
3345     // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3346     // filled in by a user.
3347     // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3348     $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3349     // This regular expression is to remove any double spaces in the display name.
3350     $patterns[] = '/\s{2,}/u';
3351     foreach ($patterns as $pattern) {
3352         $displayname = preg_replace($pattern, ' ', $displayname);
3353     }
3355     // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3356     $displayname = trim($displayname);
3357     if (empty($displayname)) {
3358         // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3359         // people in general feel is a good setting to fall back on.
3360         $displayname = $user->firstname;
3361     }
3362     return $displayname;
3365 /**
3366  * A centralised location for the all name fields. Returns an array / sql string snippet.
3367  *
3368  * @param bool $returnsql True for an sql select field snippet.
3369  * @param string $tableprefix table query prefix to use in front of each field.
3370  * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3371  * @param string $fieldprefix sql field prefix e.g. id AS userid.
3372  * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3373  * @return array|string All name fields.
3374  */
3375 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3376     // This array is provided in this order because when called by fullname() (above) if firstname is before
3377     // firstnamephonetic str_replace() will change the wrong placeholder.
3378     $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3379                             'lastnamephonetic' => 'lastnamephonetic',
3380                             'middlename' => 'middlename',
3381                             'alternatename' => 'alternatename',
3382                             'firstname' => 'firstname',
3383                             'lastname' => 'lastname');
3385     // Let's add a prefix to the array of user name fields if provided.
3386     if ($prefix) {
3387         foreach ($alternatenames as $key => $altname) {
3388             $alternatenames[$key] = $prefix . $altname;
3389         }
3390     }
3392     // If we want the end result to have firstname and lastname at the front / top of the result.
3393     if ($order) {
3394         // Move the last two elements (firstname, lastname) off the array and put them at the top.
3395         for ($i = 0; $i < 2; $i++) {
3396             // Get the last element.
3397             $lastelement = end($alternatenames);
3398             // Remove it from the array.
3399             unset($alternatenames[$lastelement]);
3400             // Put the element back on the top of the array.
3401             $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3402         }
3403     }
3405     // Create an sql field snippet if requested.
3406     if ($returnsql) {
3407         if ($tableprefix) {
3408             if ($fieldprefix) {
3409                 foreach ($alternatenames as $key => $altname) {
3410                     $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3411                 }
3412             } else {
3413                 foreach ($alternatenames as $key => $altname) {
3414                     $alternatenames[$key] = $tableprefix . '.' . $altname;
3415                 }
3416             }
3417         }
3418         $alternatenames = implode(',', $alternatenames);
3419     }
3420     return $alternatenames;
3423 /**
3424  * Reduces lines of duplicated code for getting user name fields.
3425  *
3426  * See also {@link user_picture::unalias()}
3427  *
3428  * @param object $addtoobject Object to add user name fields to.
3429  * @param object $secondobject Object that contains user name field information.
3430  * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3431  * @param array $additionalfields Additional fields to be matched with data in the second object.
3432  * The key can be set to the user table field name.
3433  * @return object User name fields.
3434  */
3435 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3436     $fields = get_all_user_name_fields(false, null, $prefix);
3437     if ($additionalfields) {
3438         // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3439         // the key is a number and then sets the key to the array value.
3440         foreach ($additionalfields as $key => $value) {
3441             if (is_numeric($key)) {
3442                 $additionalfields[$value] = $prefix . $value;
3443                 unset($additionalfields[$key]);
3444             } else {
3445                 $additionalfields[$key] = $prefix . $value;
3446             }
3447         }
3448         $fields = array_merge($fields, $additionalfields);
3449     }
3450     foreach ($fields as $key => $field) {
3451         // Important that we have all of the user name fields present in the object that we are sending back.
3452         $addtoobject->$key = '';
3453         if (isset($secondobject->$field)) {
3454             $addtoobject->$key = $secondobject->$field;
3455         }
3456     }
3457     return $addtoobject;
3460 /**
3461  * Returns an array of values in order of occurance in a provided string.
3462  * The key in the result is the character postion in the string.
3463  *
3464  * @param array $values Values to be found in the string format
3465  * @param string $stringformat The string which may contain values being searched for.
3466  * @return array An array of values in order according to placement in the string format.
3467  */
3468 function order_in_string($values, $stringformat) {
3469     $valuearray = array();
3470     foreach ($values as $value) {
3471         $pattern = "/$value\b/";
3472         // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3473         if (preg_match($pattern, $stringformat)) {
3474             $replacement = "thing";
3475             // Replace the value with something more unique to ensure we get the right position when using strpos().
3476             $newformat = preg_replace($pattern, $replacement, $stringformat);
3477             $position = strpos($newformat, $replacement);
3478             $valuearray[$position] = $value;
3479         }
3480     }
3481     ksort($valuearray);
3482     return $valuearray;
3485 /**
3486  * Checks if current user is shown any extra fields when listing users.
3487  *
3488  * @param object $context Context
3489  * @param array $already Array of fields that we're going to show anyway
3490  *   so don't bother listing them
3491  * @return array Array of field names from user table, not including anything
3492  *   listed in $already
3493  */
3494 function get_extra_user_fields($context, $already = array()) {
3495     global $CFG;
3497     // Only users with permission get the extra fields.
3498     if (!has_capability('moodle/site:viewuseridentity', $context)) {
3499         return array();
3500     }
3502     // Split showuseridentity on comma.
3503     if (empty($CFG->showuseridentity)) {
3504         // Explode gives wrong result with empty string.
3505         $extra = array();
3506     } else {
3507         $extra =  explode(',', $CFG->showuseridentity);
3508     }
3509     $renumber = false;
3510     foreach ($extra as $key => $field) {
3511         if (in_array($field, $already)) {
3512             unset($extra[$key]);
3513             $renumber = true;
3514         }
3515     }
3516     if ($renumber) {
3517         // For consistency, if entries are removed from array, renumber it
3518         // so they are numbered as you would expect.
3519         $extra = array_merge($extra);
3520     }
3521     return $extra;
3524 /**
3525  * If the current user is to be shown extra user fields when listing or
3526  * selecting users, returns a string suitable for including in an SQL select
3527  * clause to retrieve those fields.
3528  *
3529  * @param context $context Context
3530  * @param string $alias Alias of user table, e.g. 'u' (default none)
3531  * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3532  * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3533  * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3534  */
3535 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3536     $fields = get_extra_user_fields($context, $already);
3537     $result = '';
3538     // Add punctuation for alias.
3539     if ($alias !== '') {
3540         $alias .= '.';
3541     }
3542     foreach ($fields as $field) {
3543         $result .= ', ' . $alias . $field;
3544         if ($prefix) {
3545             $result .= ' AS ' . $prefix . $field;
3546         }
3547     }
3548     return $result;
3551 /**
3552  * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3553  * @param string $field Field name, e.g. 'phone1'
3554  * @return string Text description taken from language file, e.g. 'Phone number'
3555  */
3556 function get_user_field_name($field) {
3557     // Some fields have language strings which are not the same as field name.
3558     switch ($field) {
3559         case 'url' : {
3560             return get_string('webpage');
3561         }
3562         case 'icq' : {
3563             return get_string('icqnumber');
3564         }
3565         case 'skype' : {
3566             return get_string('skypeid');
3567         }
3568         case 'aim' : {
3569             return get_string('aimid');
3570         }
3571         case 'yahoo' : {
3572             return get_string('yahooid');
3573         }
3574         case 'msn' : {
3575             return get_string('msnid');
3576         }
3577     }
3578     // Otherwise just use the same lang string.
3579     return get_string($field);
3582 /**
3583  * Returns whether a given authentication plugin exists.
3584  *
3585  * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3586  * @return boolean Whether the plugin is available.
3587  */
3588 function exists_auth_plugin($auth) {
3589     global $CFG;
3591     if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3592         return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3593     }
3594     return false;
3597 /**
3598  * Checks if a given plugin is in the list of enabled authentication plugins.
3599  *
3600  * @param string $auth Authentication plugin.
3601  * @return boolean Whether the plugin is enabled.
3602  */
3603 function is_enabled_auth($auth) {
3604     if (empty($auth)) {
3605         return false;
3606     }
3608     $enabled = get_enabled_auth_plugins();
3610     return in_array($auth, $enabled);
3613 /**
3614  * Returns an authentication plugin instance.
3615  *
3616  * @param string $auth name of authentication plugin
3617  * @return auth_plugin_base An instance of the required authentication plugin.
3618  */
3619 function get_auth_plugin($auth) {
3620     global $CFG;
3622     // Check the plugin exists first.
3623     if (! exists_auth_plugin($auth)) {
3624         print_error('authpluginnotfound', 'debug', '', $auth);
3625     }
3627     // Return auth plugin instance.
3628     require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3629     $class = "auth_plugin_$auth";
3630     return new $class;
3633 /**
3634  * Returns array of active auth plugins.
3635  *
3636  * @param bool $fix fix $CFG->auth if needed
3637  * @return array
3638  */
3639 function get_enabled_auth_plugins($fix=false) {
3640     global $CFG;
3642     $default = array('manual', 'nologin');
3644     if (empty($CFG->auth)) {
3645         $auths = array();
3646     } else {
3647         $auths = explode(',', $CFG->auth);
3648     }
3650     if ($fix) {
3651         $auths = array_unique($auths);
3652         foreach ($auths as $k => $authname) {
3653             if (!exists_auth_plugin($authname) or in_array($authname, $default)) {