Merge branch 'MDL-58499-master' of git://github.com/barbararamiro/moodle
[moodle.git] / lib / moodlelib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * moodlelib.php - Moodle main library
19  *
20  * Main library file of miscellaneous general-purpose Moodle functions.
21  * Other main libraries:
22  *  - weblib.php      - functions that produce web output
23  *  - datalib.php     - functions that access the database
24  *
25  * @package    core
26  * @subpackage lib
27  * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
28  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29  */
31 defined('MOODLE_INTERNAL') || die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
36 /**
37  * Time constant - the number of seconds in a year
38  */
39 define('YEARSECS', 31536000);
41 /**
42  * Time constant - the number of seconds in a week
43  */
44 define('WEEKSECS', 604800);
46 /**
47  * Time constant - the number of seconds in a day
48  */
49 define('DAYSECS', 86400);
51 /**
52  * Time constant - the number of seconds in an hour
53  */
54 define('HOURSECS', 3600);
56 /**
57  * Time constant - the number of seconds in a minute
58  */
59 define('MINSECS', 60);
61 /**
62  * Time constant - the number of minutes in a day
63  */
64 define('DAYMINS', 1440);
66 /**
67  * Time constant - the number of minutes in an hour
68  */
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
74 /**
75  * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
76  */
77 define('PARAM_ALPHA',    'alpha');
79 /**
80  * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81  * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
82  */
83 define('PARAM_ALPHAEXT', 'alphaext');
85 /**
86  * PARAM_ALPHANUM - expected numbers and letters only.
87  */
88 define('PARAM_ALPHANUM', 'alphanum');
90 /**
91  * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
92  */
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
95 /**
96  * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
97  */
98 define('PARAM_AUTH',  'auth');
100 /**
101  * PARAM_BASE64 - Base 64 encoded format
102  */
103 define('PARAM_BASE64',   'base64');
105 /**
106  * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
107  */
108 define('PARAM_BOOL',     'bool');
110 /**
111  * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112  * checked against the list of capabilities in the database.
113  */
114 define('PARAM_CAPABILITY',   'capability');
116 /**
117  * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118  * to use this. The normal mode of operation is to use PARAM_RAW when 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', '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 /**
524  * Email from header to never include via information.
525  */
526 define('EMAIL_VIA_NEVER', 0);
528 /**
529  * Email from header to always include via information.
530  */
531 define('EMAIL_VIA_ALWAYS', 1);
533 /**
534  * Email from header to only include via information if the address is no-reply.
535  */
536 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
538 // PARAMETER HANDLING.
540 /**
541  * Returns a particular value for the named variable, taken from
542  * POST or GET.  If the parameter doesn't exist then an error is
543  * thrown because we require this variable.
544  *
545  * This function should be used to initialise all required values
546  * in a script that are based on parameters.  Usually it will be
547  * used like this:
548  *    $id = required_param('id', PARAM_INT);
549  *
550  * Please note the $type parameter is now required and the value can not be array.
551  *
552  * @param string $parname the name of the page parameter we want
553  * @param string $type expected type of parameter
554  * @return mixed
555  * @throws coding_exception
556  */
557 function required_param($parname, $type) {
558     if (func_num_args() != 2 or empty($parname) or empty($type)) {
559         throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
560     }
561     // POST has precedence.
562     if (isset($_POST[$parname])) {
563         $param = $_POST[$parname];
564     } else if (isset($_GET[$parname])) {
565         $param = $_GET[$parname];
566     } else {
567         print_error('missingparam', '', '', $parname);
568     }
570     if (is_array($param)) {
571         debugging('Invalid array parameter detected in required_param(): '.$parname);
572         // TODO: switch to fatal error in Moodle 2.3.
573         return required_param_array($parname, $type);
574     }
576     return clean_param($param, $type);
579 /**
580  * Returns a particular array value for the named variable, taken from
581  * POST or GET.  If the parameter doesn't exist then an error is
582  * thrown because we require this variable.
583  *
584  * This function should be used to initialise all required values
585  * in a script that are based on parameters.  Usually it will be
586  * used like this:
587  *    $ids = required_param_array('ids', PARAM_INT);
588  *
589  *  Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
590  *
591  * @param string $parname the name of the page parameter we want
592  * @param string $type expected type of parameter
593  * @return array
594  * @throws coding_exception
595  */
596 function required_param_array($parname, $type) {
597     if (func_num_args() != 2 or empty($parname) or empty($type)) {
598         throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
599     }
600     // POST has precedence.
601     if (isset($_POST[$parname])) {
602         $param = $_POST[$parname];
603     } else if (isset($_GET[$parname])) {
604         $param = $_GET[$parname];
605     } else {
606         print_error('missingparam', '', '', $parname);
607     }
608     if (!is_array($param)) {
609         print_error('missingparam', '', '', $parname);
610     }
612     $result = array();
613     foreach ($param as $key => $value) {
614         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
615             debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
616             continue;
617         }
618         $result[$key] = clean_param($value, $type);
619     }
621     return $result;
624 /**
625  * Returns a particular value for the named variable, taken from
626  * POST or GET, otherwise returning a given default.
627  *
628  * This function should be used to initialise all optional values
629  * in a script that are based on parameters.  Usually it will be
630  * used like this:
631  *    $name = optional_param('name', 'Fred', PARAM_TEXT);
632  *
633  * Please note the $type parameter is now required and the value can not be array.
634  *
635  * @param string $parname the name of the page parameter we want
636  * @param mixed  $default the default value to return if nothing is found
637  * @param string $type expected type of parameter
638  * @return mixed
639  * @throws coding_exception
640  */
641 function optional_param($parname, $default, $type) {
642     if (func_num_args() != 3 or empty($parname) or empty($type)) {
643         throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
644     }
646     // POST has precedence.
647     if (isset($_POST[$parname])) {
648         $param = $_POST[$parname];
649     } else if (isset($_GET[$parname])) {
650         $param = $_GET[$parname];
651     } else {
652         return $default;
653     }
655     if (is_array($param)) {
656         debugging('Invalid array parameter detected in required_param(): '.$parname);
657         // TODO: switch to $default in Moodle 2.3.
658         return optional_param_array($parname, $default, $type);
659     }
661     return clean_param($param, $type);
664 /**
665  * Returns a particular array value for the named variable, taken from
666  * POST or GET, otherwise returning a given default.
667  *
668  * This function should be used to initialise all optional values
669  * in a script that are based on parameters.  Usually it will be
670  * used like this:
671  *    $ids = optional_param('id', array(), PARAM_INT);
672  *
673  * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
674  *
675  * @param string $parname the name of the page parameter we want
676  * @param mixed $default the default value to return if nothing is found
677  * @param string $type expected type of parameter
678  * @return array
679  * @throws coding_exception
680  */
681 function optional_param_array($parname, $default, $type) {
682     if (func_num_args() != 3 or empty($parname) or empty($type)) {
683         throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
684     }
686     // POST has precedence.
687     if (isset($_POST[$parname])) {
688         $param = $_POST[$parname];
689     } else if (isset($_GET[$parname])) {
690         $param = $_GET[$parname];
691     } else {
692         return $default;
693     }
694     if (!is_array($param)) {
695         debugging('optional_param_array() expects array parameters only: '.$parname);
696         return $default;
697     }
699     $result = array();
700     foreach ($param as $key => $value) {
701         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
702             debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
703             continue;
704         }
705         $result[$key] = clean_param($value, $type);
706     }
708     return $result;
711 /**
712  * Strict validation of parameter values, the values are only converted
713  * to requested PHP type. Internally it is using clean_param, the values
714  * before and after cleaning must be equal - otherwise
715  * an invalid_parameter_exception is thrown.
716  * Objects and classes are not accepted.
717  *
718  * @param mixed $param
719  * @param string $type PARAM_ constant
720  * @param bool $allownull are nulls valid value?
721  * @param string $debuginfo optional debug information
722  * @return mixed the $param value converted to PHP type
723  * @throws invalid_parameter_exception if $param is not of given type
724  */
725 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
726     if (is_null($param)) {
727         if ($allownull == NULL_ALLOWED) {
728             return null;
729         } else {
730             throw new invalid_parameter_exception($debuginfo);
731         }
732     }
733     if (is_array($param) or is_object($param)) {
734         throw new invalid_parameter_exception($debuginfo);
735     }
737     $cleaned = clean_param($param, $type);
739     if ($type == PARAM_FLOAT) {
740         // Do not detect precision loss here.
741         if (is_float($param) or is_int($param)) {
742             // These always fit.
743         } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
744             throw new invalid_parameter_exception($debuginfo);
745         }
746     } else if ((string)$param !== (string)$cleaned) {
747         // Conversion to string is usually lossless.
748         throw new invalid_parameter_exception($debuginfo);
749     }
751     return $cleaned;
754 /**
755  * Makes sure array contains only the allowed types, this function does not validate array key names!
756  *
757  * <code>
758  * $options = clean_param($options, PARAM_INT);
759  * </code>
760  *
761  * @param array $param the variable array we are cleaning
762  * @param string $type expected format of param after cleaning.
763  * @param bool $recursive clean recursive arrays
764  * @return array
765  * @throws coding_exception
766  */
767 function clean_param_array(array $param = null, $type, $recursive = false) {
768     // Convert null to empty array.
769     $param = (array)$param;
770     foreach ($param as $key => $value) {
771         if (is_array($value)) {
772             if ($recursive) {
773                 $param[$key] = clean_param_array($value, $type, true);
774             } else {
775                 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
776             }
777         } else {
778             $param[$key] = clean_param($value, $type);
779         }
780     }
781     return $param;
784 /**
785  * Used by {@link optional_param()} and {@link required_param()} to
786  * clean the variables and/or cast to specific types, based on
787  * an options field.
788  * <code>
789  * $course->format = clean_param($course->format, PARAM_ALPHA);
790  * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
791  * </code>
792  *
793  * @param mixed $param the variable we are cleaning
794  * @param string $type expected format of param after cleaning.
795  * @return mixed
796  * @throws coding_exception
797  */
798 function clean_param($param, $type) {
799     global $CFG;
801     if (is_array($param)) {
802         throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
803     } else if (is_object($param)) {
804         if (method_exists($param, '__toString')) {
805             $param = $param->__toString();
806         } else {
807             throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
808         }
809     }
811     switch ($type) {
812         case PARAM_RAW:
813             // No cleaning at all.
814             $param = fix_utf8($param);
815             return $param;
817         case PARAM_RAW_TRIMMED:
818             // No cleaning, but strip leading and trailing whitespace.
819             $param = fix_utf8($param);
820             return trim($param);
822         case PARAM_CLEAN:
823             // General HTML cleaning, try to use more specific type if possible this is deprecated!
824             // Please use more specific type instead.
825             if (is_numeric($param)) {
826                 return $param;
827             }
828             $param = fix_utf8($param);
829             // Sweep for scripts, etc.
830             return clean_text($param);
832         case PARAM_CLEANHTML:
833             // Clean html fragment.
834             $param = fix_utf8($param);
835             // Sweep for scripts, etc.
836             $param = clean_text($param, FORMAT_HTML);
837             return trim($param);
839         case PARAM_INT:
840             // Convert to integer.
841             return (int)$param;
843         case PARAM_FLOAT:
844             // Convert to float.
845             return (float)$param;
847         case PARAM_ALPHA:
848             // Remove everything not `a-z`.
849             return preg_replace('/[^a-zA-Z]/i', '', $param);
851         case PARAM_ALPHAEXT:
852             // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
853             return preg_replace('/[^a-zA-Z_-]/i', '', $param);
855         case PARAM_ALPHANUM:
856             // Remove everything not `a-zA-Z0-9`.
857             return preg_replace('/[^A-Za-z0-9]/i', '', $param);
859         case PARAM_ALPHANUMEXT:
860             // Remove everything not `a-zA-Z0-9_-`.
861             return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
863         case PARAM_SEQUENCE:
864             // Remove everything not `0-9,`.
865             return preg_replace('/[^0-9,]/i', '', $param);
867         case PARAM_BOOL:
868             // Convert to 1 or 0.
869             $tempstr = strtolower($param);
870             if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
871                 $param = 1;
872             } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
873                 $param = 0;
874             } else {
875                 $param = empty($param) ? 0 : 1;
876             }
877             return $param;
879         case PARAM_NOTAGS:
880             // Strip all tags.
881             $param = fix_utf8($param);
882             return strip_tags($param);
884         case PARAM_TEXT:
885             // Leave only tags needed for multilang.
886             $param = fix_utf8($param);
887             // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
888             // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
889             do {
890                 if (strpos($param, '</lang>') !== false) {
891                     // Old and future mutilang syntax.
892                     $param = strip_tags($param, '<lang>');
893                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
894                         break;
895                     }
896                     $open = false;
897                     foreach ($matches[0] as $match) {
898                         if ($match === '</lang>') {
899                             if ($open) {
900                                 $open = false;
901                                 continue;
902                             } else {
903                                 break 2;
904                             }
905                         }
906                         if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
907                             break 2;
908                         } else {
909                             $open = true;
910                         }
911                     }
912                     if ($open) {
913                         break;
914                     }
915                     return $param;
917                 } else if (strpos($param, '</span>') !== false) {
918                     // Current problematic multilang syntax.
919                     $param = strip_tags($param, '<span>');
920                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
921                         break;
922                     }
923                     $open = false;
924                     foreach ($matches[0] as $match) {
925                         if ($match === '</span>') {
926                             if ($open) {
927                                 $open = false;
928                                 continue;
929                             } else {
930                                 break 2;
931                             }
932                         }
933                         if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
934                             break 2;
935                         } else {
936                             $open = true;
937                         }
938                     }
939                     if ($open) {
940                         break;
941                     }
942                     return $param;
943                 }
944             } while (false);
945             // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
946             return strip_tags($param);
948         case PARAM_COMPONENT:
949             // We do not want any guessing here, either the name is correct or not
950             // please note only normalised component names are accepted.
951             if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
952                 return '';
953             }
954             if (strpos($param, '__') !== false) {
955                 return '';
956             }
957             if (strpos($param, 'mod_') === 0) {
958                 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
959                 if (substr_count($param, '_') != 1) {
960                     return '';
961                 }
962             }
963             return $param;
965         case PARAM_PLUGIN:
966         case PARAM_AREA:
967             // We do not want any guessing here, either the name is correct or not.
968             if (!is_valid_plugin_name($param)) {
969                 return '';
970             }
971             return $param;
973         case PARAM_SAFEDIR:
974             // Remove everything not a-zA-Z0-9_- .
975             return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
977         case PARAM_SAFEPATH:
978             // Remove everything not a-zA-Z0-9/_- .
979             return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
981         case PARAM_FILE:
982             // Strip all suspicious characters from filename.
983             $param = fix_utf8($param);
984             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
985             if ($param === '.' || $param === '..') {
986                 $param = '';
987             }
988             return $param;
990         case PARAM_PATH:
991             // Strip all suspicious characters from file path.
992             $param = fix_utf8($param);
993             $param = str_replace('\\', '/', $param);
995             // Explode the path and clean each element using the PARAM_FILE rules.
996             $breadcrumb = explode('/', $param);
997             foreach ($breadcrumb as $key => $crumb) {
998                 if ($crumb === '.' && $key === 0) {
999                     // Special condition to allow for relative current path such as ./currentdirfile.txt.
1000                 } else {
1001                     $crumb = clean_param($crumb, PARAM_FILE);
1002                 }
1003                 $breadcrumb[$key] = $crumb;
1004             }
1005             $param = implode('/', $breadcrumb);
1007             // Remove multiple current path (./././) and multiple slashes (///).
1008             $param = preg_replace('~//+~', '/', $param);
1009             $param = preg_replace('~/(\./)+~', '/', $param);
1010             return $param;
1012         case PARAM_HOST:
1013             // Allow FQDN or IPv4 dotted quad.
1014             $param = preg_replace('/[^\.\d\w-]/', '', $param );
1015             // Match ipv4 dotted quad.
1016             if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1017                 // Confirm values are ok.
1018                 if ( $match[0] > 255
1019                      || $match[1] > 255
1020                      || $match[3] > 255
1021                      || $match[4] > 255 ) {
1022                     // Hmmm, what kind of dotted quad is this?
1023                     $param = '';
1024                 }
1025             } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1026                        && !preg_match('/^[\.-]/',  $param) // No leading dots/hyphens.
1027                        && !preg_match('/[\.-]$/',  $param) // No trailing dots/hyphens.
1028                        ) {
1029                 // All is ok - $param is respected.
1030             } else {
1031                 // All is not ok...
1032                 $param='';
1033             }
1034             return $param;
1036         case PARAM_URL:          // Allow safe ftp, http, mailto urls.
1037             $param = fix_utf8($param);
1038             include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1039             if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1040                 // All is ok, param is respected.
1041             } else {
1042                 // Not really ok.
1043                 $param ='';
1044             }
1045             return $param;
1047         case PARAM_LOCALURL:
1048             // Allow http absolute, root relative and relative URLs within wwwroot.
1049             $param = clean_param($param, PARAM_URL);
1050             if (!empty($param)) {
1052                 // Simulate the HTTPS version of the site.
1053                 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1055                 if ($param === $CFG->wwwroot) {
1056                     // Exact match;
1057                 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1058                     // Exact match;
1059                 } else if (preg_match(':^/:', $param)) {
1060                     // Root-relative, ok!
1061                 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1062                     // Absolute, and matches our wwwroot.
1063                 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1064                     // Absolute, and matches our httpswwwroot.
1065                 } else {
1066                     // Relative - let's make sure there are no tricks.
1067                     if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1068                         // Looks ok.
1069                     } else {
1070                         $param = '';
1071                     }
1072                 }
1073             }
1074             return $param;
1076         case PARAM_PEM:
1077             $param = trim($param);
1078             // PEM formatted strings may contain letters/numbers and the symbols:
1079             //   forward slash: /
1080             //   plus sign:     +
1081             //   equal sign:    =
1082             //   , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1083             if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1084                 list($wholething, $body) = $matches;
1085                 unset($wholething, $matches);
1086                 $b64 = clean_param($body, PARAM_BASE64);
1087                 if (!empty($b64)) {
1088                     return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1089                 } else {
1090                     return '';
1091                 }
1092             }
1093             return '';
1095         case PARAM_BASE64:
1096             if (!empty($param)) {
1097                 // PEM formatted strings may contain letters/numbers and the symbols
1098                 //   forward slash: /
1099                 //   plus sign:     +
1100                 //   equal sign:    =.
1101                 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1102                     return '';
1103                 }
1104                 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1105                 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1106                 // than (or equal to) 64 characters long.
1107                 for ($i=0, $j=count($lines); $i < $j; $i++) {
1108                     if ($i + 1 == $j) {
1109                         if (64 < strlen($lines[$i])) {
1110                             return '';
1111                         }
1112                         continue;
1113                     }
1115                     if (64 != strlen($lines[$i])) {
1116                         return '';
1117                     }
1118                 }
1119                 return implode("\n", $lines);
1120             } else {
1121                 return '';
1122             }
1124         case PARAM_TAG:
1125             $param = fix_utf8($param);
1126             // Please note it is not safe to use the tag name directly anywhere,
1127             // it must be processed with s(), urlencode() before embedding anywhere.
1128             // Remove some nasties.
1129             $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1130             // Convert many whitespace chars into one.
1131             $param = preg_replace('/\s+/u', ' ', $param);
1132             $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1133             return $param;
1135         case PARAM_TAGLIST:
1136             $param = fix_utf8($param);
1137             $tags = explode(',', $param);
1138             $result = array();
1139             foreach ($tags as $tag) {
1140                 $res = clean_param($tag, PARAM_TAG);
1141                 if ($res !== '') {
1142                     $result[] = $res;
1143                 }
1144             }
1145             if ($result) {
1146                 return implode(',', $result);
1147             } else {
1148                 return '';
1149             }
1151         case PARAM_CAPABILITY:
1152             if (get_capability_info($param)) {
1153                 return $param;
1154             } else {
1155                 return '';
1156             }
1158         case PARAM_PERMISSION:
1159             $param = (int)$param;
1160             if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1161                 return $param;
1162             } else {
1163                 return CAP_INHERIT;
1164             }
1166         case PARAM_AUTH:
1167             $param = clean_param($param, PARAM_PLUGIN);
1168             if (empty($param)) {
1169                 return '';
1170             } else if (exists_auth_plugin($param)) {
1171                 return $param;
1172             } else {
1173                 return '';
1174             }
1176         case PARAM_LANG:
1177             $param = clean_param($param, PARAM_SAFEDIR);
1178             if (get_string_manager()->translation_exists($param)) {
1179                 return $param;
1180             } else {
1181                 // Specified language is not installed or param malformed.
1182                 return '';
1183             }
1185         case PARAM_THEME:
1186             $param = clean_param($param, PARAM_PLUGIN);
1187             if (empty($param)) {
1188                 return '';
1189             } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1190                 return $param;
1191             } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1192                 return $param;
1193             } else {
1194                 // Specified theme is not installed.
1195                 return '';
1196             }
1198         case PARAM_USERNAME:
1199             $param = fix_utf8($param);
1200             $param = trim($param);
1201             // Convert uppercase to lowercase MDL-16919.
1202             $param = core_text::strtolower($param);
1203             if (empty($CFG->extendedusernamechars)) {
1204                 $param = str_replace(" " , "", $param);
1205                 // Regular expression, eliminate all chars EXCEPT:
1206                 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1207                 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1208             }
1209             return $param;
1211         case PARAM_EMAIL:
1212             $param = fix_utf8($param);
1213             if (validate_email($param)) {
1214                 return $param;
1215             } else {
1216                 return '';
1217             }
1219         case PARAM_STRINGID:
1220             if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1221                 return $param;
1222             } else {
1223                 return '';
1224             }
1226         case PARAM_TIMEZONE:
1227             // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1228             $param = fix_utf8($param);
1229             $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1230             if (preg_match($timezonepattern, $param)) {
1231                 return $param;
1232             } else {
1233                 return '';
1234             }
1236         default:
1237             // Doh! throw error, switched parameters in optional_param or another serious problem.
1238             print_error("unknownparamtype", '', '', $type);
1239     }
1242 /**
1243  * Whether the PARAM_* type is compatible in RTL.
1244  *
1245  * Being compatible with RTL means that the data they contain can flow
1246  * from right-to-left or left-to-right without compromising the user experience.
1247  *
1248  * Take URLs for example, they are not RTL compatible as they should always
1249  * flow from the left to the right. This also applies to numbers, email addresses,
1250  * configuration snippets, base64 strings, etc...
1251  *
1252  * This function tries to best guess which parameters can contain localised strings.
1253  *
1254  * @param string $paramtype Constant PARAM_*.
1255  * @return bool
1256  */
1257 function is_rtl_compatible($paramtype) {
1258     return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1261 /**
1262  * Makes sure the data is using valid utf8, invalid characters are discarded.
1263  *
1264  * Note: this function is not intended for full objects with methods and private properties.
1265  *
1266  * @param mixed $value
1267  * @return mixed with proper utf-8 encoding
1268  */
1269 function fix_utf8($value) {
1270     if (is_null($value) or $value === '') {
1271         return $value;
1273     } else if (is_string($value)) {
1274         if ((string)(int)$value === $value) {
1275             // Shortcut.
1276             return $value;
1277         }
1278         // No null bytes expected in our data, so let's remove it.
1279         $value = str_replace("\0", '', $value);
1281         // Note: this duplicates min_fix_utf8() intentionally.
1282         static $buggyiconv = null;
1283         if ($buggyiconv === null) {
1284             $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1285         }
1287         if ($buggyiconv) {
1288             if (function_exists('mb_convert_encoding')) {
1289                 $subst = mb_substitute_character();
1290                 mb_substitute_character('');
1291                 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1292                 mb_substitute_character($subst);
1294             } else {
1295                 // Warn admins on admin/index.php page.
1296                 $result = $value;
1297             }
1299         } else {
1300             $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1301         }
1303         return $result;
1305     } else if (is_array($value)) {
1306         foreach ($value as $k => $v) {
1307             $value[$k] = fix_utf8($v);
1308         }
1309         return $value;
1311     } else if (is_object($value)) {
1312         // Do not modify original.
1313         $value = clone($value);
1314         foreach ($value as $k => $v) {
1315             $value->$k = fix_utf8($v);
1316         }
1317         return $value;
1319     } else {
1320         // This is some other type, no utf-8 here.
1321         return $value;
1322     }
1325 /**
1326  * Return true if given value is integer or string with integer value
1327  *
1328  * @param mixed $value String or Int
1329  * @return bool true if number, false if not
1330  */
1331 function is_number($value) {
1332     if (is_int($value)) {
1333         return true;
1334     } else if (is_string($value)) {
1335         return ((string)(int)$value) === $value;
1336     } else {
1337         return false;
1338     }
1341 /**
1342  * Returns host part from url.
1343  *
1344  * @param string $url full url
1345  * @return string host, null if not found
1346  */
1347 function get_host_from_url($url) {
1348     preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1349     if ($matches) {
1350         return $matches[1];
1351     }
1352     return null;
1355 /**
1356  * Tests whether anything was returned by text editor
1357  *
1358  * This function is useful for testing whether something you got back from
1359  * the HTML editor actually contains anything. Sometimes the HTML editor
1360  * appear to be empty, but actually you get back a <br> tag or something.
1361  *
1362  * @param string $string a string containing HTML.
1363  * @return boolean does the string contain any actual content - that is text,
1364  * images, objects, etc.
1365  */
1366 function html_is_blank($string) {
1367     return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1370 /**
1371  * Set a key in global configuration
1372  *
1373  * Set a key/value pair in both this session's {@link $CFG} global variable
1374  * and in the 'config' database table for future sessions.
1375  *
1376  * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1377  * In that case it doesn't affect $CFG.
1378  *
1379  * A NULL value will delete the entry.
1380  *
1381  * NOTE: this function is called from lib/db/upgrade.php
1382  *
1383  * @param string $name the key to set
1384  * @param string $value the value to set (without magic quotes)
1385  * @param string $plugin (optional) the plugin scope, default null
1386  * @return bool true or exception
1387  */
1388 function set_config($name, $value, $plugin=null) {
1389     global $CFG, $DB;
1391     if (empty($plugin)) {
1392         if (!array_key_exists($name, $CFG->config_php_settings)) {
1393             // So it's defined for this invocation at least.
1394             if (is_null($value)) {
1395                 unset($CFG->$name);
1396             } else {
1397                 // Settings from db are always strings.
1398                 $CFG->$name = (string)$value;
1399             }
1400         }
1402         if ($DB->get_field('config', 'name', array('name' => $name))) {
1403             if ($value === null) {
1404                 $DB->delete_records('config', array('name' => $name));
1405             } else {
1406                 $DB->set_field('config', 'value', $value, array('name' => $name));
1407             }
1408         } else {
1409             if ($value !== null) {
1410                 $config = new stdClass();
1411                 $config->name  = $name;
1412                 $config->value = $value;
1413                 $DB->insert_record('config', $config, false);
1414             }
1415         }
1416         if ($name === 'siteidentifier') {
1417             cache_helper::update_site_identifier($value);
1418         }
1419         cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1420     } else {
1421         // Plugin scope.
1422         if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1423             if ($value===null) {
1424                 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1425             } else {
1426                 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1427             }
1428         } else {
1429             if ($value !== null) {
1430                 $config = new stdClass();
1431                 $config->plugin = $plugin;
1432                 $config->name   = $name;
1433                 $config->value  = $value;
1434                 $DB->insert_record('config_plugins', $config, false);
1435             }
1436         }
1437         cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1438     }
1440     return true;
1443 /**
1444  * Get configuration values from the global config table
1445  * or the config_plugins table.
1446  *
1447  * If called with one parameter, it will load all the config
1448  * variables for one plugin, and return them as an object.
1449  *
1450  * If called with 2 parameters it will return a string single
1451  * value or false if the value is not found.
1452  *
1453  * NOTE: this function is called from lib/db/upgrade.php
1454  *
1455  * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1456  *     that we need only fetch it once per request.
1457  * @param string $plugin full component name
1458  * @param string $name default null
1459  * @return mixed hash-like object or single value, return false no config found
1460  * @throws dml_exception
1461  */
1462 function get_config($plugin, $name = null) {
1463     global $CFG, $DB;
1465     static $siteidentifier = null;
1467     if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1468         $forced =& $CFG->config_php_settings;
1469         $iscore = true;
1470         $plugin = 'core';
1471     } else {
1472         if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1473             $forced =& $CFG->forced_plugin_settings[$plugin];
1474         } else {
1475             $forced = array();
1476         }
1477         $iscore = false;
1478     }
1480     if ($siteidentifier === null) {
1481         try {
1482             // This may fail during installation.
1483             // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1484             // install the database.
1485             $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1486         } catch (dml_exception $ex) {
1487             // Set siteidentifier to false. We don't want to trip this continually.
1488             $siteidentifier = false;
1489             throw $ex;
1490         }
1491     }
1493     if (!empty($name)) {
1494         if (array_key_exists($name, $forced)) {
1495             return (string)$forced[$name];
1496         } else if ($name === 'siteidentifier' && $plugin == 'core') {
1497             return $siteidentifier;
1498         }
1499     }
1501     $cache = cache::make('core', 'config');
1502     $result = $cache->get($plugin);
1503     if ($result === false) {
1504         // The user is after a recordset.
1505         if (!$iscore) {
1506             $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1507         } else {
1508             // This part is not really used any more, but anyway...
1509             $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1510         }
1511         $cache->set($plugin, $result);
1512     }
1514     if (!empty($name)) {
1515         if (array_key_exists($name, $result)) {
1516             return $result[$name];
1517         }
1518         return false;
1519     }
1521     if ($plugin === 'core') {
1522         $result['siteidentifier'] = $siteidentifier;
1523     }
1525     foreach ($forced as $key => $value) {
1526         if (is_null($value) or is_array($value) or is_object($value)) {
1527             // We do not want any extra mess here, just real settings that could be saved in db.
1528             unset($result[$key]);
1529         } else {
1530             // Convert to string as if it went through the DB.
1531             $result[$key] = (string)$value;
1532         }
1533     }
1535     return (object)$result;
1538 /**
1539  * Removes a key from global configuration.
1540  *
1541  * NOTE: this function is called from lib/db/upgrade.php
1542  *
1543  * @param string $name the key to set
1544  * @param string $plugin (optional) the plugin scope
1545  * @return boolean whether the operation succeeded.
1546  */
1547 function unset_config($name, $plugin=null) {
1548     global $CFG, $DB;
1550     if (empty($plugin)) {
1551         unset($CFG->$name);
1552         $DB->delete_records('config', array('name' => $name));
1553         cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1554     } else {
1555         $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1556         cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1557     }
1559     return true;
1562 /**
1563  * Remove all the config variables for a given plugin.
1564  *
1565  * NOTE: this function is called from lib/db/upgrade.php
1566  *
1567  * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1568  * @return boolean whether the operation succeeded.
1569  */
1570 function unset_all_config_for_plugin($plugin) {
1571     global $DB;
1572     // Delete from the obvious config_plugins first.
1573     $DB->delete_records('config_plugins', array('plugin' => $plugin));
1574     // Next delete any suspect settings from config.
1575     $like = $DB->sql_like('name', '?', true, true, false, '|');
1576     $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1577     $DB->delete_records_select('config', $like, $params);
1578     // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1579     cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1581     return true;
1584 /**
1585  * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1586  *
1587  * All users are verified if they still have the necessary capability.
1588  *
1589  * @param string $value the value of the config setting.
1590  * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1591  * @param bool $includeadmins include administrators.
1592  * @return array of user objects.
1593  */
1594 function get_users_from_config($value, $capability, $includeadmins = true) {
1595     if (empty($value) or $value === '$@NONE@$') {
1596         return array();
1597     }
1599     // We have to make sure that users still have the necessary capability,
1600     // it should be faster to fetch them all first and then test if they are present
1601     // instead of validating them one-by-one.
1602     $users = get_users_by_capability(context_system::instance(), $capability);
1603     if ($includeadmins) {
1604         $admins = get_admins();
1605         foreach ($admins as $admin) {
1606             $users[$admin->id] = $admin;
1607         }
1608     }
1610     if ($value === '$@ALL@$') {
1611         return $users;
1612     }
1614     $result = array(); // Result in correct order.
1615     $allowed = explode(',', $value);
1616     foreach ($allowed as $uid) {
1617         if (isset($users[$uid])) {
1618             $user = $users[$uid];
1619             $result[$user->id] = $user;
1620         }
1621     }
1623     return $result;
1627 /**
1628  * Invalidates browser caches and cached data in temp.
1629  *
1630  * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1631  * {@link phpunit_util::reset_dataroot()}
1632  *
1633  * @return void
1634  */
1635 function purge_all_caches() {
1636     global $CFG, $DB;
1638     reset_text_filters_cache();
1639     js_reset_all_caches();
1640     theme_reset_all_caches();
1641     get_string_manager()->reset_caches();
1642     core_text::reset_caches();
1643     if (class_exists('core_plugin_manager')) {
1644         core_plugin_manager::reset_caches();
1645     }
1647     // Bump up cacherev field for all courses.
1648     try {
1649         increment_revision_number('course', 'cacherev', '');
1650     } catch (moodle_exception $e) {
1651         // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1652     }
1654     $DB->reset_caches();
1655     cache_helper::purge_all();
1657     // Purge all other caches: rss, simplepie, etc.
1658     clearstatcache();
1659     remove_dir($CFG->cachedir.'', true);
1661     // Make sure cache dir is writable, throws exception if not.
1662     make_cache_directory('');
1664     // This is the only place where we purge local caches, we are only adding files there.
1665     // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1666     remove_dir($CFG->localcachedir, true);
1667     set_config('localcachedirpurged', time());
1668     make_localcache_directory('', true);
1669     \core\task\manager::clear_static_caches();
1672 /**
1673  * Get volatile flags
1674  *
1675  * @param string $type
1676  * @param int $changedsince default null
1677  * @return array records array
1678  */
1679 function get_cache_flags($type, $changedsince = null) {
1680     global $DB;
1682     $params = array('type' => $type, 'expiry' => time());
1683     $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1684     if ($changedsince !== null) {
1685         $params['changedsince'] = $changedsince;
1686         $sqlwhere .= " AND timemodified > :changedsince";
1687     }
1688     $cf = array();
1689     if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1690         foreach ($flags as $flag) {
1691             $cf[$flag->name] = $flag->value;
1692         }
1693     }
1694     return $cf;
1697 /**
1698  * Get volatile flags
1699  *
1700  * @param string $type
1701  * @param string $name
1702  * @param int $changedsince default null
1703  * @return string|false The cache flag value or false
1704  */
1705 function get_cache_flag($type, $name, $changedsince=null) {
1706     global $DB;
1708     $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1710     $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1711     if ($changedsince !== null) {
1712         $params['changedsince'] = $changedsince;
1713         $sqlwhere .= " AND timemodified > :changedsince";
1714     }
1716     return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1719 /**
1720  * Set a volatile flag
1721  *
1722  * @param string $type the "type" namespace for the key
1723  * @param string $name the key to set
1724  * @param string $value the value to set (without magic quotes) - null will remove the flag
1725  * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1726  * @return bool Always returns true
1727  */
1728 function set_cache_flag($type, $name, $value, $expiry = null) {
1729     global $DB;
1731     $timemodified = time();
1732     if ($expiry === null || $expiry < $timemodified) {
1733         $expiry = $timemodified + 24 * 60 * 60;
1734     } else {
1735         $expiry = (int)$expiry;
1736     }
1738     if ($value === null) {
1739         unset_cache_flag($type, $name);
1740         return true;
1741     }
1743     if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1744         // This is a potential problem in DEBUG_DEVELOPER.
1745         if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1746             return true; // No need to update.
1747         }
1748         $f->value        = $value;
1749         $f->expiry       = $expiry;
1750         $f->timemodified = $timemodified;
1751         $DB->update_record('cache_flags', $f);
1752     } else {
1753         $f = new stdClass();
1754         $f->flagtype     = $type;
1755         $f->name         = $name;
1756         $f->value        = $value;
1757         $f->expiry       = $expiry;
1758         $f->timemodified = $timemodified;
1759         $DB->insert_record('cache_flags', $f);
1760     }
1761     return true;
1764 /**
1765  * Removes a single volatile flag
1766  *
1767  * @param string $type the "type" namespace for the key
1768  * @param string $name the key to set
1769  * @return bool
1770  */
1771 function unset_cache_flag($type, $name) {
1772     global $DB;
1773     $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1774     return true;
1777 /**
1778  * Garbage-collect volatile flags
1779  *
1780  * @return bool Always returns true
1781  */
1782 function gc_cache_flags() {
1783     global $DB;
1784     $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1785     return true;
1788 // USER PREFERENCE API.
1790 /**
1791  * Refresh user preference cache. This is used most often for $USER
1792  * object that is stored in session, but it also helps with performance in cron script.
1793  *
1794  * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1795  *
1796  * @package  core
1797  * @category preference
1798  * @access   public
1799  * @param    stdClass         $user          User object. Preferences are preloaded into 'preference' property
1800  * @param    int              $cachelifetime Cache life time on the current page (in seconds)
1801  * @throws   coding_exception
1802  * @return   null
1803  */
1804 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1805     global $DB;
1806     // Static cache, we need to check on each page load, not only every 2 minutes.
1807     static $loadedusers = array();
1809     if (!isset($user->id)) {
1810         throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1811     }
1813     if (empty($user->id) or isguestuser($user->id)) {
1814         // No permanent storage for not-logged-in users and guest.
1815         if (!isset($user->preference)) {
1816             $user->preference = array();
1817         }
1818         return;
1819     }
1821     $timenow = time();
1823     if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1824         // Already loaded at least once on this page. Are we up to date?
1825         if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1826             // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1827             return;
1829         } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1830             // No change since the lastcheck on this page.
1831             $user->preference['_lastloaded'] = $timenow;
1832             return;
1833         }
1834     }
1836     // OK, so we have to reload all preferences.
1837     $loadedusers[$user->id] = true;
1838     $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1839     $user->preference['_lastloaded'] = $timenow;
1842 /**
1843  * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1844  *
1845  * NOTE: internal function, do not call from other code.
1846  *
1847  * @package core
1848  * @access private
1849  * @param integer $userid the user whose prefs were changed.
1850  */
1851 function mark_user_preferences_changed($userid) {
1852     global $CFG;
1854     if (empty($userid) or isguestuser($userid)) {
1855         // No cache flags for guest and not-logged-in users.
1856         return;
1857     }
1859     set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1862 /**
1863  * Sets a preference for the specified user.
1864  *
1865  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1866  *
1867  * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1868  *
1869  * @package  core
1870  * @category preference
1871  * @access   public
1872  * @param    string            $name  The key to set as preference for the specified user
1873  * @param    string            $value The value to set for the $name key in the specified user's
1874  *                                    record, null means delete current value.
1875  * @param    stdClass|int|null $user  A moodle user object or id, null means current user
1876  * @throws   coding_exception
1877  * @return   bool                     Always true or exception
1878  */
1879 function set_user_preference($name, $value, $user = null) {
1880     global $USER, $DB;
1882     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1883         throw new coding_exception('Invalid preference name in set_user_preference() call');
1884     }
1886     if (is_null($value)) {
1887         // Null means delete current.
1888         return unset_user_preference($name, $user);
1889     } else if (is_object($value)) {
1890         throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1891     } else if (is_array($value)) {
1892         throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1893     }
1894     // Value column maximum length is 1333 characters.
1895     $value = (string)$value;
1896     if (core_text::strlen($value) > 1333) {
1897         throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1898     }
1900     if (is_null($user)) {
1901         $user = $USER;
1902     } else if (isset($user->id)) {
1903         // It is a valid object.
1904     } else if (is_numeric($user)) {
1905         $user = (object)array('id' => (int)$user);
1906     } else {
1907         throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1908     }
1910     check_user_preferences_loaded($user);
1912     if (empty($user->id) or isguestuser($user->id)) {
1913         // No permanent storage for not-logged-in users and guest.
1914         $user->preference[$name] = $value;
1915         return true;
1916     }
1918     if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1919         if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1920             // Preference already set to this value.
1921             return true;
1922         }
1923         $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1925     } else {
1926         $preference = new stdClass();
1927         $preference->userid = $user->id;
1928         $preference->name   = $name;
1929         $preference->value  = $value;
1930         $DB->insert_record('user_preferences', $preference);
1931     }
1933     // Update value in cache.
1934     $user->preference[$name] = $value;
1936     // Set reload flag for other sessions.
1937     mark_user_preferences_changed($user->id);
1939     return true;
1942 /**
1943  * Sets a whole array of preferences for the current user
1944  *
1945  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1946  *
1947  * @package  core
1948  * @category preference
1949  * @access   public
1950  * @param    array             $prefarray An array of key/value pairs to be set
1951  * @param    stdClass|int|null $user      A moodle user object or id, null means current user
1952  * @return   bool                         Always true or exception
1953  */
1954 function set_user_preferences(array $prefarray, $user = null) {
1955     foreach ($prefarray as $name => $value) {
1956         set_user_preference($name, $value, $user);
1957     }
1958     return true;
1961 /**
1962  * Unsets a preference completely by deleting it from the database
1963  *
1964  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1965  *
1966  * @package  core
1967  * @category preference
1968  * @access   public
1969  * @param    string            $name The key to unset as preference for the specified user
1970  * @param    stdClass|int|null $user A moodle user object or id, null means current user
1971  * @throws   coding_exception
1972  * @return   bool                    Always true or exception
1973  */
1974 function unset_user_preference($name, $user = null) {
1975     global $USER, $DB;
1977     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1978         throw new coding_exception('Invalid preference name in unset_user_preference() call');
1979     }
1981     if (is_null($user)) {
1982         $user = $USER;
1983     } else if (isset($user->id)) {
1984         // It is a valid object.
1985     } else if (is_numeric($user)) {
1986         $user = (object)array('id' => (int)$user);
1987     } else {
1988         throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1989     }
1991     check_user_preferences_loaded($user);
1993     if (empty($user->id) or isguestuser($user->id)) {
1994         // No permanent storage for not-logged-in user and guest.
1995         unset($user->preference[$name]);
1996         return true;
1997     }
1999     // Delete from DB.
2000     $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2002     // Delete the preference from cache.
2003     unset($user->preference[$name]);
2005     // Set reload flag for other sessions.
2006     mark_user_preferences_changed($user->id);
2008     return true;
2011 /**
2012  * Used to fetch user preference(s)
2013  *
2014  * If no arguments are supplied this function will return
2015  * all of the current user preferences as an array.
2016  *
2017  * If a name is specified then this function
2018  * attempts to return that particular preference value.  If
2019  * none is found, then the optional value $default is returned,
2020  * otherwise null.
2021  *
2022  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2023  *
2024  * @package  core
2025  * @category preference
2026  * @access   public
2027  * @param    string            $name    Name of the key to use in finding a preference value
2028  * @param    mixed|null        $default Value to be returned if the $name key is not set in the user preferences
2029  * @param    stdClass|int|null $user    A moodle user object or id, null means current user
2030  * @throws   coding_exception
2031  * @return   string|mixed|null          A string containing the value of a single preference. An
2032  *                                      array with all of the preferences or null
2033  */
2034 function get_user_preferences($name = null, $default = null, $user = null) {
2035     global $USER;
2037     if (is_null($name)) {
2038         // All prefs.
2039     } else if (is_numeric($name) or $name === '_lastloaded') {
2040         throw new coding_exception('Invalid preference name in get_user_preferences() call');
2041     }
2043     if (is_null($user)) {
2044         $user = $USER;
2045     } else if (isset($user->id)) {
2046         // Is a valid object.
2047     } else if (is_numeric($user)) {
2048         $user = (object)array('id' => (int)$user);
2049     } else {
2050         throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2051     }
2053     check_user_preferences_loaded($user);
2055     if (empty($name)) {
2056         // All values.
2057         return $user->preference;
2058     } else if (isset($user->preference[$name])) {
2059         // The single string value.
2060         return $user->preference[$name];
2061     } else {
2062         // Default value (null if not specified).
2063         return $default;
2064     }
2067 // FUNCTIONS FOR HANDLING TIME.
2069 /**
2070  * Given Gregorian date parts in user time produce a GMT timestamp.
2071  *
2072  * @package core
2073  * @category time
2074  * @param int $year The year part to create timestamp of
2075  * @param int $month The month part to create timestamp of
2076  * @param int $day The day part to create timestamp of
2077  * @param int $hour The hour part to create timestamp of
2078  * @param int $minute The minute part to create timestamp of
2079  * @param int $second The second part to create timestamp of
2080  * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2081  *             if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2082  * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2083  *             applied only if timezone is 99 or string.
2084  * @return int GMT timestamp
2085  */
2086 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2087     $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2088     $date->setDate((int)$year, (int)$month, (int)$day);
2089     $date->setTime((int)$hour, (int)$minute, (int)$second);
2091     $time = $date->getTimestamp();
2093     if ($time === false) {
2094         throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2095             ' This can fail if year is more than 2038 and OS is 32 bit windows');
2096     }
2098     // Moodle BC DST stuff.
2099     if (!$applydst) {
2100         $time += dst_offset_on($time, $timezone);
2101     }
2103     return $time;
2107 /**
2108  * Format a date/time (seconds) as weeks, days, hours etc as needed
2109  *
2110  * Given an amount of time in seconds, returns string
2111  * formatted nicely as weeks, days, hours etc as needed
2112  *
2113  * @package core
2114  * @category time
2115  * @uses MINSECS
2116  * @uses HOURSECS
2117  * @uses DAYSECS
2118  * @uses YEARSECS
2119  * @param int $totalsecs Time in seconds
2120  * @param stdClass $str Should be a time object
2121  * @return string A nicely formatted date/time string
2122  */
2123 function format_time($totalsecs, $str = null) {
2125     $totalsecs = abs($totalsecs);
2127     if (!$str) {
2128         // Create the str structure the slow way.
2129         $str = new stdClass();
2130         $str->day   = get_string('day');
2131         $str->days  = get_string('days');
2132         $str->hour  = get_string('hour');
2133         $str->hours = get_string('hours');
2134         $str->min   = get_string('min');
2135         $str->mins  = get_string('mins');
2136         $str->sec   = get_string('sec');
2137         $str->secs  = get_string('secs');
2138         $str->year  = get_string('year');
2139         $str->years = get_string('years');
2140     }
2142     $years     = floor($totalsecs/YEARSECS);
2143     $remainder = $totalsecs - ($years*YEARSECS);
2144     $days      = floor($remainder/DAYSECS);
2145     $remainder = $totalsecs - ($days*DAYSECS);
2146     $hours     = floor($remainder/HOURSECS);
2147     $remainder = $remainder - ($hours*HOURSECS);
2148     $mins      = floor($remainder/MINSECS);
2149     $secs      = $remainder - ($mins*MINSECS);
2151     $ss = ($secs == 1)  ? $str->sec  : $str->secs;
2152     $sm = ($mins == 1)  ? $str->min  : $str->mins;
2153     $sh = ($hours == 1) ? $str->hour : $str->hours;
2154     $sd = ($days == 1)  ? $str->day  : $str->days;
2155     $sy = ($years == 1)  ? $str->year  : $str->years;
2157     $oyears = '';
2158     $odays = '';
2159     $ohours = '';
2160     $omins = '';
2161     $osecs = '';
2163     if ($years) {
2164         $oyears  = $years .' '. $sy;
2165     }
2166     if ($days) {
2167         $odays  = $days .' '. $sd;
2168     }
2169     if ($hours) {
2170         $ohours = $hours .' '. $sh;
2171     }
2172     if ($mins) {
2173         $omins  = $mins .' '. $sm;
2174     }
2175     if ($secs) {
2176         $osecs  = $secs .' '. $ss;
2177     }
2179     if ($years) {
2180         return trim($oyears .' '. $odays);
2181     }
2182     if ($days) {
2183         return trim($odays .' '. $ohours);
2184     }
2185     if ($hours) {
2186         return trim($ohours .' '. $omins);
2187     }
2188     if ($mins) {
2189         return trim($omins .' '. $osecs);
2190     }
2191     if ($secs) {
2192         return $osecs;
2193     }
2194     return get_string('now');
2197 /**
2198  * Returns a formatted string that represents a date in user time.
2199  *
2200  * @package core
2201  * @category time
2202  * @param int $date the timestamp in UTC, as obtained from the database.
2203  * @param string $format strftime format. You should probably get this using
2204  *        get_string('strftime...', 'langconfig');
2205  * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2206  *        not 99 then daylight saving will not be added.
2207  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2208  * @param bool $fixday If true (default) then the leading zero from %d is removed.
2209  *        If false then the leading zero is maintained.
2210  * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2211  * @return string the formatted date/time.
2212  */
2213 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2214     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2215     return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2218 /**
2219  * Returns a formatted date ensuring it is UTF-8.
2220  *
2221  * If we are running under Windows convert to Windows encoding and then back to UTF-8
2222  * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2223  *
2224  * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2225  * @param string $format strftime format.
2226  * @param int|float|string $tz the user timezone
2227  * @return string the formatted date/time.
2228  * @since Moodle 2.3.3
2229  */
2230 function date_format_string($date, $format, $tz = 99) {
2231     global $CFG;
2233     $localewincharset = null;
2234     // Get the calendar type user is using.
2235     if ($CFG->ostype == 'WINDOWS') {
2236         $calendartype = \core_calendar\type_factory::get_calendar_instance();
2237         $localewincharset = $calendartype->locale_win_charset();
2238     }
2240     if ($localewincharset) {
2241         $format = core_text::convert($format, 'utf-8', $localewincharset);
2242     }
2244     date_default_timezone_set(core_date::get_user_timezone($tz));
2245     $datestring = strftime($format, $date);
2246     core_date::set_default_server_timezone();
2248     if ($localewincharset) {
2249         $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2250     }
2252     return $datestring;
2255 /**
2256  * Given a $time timestamp in GMT (seconds since epoch),
2257  * returns an array that represents the Gregorian date in user time
2258  *
2259  * @package core
2260  * @category time
2261  * @param int $time Timestamp in GMT
2262  * @param float|int|string $timezone user timezone
2263  * @return array An array that represents the date in user time
2264  */
2265 function usergetdate($time, $timezone=99) {
2266     date_default_timezone_set(core_date::get_user_timezone($timezone));
2267     $result = getdate($time);
2268     core_date::set_default_server_timezone();
2270     return $result;
2273 /**
2274  * Given a GMT timestamp (seconds since epoch), offsets it by
2275  * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2276  *
2277  * NOTE: this function does not include DST properly,
2278  *       you should use the PHP date stuff instead!
2279  *
2280  * @package core
2281  * @category time
2282  * @param int $date Timestamp in GMT
2283  * @param float|int|string $timezone user timezone
2284  * @return int
2285  */
2286 function usertime($date, $timezone=99) {
2287     $userdate = new DateTime('@' . $date);
2288     $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2289     $dst = dst_offset_on($date, $timezone);
2291     return $date - $userdate->getOffset() + $dst;
2294 /**
2295  * Given a time, return the GMT timestamp of the most recent midnight
2296  * for the current user.
2297  *
2298  * @package core
2299  * @category time
2300  * @param int $date Timestamp in GMT
2301  * @param float|int|string $timezone user timezone
2302  * @return int Returns a GMT timestamp
2303  */
2304 function usergetmidnight($date, $timezone=99) {
2306     $userdate = usergetdate($date, $timezone);
2308     // Time of midnight of this user's day, in GMT.
2309     return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2313 /**
2314  * Returns a string that prints the user's timezone
2315  *
2316  * @package core
2317  * @category time
2318  * @param float|int|string $timezone user timezone
2319  * @return string
2320  */
2321 function usertimezone($timezone=99) {
2322     $tz = core_date::get_user_timezone($timezone);
2323     return core_date::get_localised_timezone($tz);
2326 /**
2327  * Returns a float or a string which denotes the user's timezone
2328  * 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)
2329  * means that for this timezone there are also DST rules to be taken into account
2330  * Checks various settings and picks the most dominant of those which have a value
2331  *
2332  * @package core
2333  * @category time
2334  * @param float|int|string $tz timezone to calculate GMT time offset before
2335  *        calculating user timezone, 99 is default user timezone
2336  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2337  * @return float|string
2338  */
2339 function get_user_timezone($tz = 99) {
2340     global $USER, $CFG;
2342     $timezones = array(
2343         $tz,
2344         isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2345         isset($USER->timezone) ? $USER->timezone : 99,
2346         isset($CFG->timezone) ? $CFG->timezone : 99,
2347         );
2349     $tz = 99;
2351     // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2352     while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2353         $tz = $next['value'];
2354     }
2355     return is_numeric($tz) ? (float) $tz : $tz;
2358 /**
2359  * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2360  * - Note: Daylight saving only works for string timezones and not for float.
2361  *
2362  * @package core
2363  * @category time
2364  * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2365  * @param int|float|string $strtimezone user timezone
2366  * @return int
2367  */
2368 function dst_offset_on($time, $strtimezone = null) {
2369     $tz = core_date::get_user_timezone($strtimezone);
2370     $date = new DateTime('@' . $time);
2371     $date->setTimezone(new DateTimeZone($tz));
2372     if ($date->format('I') == '1') {
2373         if ($tz === 'Australia/Lord_Howe') {
2374             return 1800;
2375         }
2376         return 3600;
2377     }
2378     return 0;
2381 /**
2382  * Calculates when the day appears in specific month
2383  *
2384  * @package core
2385  * @category time
2386  * @param int $startday starting day of the month
2387  * @param int $weekday The day when week starts (normally taken from user preferences)
2388  * @param int $month The month whose day is sought
2389  * @param int $year The year of the month whose day is sought
2390  * @return int
2391  */
2392 function find_day_in_month($startday, $weekday, $month, $year) {
2393     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2395     $daysinmonth = days_in_month($month, $year);
2396     $daysinweek = count($calendartype->get_weekdays());
2398     if ($weekday == -1) {
2399         // Don't care about weekday, so return:
2400         //    abs($startday) if $startday != -1
2401         //    $daysinmonth otherwise.
2402         return ($startday == -1) ? $daysinmonth : abs($startday);
2403     }
2405     // From now on we 're looking for a specific weekday.
2406     // Give "end of month" its actual value, since we know it.
2407     if ($startday == -1) {
2408         $startday = -1 * $daysinmonth;
2409     }
2411     // Starting from day $startday, the sign is the direction.
2412     if ($startday < 1) {
2413         $startday = abs($startday);
2414         $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2416         // This is the last such weekday of the month.
2417         $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2418         if ($lastinmonth > $daysinmonth) {
2419             $lastinmonth -= $daysinweek;
2420         }
2422         // Find the first such weekday <= $startday.
2423         while ($lastinmonth > $startday) {
2424             $lastinmonth -= $daysinweek;
2425         }
2427         return $lastinmonth;
2428     } else {
2429         $indexweekday = dayofweek($startday, $month, $year);
2431         $diff = $weekday - $indexweekday;
2432         if ($diff < 0) {
2433             $diff += $daysinweek;
2434         }
2436         // This is the first such weekday of the month equal to or after $startday.
2437         $firstfromindex = $startday + $diff;
2439         return $firstfromindex;
2440     }
2443 /**
2444  * Calculate the number of days in a given month
2445  *
2446  * @package core
2447  * @category time
2448  * @param int $month The month whose day count is sought
2449  * @param int $year The year of the month whose day count is sought
2450  * @return int
2451  */
2452 function days_in_month($month, $year) {
2453     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2454     return $calendartype->get_num_days_in_month($year, $month);
2457 /**
2458  * Calculate the position in the week of a specific calendar day
2459  *
2460  * @package core
2461  * @category time
2462  * @param int $day The day of the date whose position in the week is sought
2463  * @param int $month The month of the date whose position in the week is sought
2464  * @param int $year The year of the date whose position in the week is sought
2465  * @return int
2466  */
2467 function dayofweek($day, $month, $year) {
2468     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2469     return $calendartype->get_weekday($year, $month, $day);
2472 // USER AUTHENTICATION AND LOGIN.
2474 /**
2475  * Returns full login url.
2476  *
2477  * @return string login url
2478  */
2479 function get_login_url() {
2480     global $CFG;
2482     $url = "$CFG->wwwroot/login/index.php";
2484     if (!empty($CFG->loginhttps)) {
2485         $url = str_replace('http:', 'https:', $url);
2486     }
2488     return $url;
2491 /**
2492  * This function checks that the current user is logged in and has the
2493  * required privileges
2494  *
2495  * This function checks that the current user is logged in, and optionally
2496  * whether they are allowed to be in a particular course and view a particular
2497  * course module.
2498  * If they are not logged in, then it redirects them to the site login unless
2499  * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2500  * case they are automatically logged in as guests.
2501  * If $courseid is given and the user is not enrolled in that course then the
2502  * user is redirected to the course enrolment page.
2503  * If $cm is given and the course module is hidden and the user is not a teacher
2504  * in the course then the user is redirected to the course home page.
2505  *
2506  * When $cm parameter specified, this function sets page layout to 'module'.
2507  * You need to change it manually later if some other layout needed.
2508  *
2509  * @package    core_access
2510  * @category   access
2511  *
2512  * @param mixed $courseorid id of the course or course object
2513  * @param bool $autologinguest default true
2514  * @param object $cm course module object
2515  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2516  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2517  *             in order to keep redirects working properly. MDL-14495
2518  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2519  * @return mixed Void, exit, and die depending on path
2520  * @throws coding_exception
2521  * @throws require_login_exception
2522  * @throws moodle_exception
2523  */
2524 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2525     global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2527     // Must not redirect when byteserving already started.
2528     if (!empty($_SERVER['HTTP_RANGE'])) {
2529         $preventredirect = true;
2530     }
2532     if (AJAX_SCRIPT) {
2533         // We cannot redirect for AJAX scripts either.
2534         $preventredirect = true;
2535     }
2537     // Setup global $COURSE, themes, language and locale.
2538     if (!empty($courseorid)) {
2539         if (is_object($courseorid)) {
2540             $course = $courseorid;
2541         } else if ($courseorid == SITEID) {
2542             $course = clone($SITE);
2543         } else {
2544             $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2545         }
2546         if ($cm) {
2547             if ($cm->course != $course->id) {
2548                 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2549             }
2550             // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2551             if (!($cm instanceof cm_info)) {
2552                 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2553                 // db queries so this is not really a performance concern, however it is obviously
2554                 // better if you use get_fast_modinfo to get the cm before calling this.
2555                 $modinfo = get_fast_modinfo($course);
2556                 $cm = $modinfo->get_cm($cm->id);
2557             }
2558         }
2559     } else {
2560         // Do not touch global $COURSE via $PAGE->set_course(),
2561         // the reasons is we need to be able to call require_login() at any time!!
2562         $course = $SITE;
2563         if ($cm) {
2564             throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2565         }
2566     }
2568     // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2569     // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2570     // risk leading the user back to the AJAX request URL.
2571     if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2572         $setwantsurltome = false;
2573     }
2575     // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2576     if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2577         if ($preventredirect) {
2578             throw new require_login_session_timeout_exception();
2579         } else {
2580             if ($setwantsurltome) {
2581                 $SESSION->wantsurl = qualified_me();
2582             }
2583             redirect(get_login_url());
2584         }
2585     }
2587     // If the user is not even logged in yet then make sure they are.
2588     if (!isloggedin()) {
2589         if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2590             if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2591                 // Misconfigured site guest, just redirect to login page.
2592                 redirect(get_login_url());
2593                 exit; // Never reached.
2594             }
2595             $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2596             complete_user_login($guest);
2597             $USER->autologinguest = true;
2598             $SESSION->lang = $lang;
2599         } else {
2600             // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2601             if ($preventredirect) {
2602                 throw new require_login_exception('You are not logged in');
2603             }
2605             if ($setwantsurltome) {
2606                 $SESSION->wantsurl = qualified_me();
2607             }
2609             $referer = get_local_referer(false);
2610             if (!empty($referer)) {
2611                 $SESSION->fromurl = $referer;
2612             }
2614             // Give auth plugins an opportunity to authenticate or redirect to an external login page
2615             $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2616             foreach($authsequence as $authname) {
2617                 $authplugin = get_auth_plugin($authname);
2618                 $authplugin->pre_loginpage_hook();
2619                 if (isloggedin()) {
2620                     break;
2621                 }
2622             }
2624             // If we're still not logged in then go to the login page
2625             if (!isloggedin()) {
2626                 redirect(get_login_url());
2627                 exit; // Never reached.
2628             }
2629         }
2630     }
2632     // Loginas as redirection if needed.
2633     if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2634         if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2635             if ($USER->loginascontext->instanceid != $course->id) {
2636                 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2637             }
2638         }
2639     }
2641     // Check whether the user should be changing password (but only if it is REALLY them).
2642     if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2643         $userauth = get_auth_plugin($USER->auth);
2644         if ($userauth->can_change_password() and !$preventredirect) {
2645             if ($setwantsurltome) {
2646                 $SESSION->wantsurl = qualified_me();
2647             }
2648             if ($changeurl = $userauth->change_password_url()) {
2649                 // Use plugin custom url.
2650                 redirect($changeurl);
2651             } else {
2652                 // Use moodle internal method.
2653                 if (empty($CFG->loginhttps)) {
2654                     redirect($CFG->wwwroot .'/login/change_password.php');
2655                 } else {
2656                     $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2657                     redirect($wwwroot .'/login/change_password.php');
2658                 }
2659             }
2660         } else if ($userauth->can_change_password()) {
2661             throw new moodle_exception('forcepasswordchangenotice');
2662         } else {
2663             throw new moodle_exception('nopasswordchangeforced', 'auth');
2664         }
2665     }
2667     // Check that the user account is properly set up. If we can't redirect to
2668     // edit their profile and this is not a WS request, perform just the lax check.
2669     // It will allow them to use filepicker on the profile edit page.
2671     if ($preventredirect && !WS_SERVER) {
2672         $usernotfullysetup = user_not_fully_set_up($USER, false);
2673     } else {
2674         $usernotfullysetup = user_not_fully_set_up($USER, true);
2675     }
2677     if ($usernotfullysetup) {
2678         if ($preventredirect) {
2679             throw new moodle_exception('usernotfullysetup');
2680         }
2681         if ($setwantsurltome) {
2682             $SESSION->wantsurl = qualified_me();
2683         }
2684         redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2685     }
2687     // Make sure the USER has a sesskey set up. Used for CSRF protection.
2688     sesskey();
2690     // Do not bother admins with any formalities, except for activities pending deletion.
2691     if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2692         // Set the global $COURSE.
2693         if ($cm) {
2694             $PAGE->set_cm($cm, $course);
2695             $PAGE->set_pagelayout('incourse');
2696         } else if (!empty($courseorid)) {
2697             $PAGE->set_course($course);
2698         }
2699         // Set accesstime or the user will appear offline which messes up messaging.
2700         user_accesstime_log($course->id);
2701         return;
2702     }
2704     // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2705     if (!$USER->policyagreed and !is_siteadmin()) {
2706         if (!empty($CFG->sitepolicy) and !isguestuser()) {
2707             if ($preventredirect) {
2708                 throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicy);
2709             }
2710             if ($setwantsurltome) {
2711                 $SESSION->wantsurl = qualified_me();
2712             }
2713             redirect($CFG->wwwroot .'/user/policy.php');
2714         } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2715             if ($preventredirect) {
2716                 throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicyguest);
2717             }
2718             if ($setwantsurltome) {
2719                 $SESSION->wantsurl = qualified_me();
2720             }
2721             redirect($CFG->wwwroot .'/user/policy.php');
2722         }
2723     }
2725     // Fetch the system context, the course context, and prefetch its child contexts.
2726     $sysctx = context_system::instance();
2727     $coursecontext = context_course::instance($course->id, MUST_EXIST);
2728     if ($cm) {
2729         $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2730     } else {
2731         $cmcontext = null;
2732     }
2734     // If the site is currently under maintenance, then print a message.
2735     if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2736         if ($preventredirect) {
2737             throw new require_login_exception('Maintenance in progress');
2738         }
2739         $PAGE->set_context(null);
2740         print_maintenance_message();
2741     }
2743     // Make sure the course itself is not hidden.
2744     if ($course->id == SITEID) {
2745         // Frontpage can not be hidden.
2746     } else {
2747         if (is_role_switched($course->id)) {
2748             // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2749         } else {
2750             if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2751                 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2752                 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2753                 if ($preventredirect) {
2754                     throw new require_login_exception('Course is hidden');
2755                 }
2756                 $PAGE->set_context(null);
2757                 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2758                 // the navigation will mess up when trying to find it.
2759                 navigation_node::override_active_url(new moodle_url('/'));
2760                 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2761             }
2762         }
2763     }
2765     // Is the user enrolled?
2766     if ($course->id == SITEID) {
2767         // Everybody is enrolled on the frontpage.
2768     } else {
2769         if (\core\session\manager::is_loggedinas()) {
2770             // Make sure the REAL person can access this course first.
2771             $realuser = \core\session\manager::get_realuser();
2772             if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2773                 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2774                 if ($preventredirect) {
2775                     throw new require_login_exception('Invalid course login-as access');
2776                 }
2777                 $PAGE->set_context(null);
2778                 echo $OUTPUT->header();
2779                 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2780             }
2781         }
2783         $access = false;
2785         if (is_role_switched($course->id)) {
2786             // Ok, user had to be inside this course before the switch.
2787             $access = true;
2789         } else if (is_viewing($coursecontext, $USER)) {
2790             // Ok, no need to mess with enrol.
2791             $access = true;
2793         } else {
2794             if (isset($USER->enrol['enrolled'][$course->id])) {
2795                 if ($USER->enrol['enrolled'][$course->id] > time()) {
2796                     $access = true;
2797                     if (isset($USER->enrol['tempguest'][$course->id])) {
2798                         unset($USER->enrol['tempguest'][$course->id]);
2799                         remove_temp_course_roles($coursecontext);
2800                     }
2801                 } else {
2802                     // Expired.
2803                     unset($USER->enrol['enrolled'][$course->id]);
2804                 }
2805             }
2806             if (isset($USER->enrol['tempguest'][$course->id])) {
2807                 if ($USER->enrol['tempguest'][$course->id] == 0) {
2808                     $access = true;
2809                 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2810                     $access = true;
2811                 } else {
2812                     // Expired.
2813                     unset($USER->enrol['tempguest'][$course->id]);
2814                     remove_temp_course_roles($coursecontext);
2815                 }
2816             }
2818             if (!$access) {
2819                 // Cache not ok.
2820                 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2821                 if ($until !== false) {
2822                     // Active participants may always access, a timestamp in the future, 0 (always) or false.
2823                     if ($until == 0) {
2824                         $until = ENROL_MAX_TIMESTAMP;
2825                     }
2826                     $USER->enrol['enrolled'][$course->id] = $until;
2827                     $access = true;
2829                 } else {
2830                     $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2831                     $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2832                     $enrols = enrol_get_plugins(true);
2833                     // First ask all enabled enrol instances in course if they want to auto enrol user.
2834                     foreach ($instances as $instance) {
2835                         if (!isset($enrols[$instance->enrol])) {
2836                             continue;
2837                         }
2838                         // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2839                         $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2840                         if ($until !== false) {
2841                             if ($until == 0) {
2842                                 $until = ENROL_MAX_TIMESTAMP;
2843                             }
2844                             $USER->enrol['enrolled'][$course->id] = $until;
2845                             $access = true;
2846                             break;
2847                         }
2848                     }
2849                     // If not enrolled yet try to gain temporary guest access.
2850                     if (!$access) {
2851                         foreach ($instances as $instance) {
2852                             if (!isset($enrols[$instance->enrol])) {
2853                                 continue;
2854                             }
2855                             // Get a duration for the guest access, a timestamp in the future or false.
2856                             $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2857                             if ($until !== false and $until > time()) {
2858                                 $USER->enrol['tempguest'][$course->id] = $until;
2859                                 $access = true;
2860                                 break;
2861                             }
2862                         }
2863                     }
2864                 }
2865             }
2866         }
2868         if (!$access) {
2869             if ($preventredirect) {
2870                 throw new require_login_exception('Not enrolled');
2871             }
2872             if ($setwantsurltome) {
2873                 $SESSION->wantsurl = qualified_me();
2874             }
2875             redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2876         }
2877     }
2879     // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
2880     if ($cm && $cm->deletioninprogress) {
2881         if ($preventredirect) {
2882             throw new moodle_exception('activityisscheduledfordeletion');
2883         }
2884         require_once($CFG->dirroot . '/course/lib.php');
2885         redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
2886     }
2888     // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2889     if ($cm && !$cm->uservisible) {
2890         if ($preventredirect) {
2891             throw new require_login_exception('Activity is hidden');
2892         }
2893         if ($course->id != SITEID) {
2894             $url = new moodle_url('/course/view.php', array('id' => $course->id));
2895         } else {
2896             $url = new moodle_url('/');
2897         }
2898         redirect($url, get_string('activityiscurrentlyhidden'), null,
2899                 \core\output\notification::NOTIFY_ERROR);
2900     }
2902     // Set the global $COURSE.
2903     if ($cm) {
2904         $PAGE->set_cm($cm, $course);
2905         $PAGE->set_pagelayout('incourse');
2906     } else if (!empty($courseorid)) {
2907         $PAGE->set_course($course);
2908     }
2910     // Finally access granted, update lastaccess times.
2911     user_accesstime_log($course->id);
2915 /**
2916  * This function just makes sure a user is logged out.
2917  *
2918  * @package    core_access
2919  * @category   access
2920  */
2921 function require_logout() {
2922     global $USER, $DB;
2924     if (!isloggedin()) {
2925         // This should not happen often, no need for hooks or events here.
2926         \core\session\manager::terminate_current();
2927         return;
2928     }
2930     // Execute hooks before action.
2931     $authplugins = array();
2932     $authsequence = get_enabled_auth_plugins();
2933     foreach ($authsequence as $authname) {
2934         $authplugins[$authname] = get_auth_plugin($authname);
2935         $authplugins[$authname]->prelogout_hook();
2936     }
2938     // Store info that gets removed during logout.
2939     $sid = session_id();
2940     $event = \core\event\user_loggedout::create(
2941         array(
2942             'userid' => $USER->id,
2943             'objectid' => $USER->id,
2944             'other' => array('sessionid' => $sid),
2945         )
2946     );
2947     if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2948         $event->add_record_snapshot('sessions', $session);
2949     }
2951     // Clone of $USER object to be used by auth plugins.
2952     $user = fullclone($USER);
2954     // Delete session record and drop $_SESSION content.
2955     \core\session\manager::terminate_current();
2957     // Trigger event AFTER action.
2958     $event->trigger();
2960     // Hook to execute auth plugins redirection after event trigger.
2961     foreach ($authplugins as $authplugin) {
2962         $authplugin->postlogout_hook($user);
2963     }
2966 /**
2967  * Weaker version of require_login()
2968  *
2969  * This is a weaker version of {@link require_login()} which only requires login
2970  * when called from within a course rather than the site page, unless
2971  * the forcelogin option is turned on.
2972  * @see require_login()
2973  *
2974  * @package    core_access
2975  * @category   access
2976  *
2977  * @param mixed $courseorid The course object or id in question
2978  * @param bool $autologinguest Allow autologin guests if that is wanted
2979  * @param object $cm Course activity module if known
2980  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2981  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2982  *             in order to keep redirects working properly. MDL-14495
2983  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2984  * @return void
2985  * @throws coding_exception
2986  */
2987 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2988     global $CFG, $PAGE, $SITE;
2989     $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2990           or (!is_object($courseorid) and $courseorid == SITEID));
2991     if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2992         // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2993         // db queries so this is not really a performance concern, however it is obviously
2994         // better if you use get_fast_modinfo to get the cm before calling this.
2995         if (is_object($courseorid)) {
2996             $course = $courseorid;
2997         } else {
2998             $course = clone($SITE);
2999         }
3000         $modinfo = get_fast_modinfo($course);
3001         $cm = $modinfo->get_cm($cm->id);
3002     }
3003     if (!empty($CFG->forcelogin)) {
3004         // Login required for both SITE and courses.
3005         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3007     } else if ($issite && !empty($cm) and !$cm->uservisible) {
3008         // Always login for hidden activities.
3009         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3011     } else if ($issite) {
3012         // Login for SITE not required.
3013         // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3014         if (!empty($courseorid)) {
3015             if (is_object($courseorid)) {
3016                 $course = $courseorid;
3017             } else {
3018                 $course = clone $SITE;
3019             }
3020             if ($cm) {
3021                 if ($cm->course != $course->id) {
3022                     throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3023                 }
3024                 $PAGE->set_cm($cm, $course);
3025                 $PAGE->set_pagelayout('incourse');
3026             } else {
3027                 $PAGE->set_course($course);
3028             }
3029         } else {
3030             // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3031             $PAGE->set_course($PAGE->course);
3032         }
3033         user_accesstime_log(SITEID);
3034         return;
3036     } else {
3037         // Course login always required.
3038         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3039     }
3042 /**
3043  * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3044  *
3045  * @param  string $keyvalue the key value
3046  * @param  string $script   unique script identifier
3047  * @param  int $instance    instance id
3048  * @return stdClass the key entry in the user_private_key table
3049  * @since Moodle 3.2
3050  * @throws moodle_exception
3051  */
3052 function validate_user_key($keyvalue, $script, $instance) {
3053     global $DB;
3055     if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3056         print_error('invalidkey');
3057     }
3059     if (!empty($key->validuntil) and $key->validuntil < time()) {
3060         print_error('expiredkey');
3061     }
3063     if ($key->iprestriction) {
3064         $remoteaddr = getremoteaddr(null);
3065         if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3066             print_error('ipmismatch');
3067         }
3068     }
3069     return $key;
3072 /**
3073  * Require key login. Function terminates with error if key not found or incorrect.
3074  *
3075  * @uses NO_MOODLE_COOKIES
3076  * @uses PARAM_ALPHANUM
3077  * @param string $script unique script identifier
3078  * @param int $instance optional instance id
3079  * @return int Instance ID
3080  */
3081 function require_user_key_login($script, $instance=null) {
3082     global $DB;
3084     if (!NO_MOODLE_COOKIES) {
3085         print_error('sessioncookiesdisable');
3086     }
3088     // Extra safety.
3089     \core\session\manager::write_close();
3091     $keyvalue = required_param('key', PARAM_ALPHANUM);
3093     $key = validate_user_key($keyvalue, $script, $instance);
3095     if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3096         print_error('invaliduserid');
3097     }
3099     // Emulate normal session.
3100     enrol_check_plugins($user);
3101     \core\session\manager::set_user($user);
3103     // Note we are not using normal login.
3104     if (!defined('USER_KEY_LOGIN')) {
3105         define('USER_KEY_LOGIN', true);
3106     }
3108     // Return instance id - it might be empty.
3109     return $key->instance;
3112 /**
3113  * Creates a new private user access key.
3114  *
3115  * @param string $script unique target identifier
3116  * @param int $userid
3117  * @param int $instance optional instance id
3118  * @param string $iprestriction optional ip restricted access
3119  * @param int $validuntil key valid only until given data
3120  * @return string access key value
3121  */
3122 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3123     global $DB;
3125     $key = new stdClass();
3126     $key->script        = $script;
3127     $key->userid        = $userid;
3128     $key->instance      = $instance;
3129     $key->iprestriction = $iprestriction;
3130     $key->validuntil    = $validuntil;
3131     $key->timecreated   = time();
3133     // Something long and unique.
3134     $key->value         = md5($userid.'_'.time().random_string(40));
3135     while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3136         // Must be unique.
3137         $key->value     = md5($userid.'_'.time().random_string(40));
3138     }
3139     $DB->insert_record('user_private_key', $key);
3140     return $key->value;
3143 /**
3144  * Delete the user's new private user access keys for a particular script.
3145  *
3146  * @param string $script unique target identifier
3147  * @param int $userid
3148  * @return void
3149  */
3150 function delete_user_key($script, $userid) {
3151     global $DB;
3152     $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3155 /**
3156  * Gets a private user access key (and creates one if one doesn't exist).
3157  *
3158  * @param string $script unique target identifier
3159  * @param int $userid
3160  * @param int $instance optional instance id
3161  * @param string $iprestriction optional ip restricted access
3162  * @param int $validuntil key valid only until given date
3163  * @return string access key value
3164  */
3165 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3166     global $DB;
3168     if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3169                                                          'instance' => $instance, 'iprestriction' => $iprestriction,
3170                                                          'validuntil' => $validuntil))) {
3171         return $key->value;
3172     } else {
3173         return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3174     }
3178 /**
3179  * Modify the user table by setting the currently logged in user's last login to now.
3180  *
3181  * @return bool Always returns true
3182  */
3183 function update_user_login_times() {
3184     global $USER, $DB;
3186     if (isguestuser()) {
3187         // Do not update guest access times/ips for performance.
3188         return true;
3189     }
3191     $now = time();
3193     $user = new stdClass();
3194     $user->id = $USER->id;
3196     // Make sure all users that logged in have some firstaccess.
3197     if ($USER->firstaccess == 0) {
3198         $USER->firstaccess = $user->firstaccess = $now;
3199     }
3201     // Store the previous current as lastlogin.
3202     $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3204     $USER->currentlogin = $user->currentlogin = $now;
3206     // Function user_accesstime_log() may not update immediately, better do it here.
3207     $USER->lastaccess = $user->lastaccess = $now;
3208     $USER->lastip = $user->lastip = getremoteaddr();
3210     // Note: do not call user_update_user() here because this is part of the login process,
3211     //       the login event means that these fields were updated.
3212     $DB->update_record('user', $user);
3213     return true;
3216 /**
3217  * Determines if a user has completed setting up their account.
3218  *
3219  * The lax mode (with $strict = false) has been introduced for special cases
3220  * only where we want to skip certain checks intentionally. This is valid in
3221  * certain mnet or ajax scenarios when the user cannot / should not be
3222  * redirected to edit their profile. In most cases, you should perform the
3223  * strict check.
3224  *
3225  * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3226  * @param bool $strict Be more strict and assert id and custom profile fields set, too
3227  * @return bool
3228  */
3229 function user_not_fully_set_up($user, $strict = true) {
3230     global $CFG;
3231     require_once($CFG->dirroot.'/user/profile/lib.php');
3233     if (isguestuser($user)) {
3234         return false;
3235     }
3237     if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3238         return true;
3239     }
3241     if ($strict) {
3242         if (empty($user->id)) {
3243             // Strict mode can be used with existing accounts only.
3244             return true;
3245         }
3246         if (!profile_has_required_custom_fields_set($user->id)) {
3247             return true;
3248         }
3249     }
3251     return false;
3254 /**
3255  * Check whether the user has exceeded the bounce threshold
3256  *
3257  * @param stdClass $user A {@link $USER} object
3258  * @return bool true => User has exceeded bounce threshold
3259  */
3260 function over_bounce_threshold($user) {
3261     global $CFG, $DB;
3263     if (empty($CFG->handlebounces)) {
3264         return false;
3265     }
3267     if (empty($user->id)) {
3268         // No real (DB) user, nothing to do here.
3269         return false;
3270     }
3272     // Set sensible defaults.
3273     if (empty($CFG->minbounces)) {
3274         $CFG->minbounces = 10;
3275     }
3276     if (empty($CFG->bounceratio)) {
3277         $CFG->bounceratio = .20;
3278     }
3279     $bouncecount = 0;
3280     $sendcount = 0;
3281     if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3282         $bouncecount = $bounce->value;
3283     }
3284     if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3285         $sendcount = $send->value;
3286     }
3287     return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3290 /**
3291  * Used to increment or reset email sent count
3292  *
3293  * @param stdClass $user object containing an id
3294  * @param bool $reset will reset the count to 0
3295  * @return void
3296  */
3297 function set_send_count($user, $reset=false) {
3298     global $DB;
3300     if (empty($user->id)) {
3301         // No real (DB) user, nothing to do here.
3302         return;
3303     }
3305     if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3306         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3307         $DB->update_record('user_preferences', $pref);
3308     } else if (!empty($reset)) {
3309         // If it's not there and we're resetting, don't bother. Make a new one.
3310         $pref = new stdClass();
3311         $pref->name   = 'email_send_count';
3312         $pref->value  = 1;
3313         $pref->userid = $user->id;
3314         $DB->insert_record('user_preferences', $pref, false);
3315     }
3318 /**
3319  * Increment or reset user's email bounce count
3320  *
3321  * @param stdClass $user object containing an id
3322  * @param bool $reset will reset the count to 0
3323  */
3324 function set_bounce_count($user, $reset=false) {
3325     global $DB;
3327     if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3328         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3329         $DB->update_record('user_preferences', $pref);
3330     } else if (!empty($reset)) {
3331         // If it's not there and we're resetting, don't bother. Make a new one.
3332         $pref = new stdClass();
3333         $pref->name   = 'email_bounce_count';
3334         $pref->value  = 1;
3335         $pref->userid = $user->id;
3336         $DB->insert_record('user_preferences', $pref, false);
3337     }
3340 /**
3341  * Determines if the logged in user is currently moving an activity
3342  *
3343  * @param int $courseid The id of the course being tested
3344  * @return bool
3345  */
3346 function ismoving($courseid) {
3347     global $USER;
3349     if (!empty($USER->activitycopy)) {
3350         return ($USER->activitycopycourse == $courseid);
3351     }
3352     return false;
3355 /**
3356  * Returns a persons full name
3357  *
3358  * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3359  * The result may depend on system settings or language.  'override' will force both names to be used even if system settings
3360  * specify one.
3361  *
3362  * @param stdClass $user A {@link $USER} object to get full name of.
3363  * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3364  * @return string
3365  */
3366 function fullname($user, $override=false) {
3367     global $CFG, $SESSION;
3369     if (!isset($user->firstname) and !isset($user->lastname)) {
3370         return '';
3371     }
3373     // Get all of the name fields.
3374     $allnames = get_all_user_name_fields();
3375     if ($CFG->debugdeveloper) {
3376         foreach ($allnames as $allname) {
3377             if (!property_exists($user, $allname)) {
3378                 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3379                 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3380                 // Message has been sent, no point in sending the message multiple times.
3381                 break;
3382             }
3383         }
3384     }
3386     if (!$override) {
3387         if (!empty($CFG->forcefirstname)) {
3388             $user->firstname = $CFG->forcefirstname;
3389         }
3390         if (!empty($CFG->forcelastname)) {
3391             $user->lastname = $CFG->forcelastname;
3392         }
3393     }
3395     if (!empty($SESSION->fullnamedisplay)) {
3396         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3397     }
3399     $template = null;
3400     // If the fullnamedisplay setting is available, set the template to that.
3401     if (isset($CFG->fullnamedisplay)) {
3402         $template = $CFG->fullnamedisplay;
3403     }
3404     // If the template is empty, or set to language, return the language string.
3405     if ((empty($template) || $template == 'language') && !$override) {
3406         return get_string('fullnamedisplay', null, $user);
3407     }
3409     // Check to see if we are displaying according to the alternative full name format.
3410     if ($override) {
3411         if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3412             // Default to show just the user names according to the fullnamedisplay string.
3413             return get_string('fullnamedisplay', null, $user);
3414         } else {
3415             // If the override is true, then change the template to use the complete name.
3416             $template = $CFG->alternativefullnameformat;
3417         }
3418     }
3420     $requirednames = array();
3421     // With each name, see if it is in the display name template, and add it to the required names array if it is.
3422     foreach ($allnames as $allname) {
3423         if (strpos($template, $allname) !== false) {
3424             $requirednames[] = $allname;
3425         }
3426     }
3428     $displayname = $template;
3429     // Switch in the actual data into the template.
3430     foreach ($requirednames as $altname) {
3431         if (isset($user->$altname)) {
3432             // Using empty() on the below if statement causes breakages.
3433             if ((string)$user->$altname == '') {
3434                 $displayname = str_replace($altname, 'EMPTY', $displayname);
3435             } else {
3436                 $displayname = str_replace($altname, $user->$altname, $displayname);
3437             }
3438         } else {
3439             $displayname = str_replace($altname, 'EMPTY', $displayname);
3440         }
3441     }
3442     // Tidy up any misc. characters (Not perfect, but gets most characters).
3443     // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3444     // katakana and parenthesis.
3445     $patterns = array();
3446     // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3447     // filled in by a user.
3448     // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3449     $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3450     // This regular expression is to remove any double spaces in the display name.
3451     $patterns[] = '/\s{2,}/u';
3452     foreach ($patterns as $pattern) {
3453         $displayname = preg_replace($pattern, ' ', $displayname);
3454     }
3456     // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3457     $displayname = trim($displayname);
3458     if (empty($displayname)) {
3459         // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3460         // people in general feel is a good setting to fall back on.
3461         $displayname = $user->firstname;
3462     }
3463     return $displayname;
3466 /**
3467  * A centralised location for the all name fields. Returns an array / sql string snippet.
3468  *
3469  * @param bool $returnsql True for an sql select field snippet.
3470  * @param string $tableprefix table query prefix to use in front of each field.
3471  * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3472  * @param string $fieldprefix sql field prefix e.g. id AS userid.
3473  * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3474  * @return array|string All name fields.
3475  */
3476 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3477     // This array is provided in this order because when called by fullname() (above) if firstname is before
3478     // firstnamephonetic str_replace() will change the wrong placeholder.
3479     $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3480                             'lastnamephonetic' => 'lastnamephonetic',
3481                             'middlename' => 'middlename',
3482                             'alternatename' => 'alternatename',
3483                             'firstname' => 'firstname',
3484                             'lastname' => 'lastname');
3486     // Let's add a prefix to the array of user name fields if provided.
3487     if ($prefix) {
3488         foreach ($alternatenames as $key => $altname) {
3489             $alternatenames[$key] = $prefix . $altname;
3490         }
3491     }
3493     // If we want the end result to have firstname and lastname at the front / top of the result.
3494     if ($order) {
3495         // Move the last two elements (firstname, lastname) off the array and put them at the top.
3496         for ($i = 0; $i < 2; $i++) {
3497             // Get the last element.
3498             $lastelement = end($alternatenames);
3499             // Remove it from the array.
3500             unset($alternatenames[$lastelement]);
3501             // Put the element back on the top of the array.
3502             $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3503         }
3504     }
3506     // Create an sql field snippet if requested.
3507     if ($returnsql) {
3508         if ($tableprefix) {
3509             if ($fieldprefix) {
3510                 foreach ($alternatenames as $key => $altname) {
3511                     $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3512                 }
3513             } else {
3514                 foreach ($alternatenames as $key => $altname) {
3515                     $alternatenames[$key] = $tableprefix . '.' . $altname;
3516                 }
3517             }
3518         }
3519         $alternatenames = implode(',', $alternatenames);
3520     }
3521     return $alternatenames;
3524 /**
3525  * Reduces lines of duplicated code for getting user name fields.
3526  *
3527  * See also {@link user_picture::unalias()}
3528  *
3529  * @param object $addtoobject Object to add user name fields to.
3530  * @param object $secondobject Object that contains user name field information.
3531  * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3532  * @param array $additionalfields Additional fields to be matched with data in the second object.
3533  * The key can be set to the user table field name.
3534  * @return object User name fields.
3535  */
3536 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3537     $fields = get_all_user_name_fields(false, null, $prefix);
3538     if ($additionalfields) {
3539         // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3540         // the key is a number and then sets the key to the array value.
3541         foreach ($additionalfields as $key => $value) {
3542             if (is_numeric($key)) {
3543                 $additionalfields[$value] = $prefix . $value;
3544                 unset($additionalfields[$key]);
3545             } else {
3546                 $additionalfields[$key] = $prefix . $value;
3547             }
3548         }
3549         $fields = array_merge($fields, $additionalfields);
3550     }
3551     foreach ($fields as $key => $field) {
3552         // Important that we have all of the user name fields present in the object that we are sending back.
3553         $addtoobject->$key = '';
3554         if (isset($secondobject->$field)) {
3555             $addtoobject->$key = $secondobject->$field;
3556         }
3557     }
3558     return $addtoobject;
3561 /**
3562  * Returns an array of values in order of occurance in a provided string.
3563  * The key in the result is the character postion in the string.
3564  *
3565  * @param array $values Values to be found in the string format
3566  * @param string $stringformat The string which may contain values being searched for.
3567  * @return array An array of values in order according to placement in the string format.
3568  */
3569 function order_in_string($values, $stringformat) {
3570     $valuearray = array();
3571     foreach ($values as $value) {
3572         $pattern = "/$value\b/";
3573         // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3574         if (preg_match($pattern, $stringformat)) {
3575             $replacement = "thing";
3576             // Replace the value with something more unique to ensure we get the right position when using strpos().
3577             $newformat = preg_replace($pattern, $replacement, $stringformat);
3578             $position = strpos($newformat, $replacement);
3579             $valuearray[$position] = $value;
3580         }
3581     }
3582     ksort($valuearray);
3583     return $valuearray;
3586 /**
3587  * Checks if current user is shown any extra fields when listing users.
3588  *
3589  * @param object $context Context
3590  * @param array $already Array of fields that we're going to show anyway
3591  *   so don't bother listing them
3592  * @return array Array of field names from user table, not including anything
3593  *   listed in $already
3594  */
3595 function get_extra_user_fields($context, $already = array()) {
3596     global $CFG;
3598     // Only users with permission get the extra fields.
3599     if (!has_capability('moodle/site:viewuseridentity', $context)) {
3600         return array();
3601     }
3603     // Split showuseridentity on comma.
3604     if (empty($CFG->showuseridentity)) {
3605         // Explode gives wrong result with empty string.
3606         $extra = array();
3607     } else {
3608         $extra =  explode(',', $CFG->showuseridentity);
3609     }
3610     $renumber = false;
3611     foreach ($extra as $key => $field) {
3612         if (in_array($field, $already)) {
3613             unset($extra[$key]);
3614             $renumber = true;
3615         }
3616     }
3617     if ($renumber) {
3618         // For consistency, if entries are removed from array, renumber it
3619         // so they are numbered as you would expect.
3620         $extra = array_merge($extra);
3621     }
3622     return $extra;
3625 /**
3626  * If the current user is to be shown extra user fields when listing or
3627  * selecting users, returns a string suitable for including in an SQL select
3628  * clause to retrieve those fields.
3629  *
3630  * @param context $context Context
3631  * @param string $alias Alias of user table, e.g. 'u' (default none)
3632  * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3633  * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3634  * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3635  */
3636 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3637     $fields = get_extra_user_fields($context, $already);
3638     $result = '';
3639     // Add punctuation for alias.
3640     if ($alias !== '') {
3641         $alias .= '.';
3642     }
3643     foreach ($fields as $field) {
3644         $result .= ', ' . $alias . $field;