Merge branch 'mdl-46427-master' of git://github.com/deraadt/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', 'radius', 'paypal', 'completionstatus'.
321  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322  * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
323  */
324 define('PARAM_PLUGIN', 'plugin');
327 // Web Services.
329 /**
330  * VALUE_REQUIRED - if the parameter is not supplied, there is an error
331  */
332 define('VALUE_REQUIRED', 1);
334 /**
335  * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
336  */
337 define('VALUE_OPTIONAL', 2);
339 /**
340  * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
341  */
342 define('VALUE_DEFAULT', 0);
344 /**
345  * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
346  */
347 define('NULL_NOT_ALLOWED', false);
349 /**
350  * NULL_ALLOWED - the parameter can be set to null in the database
351  */
352 define('NULL_ALLOWED', true);
354 // Page types.
356 /**
357  * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
358  */
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
374 // Tag constants.
375 /**
376  * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377  * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378  * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
379  *
380  * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
381  */
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True if module supports outcomes */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
417 /** True if module supports groupmembersonly */
418 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
420 /** Type of module */
421 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
422 /** True if module supports intro editor */
423 define('FEATURE_MOD_INTRO', 'mod_intro');
424 /** True if module has default completion */
425 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
427 define('FEATURE_COMMENT', 'comment');
429 define('FEATURE_RATE', 'rate');
430 /** True if module supports backup/restore of moodle2 format */
431 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
433 /** True if module can show description on course main page */
434 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
436 /** True if module uses the question bank */
437 define('FEATURE_USES_QUESTIONS', 'usesquestions');
439 /** Unspecified module archetype */
440 define('MOD_ARCHETYPE_OTHER', 0);
441 /** Resource-like type module */
442 define('MOD_ARCHETYPE_RESOURCE', 1);
443 /** Assignment module archetype */
444 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
445 /** System (not user-addable) module archetype */
446 define('MOD_ARCHETYPE_SYSTEM', 3);
448 /** Return this from modname_get_types callback to use default display in activity chooser */
449 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
451 /**
452  * Security token used for allowing access
453  * from external application such as web services.
454  * Scripts do not use any session, performance is relatively
455  * low because we need to load access info in each request.
456  * Scripts are executed in parallel.
457  */
458 define('EXTERNAL_TOKEN_PERMANENT', 0);
460 /**
461  * Security token used for allowing access
462  * of embedded applications, the code is executed in the
463  * active user session. Token is invalidated after user logs out.
464  * Scripts are executed serially - normal session locking is used.
465  */
466 define('EXTERNAL_TOKEN_EMBEDDED', 1);
468 /**
469  * The home page should be the site home
470  */
471 define('HOMEPAGE_SITE', 0);
472 /**
473  * The home page should be the users my page
474  */
475 define('HOMEPAGE_MY', 1);
476 /**
477  * The home page can be chosen by the user
478  */
479 define('HOMEPAGE_USER', 2);
481 /**
482  * Hub directory url (should be moodle.org)
483  */
484 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
487 /**
488  * Moodle.org url (should be moodle.org)
489  */
490 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
492 /**
493  * Moodle mobile app service name
494  */
495 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
497 /**
498  * Indicates the user has the capabilities required to ignore activity and course file size restrictions
499  */
500 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
502 /**
503  * Course display settings: display all sections on one page.
504  */
505 define('COURSE_DISPLAY_SINGLEPAGE', 0);
506 /**
507  * Course display settings: split pages into a page per section.
508  */
509 define('COURSE_DISPLAY_MULTIPAGE', 1);
511 /**
512  * Authentication constant: String used in password field when password is not stored.
513  */
514 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
516 // PARAMETER HANDLING.
518 /**
519  * Returns a particular value for the named variable, taken from
520  * POST or GET.  If the parameter doesn't exist then an error is
521  * thrown because we require this variable.
522  *
523  * This function should be used to initialise all required values
524  * in a script that are based on parameters.  Usually it will be
525  * used like this:
526  *    $id = required_param('id', PARAM_INT);
527  *
528  * Please note the $type parameter is now required and the value can not be array.
529  *
530  * @param string $parname the name of the page parameter we want
531  * @param string $type expected type of parameter
532  * @return mixed
533  * @throws coding_exception
534  */
535 function required_param($parname, $type) {
536     if (func_num_args() != 2 or empty($parname) or empty($type)) {
537         throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
538     }
539     // POST has precedence.
540     if (isset($_POST[$parname])) {
541         $param = $_POST[$parname];
542     } else if (isset($_GET[$parname])) {
543         $param = $_GET[$parname];
544     } else {
545         print_error('missingparam', '', '', $parname);
546     }
548     if (is_array($param)) {
549         debugging('Invalid array parameter detected in required_param(): '.$parname);
550         // TODO: switch to fatal error in Moodle 2.3.
551         return required_param_array($parname, $type);
552     }
554     return clean_param($param, $type);
557 /**
558  * Returns a particular array value for the named variable, taken from
559  * POST or GET.  If the parameter doesn't exist then an error is
560  * thrown because we require this variable.
561  *
562  * This function should be used to initialise all required values
563  * in a script that are based on parameters.  Usually it will be
564  * used like this:
565  *    $ids = required_param_array('ids', PARAM_INT);
566  *
567  *  Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
568  *
569  * @param string $parname the name of the page parameter we want
570  * @param string $type expected type of parameter
571  * @return array
572  * @throws coding_exception
573  */
574 function required_param_array($parname, $type) {
575     if (func_num_args() != 2 or empty($parname) or empty($type)) {
576         throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
577     }
578     // POST has precedence.
579     if (isset($_POST[$parname])) {
580         $param = $_POST[$parname];
581     } else if (isset($_GET[$parname])) {
582         $param = $_GET[$parname];
583     } else {
584         print_error('missingparam', '', '', $parname);
585     }
586     if (!is_array($param)) {
587         print_error('missingparam', '', '', $parname);
588     }
590     $result = array();
591     foreach ($param as $key => $value) {
592         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
593             debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
594             continue;
595         }
596         $result[$key] = clean_param($value, $type);
597     }
599     return $result;
602 /**
603  * Returns a particular value for the named variable, taken from
604  * POST or GET, otherwise returning a given default.
605  *
606  * This function should be used to initialise all optional values
607  * in a script that are based on parameters.  Usually it will be
608  * used like this:
609  *    $name = optional_param('name', 'Fred', PARAM_TEXT);
610  *
611  * Please note the $type parameter is now required and the value can not be array.
612  *
613  * @param string $parname the name of the page parameter we want
614  * @param mixed  $default the default value to return if nothing is found
615  * @param string $type expected type of parameter
616  * @return mixed
617  * @throws coding_exception
618  */
619 function optional_param($parname, $default, $type) {
620     if (func_num_args() != 3 or empty($parname) or empty($type)) {
621         throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
622     }
623     if (!isset($default)) {
624         $default = null;
625     }
627     // POST has precedence.
628     if (isset($_POST[$parname])) {
629         $param = $_POST[$parname];
630     } else if (isset($_GET[$parname])) {
631         $param = $_GET[$parname];
632     } else {
633         return $default;
634     }
636     if (is_array($param)) {
637         debugging('Invalid array parameter detected in required_param(): '.$parname);
638         // TODO: switch to $default in Moodle 2.3.
639         return optional_param_array($parname, $default, $type);
640     }
642     return clean_param($param, $type);
645 /**
646  * Returns a particular array value for the named variable, taken from
647  * POST or GET, otherwise returning a given default.
648  *
649  * This function should be used to initialise all optional values
650  * in a script that are based on parameters.  Usually it will be
651  * used like this:
652  *    $ids = optional_param('id', array(), PARAM_INT);
653  *
654  * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
655  *
656  * @param string $parname the name of the page parameter we want
657  * @param mixed $default the default value to return if nothing is found
658  * @param string $type expected type of parameter
659  * @return array
660  * @throws coding_exception
661  */
662 function optional_param_array($parname, $default, $type) {
663     if (func_num_args() != 3 or empty($parname) or empty($type)) {
664         throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
665     }
667     // POST has precedence.
668     if (isset($_POST[$parname])) {
669         $param = $_POST[$parname];
670     } else if (isset($_GET[$parname])) {
671         $param = $_GET[$parname];
672     } else {
673         return $default;
674     }
675     if (!is_array($param)) {
676         debugging('optional_param_array() expects array parameters only: '.$parname);
677         return $default;
678     }
680     $result = array();
681     foreach ($param as $key => $value) {
682         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
683             debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
684             continue;
685         }
686         $result[$key] = clean_param($value, $type);
687     }
689     return $result;
692 /**
693  * Strict validation of parameter values, the values are only converted
694  * to requested PHP type. Internally it is using clean_param, the values
695  * before and after cleaning must be equal - otherwise
696  * an invalid_parameter_exception is thrown.
697  * Objects and classes are not accepted.
698  *
699  * @param mixed $param
700  * @param string $type PARAM_ constant
701  * @param bool $allownull are nulls valid value?
702  * @param string $debuginfo optional debug information
703  * @return mixed the $param value converted to PHP type
704  * @throws invalid_parameter_exception if $param is not of given type
705  */
706 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
707     if (is_null($param)) {
708         if ($allownull == NULL_ALLOWED) {
709             return null;
710         } else {
711             throw new invalid_parameter_exception($debuginfo);
712         }
713     }
714     if (is_array($param) or is_object($param)) {
715         throw new invalid_parameter_exception($debuginfo);
716     }
718     $cleaned = clean_param($param, $type);
720     if ($type == PARAM_FLOAT) {
721         // Do not detect precision loss here.
722         if (is_float($param) or is_int($param)) {
723             // These always fit.
724         } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
725             throw new invalid_parameter_exception($debuginfo);
726         }
727     } else if ((string)$param !== (string)$cleaned) {
728         // Conversion to string is usually lossless.
729         throw new invalid_parameter_exception($debuginfo);
730     }
732     return $cleaned;
735 /**
736  * Makes sure array contains only the allowed types, this function does not validate array key names!
737  *
738  * <code>
739  * $options = clean_param($options, PARAM_INT);
740  * </code>
741  *
742  * @param array $param the variable array we are cleaning
743  * @param string $type expected format of param after cleaning.
744  * @param bool $recursive clean recursive arrays
745  * @return array
746  * @throws coding_exception
747  */
748 function clean_param_array(array $param = null, $type, $recursive = false) {
749     // Convert null to empty array.
750     $param = (array)$param;
751     foreach ($param as $key => $value) {
752         if (is_array($value)) {
753             if ($recursive) {
754                 $param[$key] = clean_param_array($value, $type, true);
755             } else {
756                 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
757             }
758         } else {
759             $param[$key] = clean_param($value, $type);
760         }
761     }
762     return $param;
765 /**
766  * Used by {@link optional_param()} and {@link required_param()} to
767  * clean the variables and/or cast to specific types, based on
768  * an options field.
769  * <code>
770  * $course->format = clean_param($course->format, PARAM_ALPHA);
771  * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
772  * </code>
773  *
774  * @param mixed $param the variable we are cleaning
775  * @param string $type expected format of param after cleaning.
776  * @return mixed
777  * @throws coding_exception
778  */
779 function clean_param($param, $type) {
780     global $CFG;
782     if (is_array($param)) {
783         throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
784     } else if (is_object($param)) {
785         if (method_exists($param, '__toString')) {
786             $param = $param->__toString();
787         } else {
788             throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
789         }
790     }
792     switch ($type) {
793         case PARAM_RAW:
794             // No cleaning at all.
795             $param = fix_utf8($param);
796             return $param;
798         case PARAM_RAW_TRIMMED:
799             // No cleaning, but strip leading and trailing whitespace.
800             $param = fix_utf8($param);
801             return trim($param);
803         case PARAM_CLEAN:
804             // General HTML cleaning, try to use more specific type if possible this is deprecated!
805             // Please use more specific type instead.
806             if (is_numeric($param)) {
807                 return $param;
808             }
809             $param = fix_utf8($param);
810             // Sweep for scripts, etc.
811             return clean_text($param);
813         case PARAM_CLEANHTML:
814             // Clean html fragment.
815             $param = fix_utf8($param);
816             // Sweep for scripts, etc.
817             $param = clean_text($param, FORMAT_HTML);
818             return trim($param);
820         case PARAM_INT:
821             // Convert to integer.
822             return (int)$param;
824         case PARAM_FLOAT:
825             // Convert to float.
826             return (float)$param;
828         case PARAM_ALPHA:
829             // Remove everything not `a-z`.
830             return preg_replace('/[^a-zA-Z]/i', '', $param);
832         case PARAM_ALPHAEXT:
833             // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
834             return preg_replace('/[^a-zA-Z_-]/i', '', $param);
836         case PARAM_ALPHANUM:
837             // Remove everything not `a-zA-Z0-9`.
838             return preg_replace('/[^A-Za-z0-9]/i', '', $param);
840         case PARAM_ALPHANUMEXT:
841             // Remove everything not `a-zA-Z0-9_-`.
842             return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
844         case PARAM_SEQUENCE:
845             // Remove everything not `0-9,`.
846             return preg_replace('/[^0-9,]/i', '', $param);
848         case PARAM_BOOL:
849             // Convert to 1 or 0.
850             $tempstr = strtolower($param);
851             if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
852                 $param = 1;
853             } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
854                 $param = 0;
855             } else {
856                 $param = empty($param) ? 0 : 1;
857             }
858             return $param;
860         case PARAM_NOTAGS:
861             // Strip all tags.
862             $param = fix_utf8($param);
863             return strip_tags($param);
865         case PARAM_TEXT:
866             // Leave only tags needed for multilang.
867             $param = fix_utf8($param);
868             // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
869             // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
870             do {
871                 if (strpos($param, '</lang>') !== false) {
872                     // Old and future mutilang syntax.
873                     $param = strip_tags($param, '<lang>');
874                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
875                         break;
876                     }
877                     $open = false;
878                     foreach ($matches[0] as $match) {
879                         if ($match === '</lang>') {
880                             if ($open) {
881                                 $open = false;
882                                 continue;
883                             } else {
884                                 break 2;
885                             }
886                         }
887                         if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
888                             break 2;
889                         } else {
890                             $open = true;
891                         }
892                     }
893                     if ($open) {
894                         break;
895                     }
896                     return $param;
898                 } else if (strpos($param, '</span>') !== false) {
899                     // Current problematic multilang syntax.
900                     $param = strip_tags($param, '<span>');
901                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
902                         break;
903                     }
904                     $open = false;
905                     foreach ($matches[0] as $match) {
906                         if ($match === '</span>') {
907                             if ($open) {
908                                 $open = false;
909                                 continue;
910                             } else {
911                                 break 2;
912                             }
913                         }
914                         if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
915                             break 2;
916                         } else {
917                             $open = true;
918                         }
919                     }
920                     if ($open) {
921                         break;
922                     }
923                     return $param;
924                 }
925             } while (false);
926             // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
927             return strip_tags($param);
929         case PARAM_COMPONENT:
930             // We do not want any guessing here, either the name is correct or not
931             // please note only normalised component names are accepted.
932             if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
933                 return '';
934             }
935             if (strpos($param, '__') !== false) {
936                 return '';
937             }
938             if (strpos($param, 'mod_') === 0) {
939                 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
940                 if (substr_count($param, '_') != 1) {
941                     return '';
942                 }
943             }
944             return $param;
946         case PARAM_PLUGIN:
947         case PARAM_AREA:
948             // We do not want any guessing here, either the name is correct or not.
949             if (!is_valid_plugin_name($param)) {
950                 return '';
951             }
952             return $param;
954         case PARAM_SAFEDIR:
955             // Remove everything not a-zA-Z0-9_- .
956             return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
958         case PARAM_SAFEPATH:
959             // Remove everything not a-zA-Z0-9/_- .
960             return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
962         case PARAM_FILE:
963             // Strip all suspicious characters from filename.
964             $param = fix_utf8($param);
965             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
966             if ($param === '.' || $param === '..') {
967                 $param = '';
968             }
969             return $param;
971         case PARAM_PATH:
972             // Strip all suspicious characters from file path.
973             $param = fix_utf8($param);
974             $param = str_replace('\\', '/', $param);
976             // Explode the path and clean each element using the PARAM_FILE rules.
977             $breadcrumb = explode('/', $param);
978             foreach ($breadcrumb as $key => $crumb) {
979                 if ($crumb === '.' && $key === 0) {
980                     // Special condition to allow for relative current path such as ./currentdirfile.txt.
981                 } else {
982                     $crumb = clean_param($crumb, PARAM_FILE);
983                 }
984                 $breadcrumb[$key] = $crumb;
985             }
986             $param = implode('/', $breadcrumb);
988             // Remove multiple current path (./././) and multiple slashes (///).
989             $param = preg_replace('~//+~', '/', $param);
990             $param = preg_replace('~/(\./)+~', '/', $param);
991             return $param;
993         case PARAM_HOST:
994             // Allow FQDN or IPv4 dotted quad.
995             $param = preg_replace('/[^\.\d\w-]/', '', $param );
996             // Match ipv4 dotted quad.
997             if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
998                 // Confirm values are ok.
999                 if ( $match[0] > 255
1000                      || $match[1] > 255
1001                      || $match[3] > 255
1002                      || $match[4] > 255 ) {
1003                     // Hmmm, what kind of dotted quad is this?
1004                     $param = '';
1005                 }
1006             } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1007                        && !preg_match('/^[\.-]/',  $param) // No leading dots/hyphens.
1008                        && !preg_match('/[\.-]$/',  $param) // No trailing dots/hyphens.
1009                        ) {
1010                 // All is ok - $param is respected.
1011             } else {
1012                 // All is not ok...
1013                 $param='';
1014             }
1015             return $param;
1017         case PARAM_URL:          // Allow safe ftp, http, mailto urls.
1018             $param = fix_utf8($param);
1019             include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1020             if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1021                 // All is ok, param is respected.
1022             } else {
1023                 // Not really ok.
1024                 $param ='';
1025             }
1026             return $param;
1028         case PARAM_LOCALURL:
1029             // Allow http absolute, root relative and relative URLs within wwwroot.
1030             $param = clean_param($param, PARAM_URL);
1031             if (!empty($param)) {
1032                 if (preg_match(':^/:', $param)) {
1033                     // Root-relative, ok!
1034                 } else if (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i', $param)) {
1035                     // Absolute, and matches our wwwroot.
1036                 } else {
1037                     // Relative - let's make sure there are no tricks.
1038                     if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1039                         // Looks ok.
1040                     } else {
1041                         $param = '';
1042                     }
1043                 }
1044             }
1045             return $param;
1047         case PARAM_PEM:
1048             $param = trim($param);
1049             // PEM formatted strings may contain letters/numbers and the symbols:
1050             //   forward slash: /
1051             //   plus sign:     +
1052             //   equal sign:    =
1053             //   , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1054             if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1055                 list($wholething, $body) = $matches;
1056                 unset($wholething, $matches);
1057                 $b64 = clean_param($body, PARAM_BASE64);
1058                 if (!empty($b64)) {
1059                     return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1060                 } else {
1061                     return '';
1062                 }
1063             }
1064             return '';
1066         case PARAM_BASE64:
1067             if (!empty($param)) {
1068                 // PEM formatted strings may contain letters/numbers and the symbols
1069                 //   forward slash: /
1070                 //   plus sign:     +
1071                 //   equal sign:    =.
1072                 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1073                     return '';
1074                 }
1075                 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1076                 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1077                 // than (or equal to) 64 characters long.
1078                 for ($i=0, $j=count($lines); $i < $j; $i++) {
1079                     if ($i + 1 == $j) {
1080                         if (64 < strlen($lines[$i])) {
1081                             return '';
1082                         }
1083                         continue;
1084                     }
1086                     if (64 != strlen($lines[$i])) {
1087                         return '';
1088                     }
1089                 }
1090                 return implode("\n", $lines);
1091             } else {
1092                 return '';
1093             }
1095         case PARAM_TAG:
1096             $param = fix_utf8($param);
1097             // Please note it is not safe to use the tag name directly anywhere,
1098             // it must be processed with s(), urlencode() before embedding anywhere.
1099             // Remove some nasties.
1100             $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1101             // Convert many whitespace chars into one.
1102             $param = preg_replace('/\s+/', ' ', $param);
1103             $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1104             return $param;
1106         case PARAM_TAGLIST:
1107             $param = fix_utf8($param);
1108             $tags = explode(',', $param);
1109             $result = array();
1110             foreach ($tags as $tag) {
1111                 $res = clean_param($tag, PARAM_TAG);
1112                 if ($res !== '') {
1113                     $result[] = $res;
1114                 }
1115             }
1116             if ($result) {
1117                 return implode(',', $result);
1118             } else {
1119                 return '';
1120             }
1122         case PARAM_CAPABILITY:
1123             if (get_capability_info($param)) {
1124                 return $param;
1125             } else {
1126                 return '';
1127             }
1129         case PARAM_PERMISSION:
1130             $param = (int)$param;
1131             if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1132                 return $param;
1133             } else {
1134                 return CAP_INHERIT;
1135             }
1137         case PARAM_AUTH:
1138             $param = clean_param($param, PARAM_PLUGIN);
1139             if (empty($param)) {
1140                 return '';
1141             } else if (exists_auth_plugin($param)) {
1142                 return $param;
1143             } else {
1144                 return '';
1145             }
1147         case PARAM_LANG:
1148             $param = clean_param($param, PARAM_SAFEDIR);
1149             if (get_string_manager()->translation_exists($param)) {
1150                 return $param;
1151             } else {
1152                 // Specified language is not installed or param malformed.
1153                 return '';
1154             }
1156         case PARAM_THEME:
1157             $param = clean_param($param, PARAM_PLUGIN);
1158             if (empty($param)) {
1159                 return '';
1160             } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1161                 return $param;
1162             } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1163                 return $param;
1164             } else {
1165                 // Specified theme is not installed.
1166                 return '';
1167             }
1169         case PARAM_USERNAME:
1170             $param = fix_utf8($param);
1171             $param = str_replace(" " , "", $param);
1172             // Convert uppercase to lowercase MDL-16919.
1173             $param = core_text::strtolower($param);
1174             if (empty($CFG->extendedusernamechars)) {
1175                 // Regular expression, eliminate all chars EXCEPT:
1176                 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1177                 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1178             }
1179             return $param;
1181         case PARAM_EMAIL:
1182             $param = fix_utf8($param);
1183             if (validate_email($param)) {
1184                 return $param;
1185             } else {
1186                 return '';
1187             }
1189         case PARAM_STRINGID:
1190             if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1191                 return $param;
1192             } else {
1193                 return '';
1194             }
1196         case PARAM_TIMEZONE:
1197             // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1198             $param = fix_utf8($param);
1199             $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1200             if (preg_match($timezonepattern, $param)) {
1201                 return $param;
1202             } else {
1203                 return '';
1204             }
1206         default:
1207             // Doh! throw error, switched parameters in optional_param or another serious problem.
1208             print_error("unknownparamtype", '', '', $type);
1209     }
1212 /**
1213  * Makes sure the data is using valid utf8, invalid characters are discarded.
1214  *
1215  * Note: this function is not intended for full objects with methods and private properties.
1216  *
1217  * @param mixed $value
1218  * @return mixed with proper utf-8 encoding
1219  */
1220 function fix_utf8($value) {
1221     if (is_null($value) or $value === '') {
1222         return $value;
1224     } else if (is_string($value)) {
1225         if ((string)(int)$value === $value) {
1226             // Shortcut.
1227             return $value;
1228         }
1229         // No null bytes expected in our data, so let's remove it.
1230         $value = str_replace("\0", '', $value);
1232         // Note: this duplicates min_fix_utf8() intentionally.
1233         static $buggyiconv = null;
1234         if ($buggyiconv === null) {
1235             $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1236         }
1238         if ($buggyiconv) {
1239             if (function_exists('mb_convert_encoding')) {
1240                 $subst = mb_substitute_character();
1241                 mb_substitute_character('');
1242                 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1243                 mb_substitute_character($subst);
1245             } else {
1246                 // Warn admins on admin/index.php page.
1247                 $result = $value;
1248             }
1250         } else {
1251             $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1252         }
1254         return $result;
1256     } else if (is_array($value)) {
1257         foreach ($value as $k => $v) {
1258             $value[$k] = fix_utf8($v);
1259         }
1260         return $value;
1262     } else if (is_object($value)) {
1263         // Do not modify original.
1264         $value = clone($value);
1265         foreach ($value as $k => $v) {
1266             $value->$k = fix_utf8($v);
1267         }
1268         return $value;
1270     } else {
1271         // This is some other type, no utf-8 here.
1272         return $value;
1273     }
1276 /**
1277  * Return true if given value is integer or string with integer value
1278  *
1279  * @param mixed $value String or Int
1280  * @return bool true if number, false if not
1281  */
1282 function is_number($value) {
1283     if (is_int($value)) {
1284         return true;
1285     } else if (is_string($value)) {
1286         return ((string)(int)$value) === $value;
1287     } else {
1288         return false;
1289     }
1292 /**
1293  * Returns host part from url.
1294  *
1295  * @param string $url full url
1296  * @return string host, null if not found
1297  */
1298 function get_host_from_url($url) {
1299     preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1300     if ($matches) {
1301         return $matches[1];
1302     }
1303     return null;
1306 /**
1307  * Tests whether anything was returned by text editor
1308  *
1309  * This function is useful for testing whether something you got back from
1310  * the HTML editor actually contains anything. Sometimes the HTML editor
1311  * appear to be empty, but actually you get back a <br> tag or something.
1312  *
1313  * @param string $string a string containing HTML.
1314  * @return boolean does the string contain any actual content - that is text,
1315  * images, objects, etc.
1316  */
1317 function html_is_blank($string) {
1318     return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1321 /**
1322  * Set a key in global configuration
1323  *
1324  * Set a key/value pair in both this session's {@link $CFG} global variable
1325  * and in the 'config' database table for future sessions.
1326  *
1327  * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1328  * In that case it doesn't affect $CFG.
1329  *
1330  * A NULL value will delete the entry.
1331  *
1332  * NOTE: this function is called from lib/db/upgrade.php
1333  *
1334  * @param string $name the key to set
1335  * @param string $value the value to set (without magic quotes)
1336  * @param string $plugin (optional) the plugin scope, default null
1337  * @return bool true or exception
1338  */
1339 function set_config($name, $value, $plugin=null) {
1340     global $CFG, $DB;
1342     if (empty($plugin)) {
1343         if (!array_key_exists($name, $CFG->config_php_settings)) {
1344             // So it's defined for this invocation at least.
1345             if (is_null($value)) {
1346                 unset($CFG->$name);
1347             } else {
1348                 // Settings from db are always strings.
1349                 $CFG->$name = (string)$value;
1350             }
1351         }
1353         if ($DB->get_field('config', 'name', array('name' => $name))) {
1354             if ($value === null) {
1355                 $DB->delete_records('config', array('name' => $name));
1356             } else {
1357                 $DB->set_field('config', 'value', $value, array('name' => $name));
1358             }
1359         } else {
1360             if ($value !== null) {
1361                 $config = new stdClass();
1362                 $config->name  = $name;
1363                 $config->value = $value;
1364                 $DB->insert_record('config', $config, false);
1365             }
1366         }
1367         if ($name === 'siteidentifier') {
1368             cache_helper::update_site_identifier($value);
1369         }
1370         cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1371     } else {
1372         // Plugin scope.
1373         if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1374             if ($value===null) {
1375                 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1376             } else {
1377                 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1378             }
1379         } else {
1380             if ($value !== null) {
1381                 $config = new stdClass();
1382                 $config->plugin = $plugin;
1383                 $config->name   = $name;
1384                 $config->value  = $value;
1385                 $DB->insert_record('config_plugins', $config, false);
1386             }
1387         }
1388         cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1389     }
1391     return true;
1394 /**
1395  * Get configuration values from the global config table
1396  * or the config_plugins table.
1397  *
1398  * If called with one parameter, it will load all the config
1399  * variables for one plugin, and return them as an object.
1400  *
1401  * If called with 2 parameters it will return a string single
1402  * value or false if the value is not found.
1403  *
1404  * NOTE: this function is called from lib/db/upgrade.php
1405  *
1406  * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1407  *     that we need only fetch it once per request.
1408  * @param string $plugin full component name
1409  * @param string $name default null
1410  * @return mixed hash-like object or single value, return false no config found
1411  * @throws dml_exception
1412  */
1413 function get_config($plugin, $name = null) {
1414     global $CFG, $DB;
1416     static $siteidentifier = null;
1418     if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1419         $forced =& $CFG->config_php_settings;
1420         $iscore = true;
1421         $plugin = 'core';
1422     } else {
1423         if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1424             $forced =& $CFG->forced_plugin_settings[$plugin];
1425         } else {
1426             $forced = array();
1427         }
1428         $iscore = false;
1429     }
1431     if ($siteidentifier === null) {
1432         try {
1433             // This may fail during installation.
1434             // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1435             // install the database.
1436             $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1437         } catch (dml_exception $ex) {
1438             // Set siteidentifier to false. We don't want to trip this continually.
1439             $siteidentifier = false;
1440             throw $ex;
1441         }
1442     }
1444     if (!empty($name)) {
1445         if (array_key_exists($name, $forced)) {
1446             return (string)$forced[$name];
1447         } else if ($name === 'siteidentifier' && $plugin == 'core') {
1448             return $siteidentifier;
1449         }
1450     }
1452     $cache = cache::make('core', 'config');
1453     $result = $cache->get($plugin);
1454     if ($result === false) {
1455         // The user is after a recordset.
1456         if (!$iscore) {
1457             $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1458         } else {
1459             // This part is not really used any more, but anyway...
1460             $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1461         }
1462         $cache->set($plugin, $result);
1463     }
1465     if (!empty($name)) {
1466         if (array_key_exists($name, $result)) {
1467             return $result[$name];
1468         }
1469         return false;
1470     }
1472     if ($plugin === 'core') {
1473         $result['siteidentifier'] = $siteidentifier;
1474     }
1476     foreach ($forced as $key => $value) {
1477         if (is_null($value) or is_array($value) or is_object($value)) {
1478             // We do not want any extra mess here, just real settings that could be saved in db.
1479             unset($result[$key]);
1480         } else {
1481             // Convert to string as if it went through the DB.
1482             $result[$key] = (string)$value;
1483         }
1484     }
1486     return (object)$result;
1489 /**
1490  * Removes a key from global configuration.
1491  *
1492  * NOTE: this function is called from lib/db/upgrade.php
1493  *
1494  * @param string $name the key to set
1495  * @param string $plugin (optional) the plugin scope
1496  * @return boolean whether the operation succeeded.
1497  */
1498 function unset_config($name, $plugin=null) {
1499     global $CFG, $DB;
1501     if (empty($plugin)) {
1502         unset($CFG->$name);
1503         $DB->delete_records('config', array('name' => $name));
1504         cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1505     } else {
1506         $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1507         cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1508     }
1510     return true;
1513 /**
1514  * Remove all the config variables for a given plugin.
1515  *
1516  * NOTE: this function is called from lib/db/upgrade.php
1517  *
1518  * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1519  * @return boolean whether the operation succeeded.
1520  */
1521 function unset_all_config_for_plugin($plugin) {
1522     global $DB;
1523     // Delete from the obvious config_plugins first.
1524     $DB->delete_records('config_plugins', array('plugin' => $plugin));
1525     // Next delete any suspect settings from config.
1526     $like = $DB->sql_like('name', '?', true, true, false, '|');
1527     $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1528     $DB->delete_records_select('config', $like, $params);
1529     // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1530     cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1532     return true;
1535 /**
1536  * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1537  *
1538  * All users are verified if they still have the necessary capability.
1539  *
1540  * @param string $value the value of the config setting.
1541  * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1542  * @param bool $includeadmins include administrators.
1543  * @return array of user objects.
1544  */
1545 function get_users_from_config($value, $capability, $includeadmins = true) {
1546     if (empty($value) or $value === '$@NONE@$') {
1547         return array();
1548     }
1550     // We have to make sure that users still have the necessary capability,
1551     // it should be faster to fetch them all first and then test if they are present
1552     // instead of validating them one-by-one.
1553     $users = get_users_by_capability(context_system::instance(), $capability);
1554     if ($includeadmins) {
1555         $admins = get_admins();
1556         foreach ($admins as $admin) {
1557             $users[$admin->id] = $admin;
1558         }
1559     }
1561     if ($value === '$@ALL@$') {
1562         return $users;
1563     }
1565     $result = array(); // Result in correct order.
1566     $allowed = explode(',', $value);
1567     foreach ($allowed as $uid) {
1568         if (isset($users[$uid])) {
1569             $user = $users[$uid];
1570             $result[$user->id] = $user;
1571         }
1572     }
1574     return $result;
1578 /**
1579  * Invalidates browser caches and cached data in temp.
1580  *
1581  * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1582  * {@link phpunit_util::reset_dataroot()}
1583  *
1584  * @return void
1585  */
1586 function purge_all_caches() {
1587     global $CFG, $DB;
1589     reset_text_filters_cache();
1590     js_reset_all_caches();
1591     theme_reset_all_caches();
1592     get_string_manager()->reset_caches();
1593     core_text::reset_caches();
1594     if (class_exists('core_plugin_manager')) {
1595         core_plugin_manager::reset_caches();
1596     }
1598     // Bump up cacherev field for all courses.
1599     try {
1600         increment_revision_number('course', 'cacherev', '');
1601     } catch (moodle_exception $e) {
1602         // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1603     }
1605     $DB->reset_caches();
1606     cache_helper::purge_all();
1608     // Purge all other caches: rss, simplepie, etc.
1609     remove_dir($CFG->cachedir.'', true);
1611     // Make sure cache dir is writable, throws exception if not.
1612     make_cache_directory('');
1614     // This is the only place where we purge local caches, we are only adding files there.
1615     // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1616     remove_dir($CFG->localcachedir, true);
1617     set_config('localcachedirpurged', time());
1618     make_localcache_directory('', true);
1619     \core\task\manager::clear_static_caches();
1622 /**
1623  * Get volatile flags
1624  *
1625  * @param string $type
1626  * @param int $changedsince default null
1627  * @return array records array
1628  */
1629 function get_cache_flags($type, $changedsince = null) {
1630     global $DB;
1632     $params = array('type' => $type, 'expiry' => time());
1633     $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1634     if ($changedsince !== null) {
1635         $params['changedsince'] = $changedsince;
1636         $sqlwhere .= " AND timemodified > :changedsince";
1637     }
1638     $cf = array();
1639     if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1640         foreach ($flags as $flag) {
1641             $cf[$flag->name] = $flag->value;
1642         }
1643     }
1644     return $cf;
1647 /**
1648  * Get volatile flags
1649  *
1650  * @param string $type
1651  * @param string $name
1652  * @param int $changedsince default null
1653  * @return string|false The cache flag value or false
1654  */
1655 function get_cache_flag($type, $name, $changedsince=null) {
1656     global $DB;
1658     $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1660     $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1661     if ($changedsince !== null) {
1662         $params['changedsince'] = $changedsince;
1663         $sqlwhere .= " AND timemodified > :changedsince";
1664     }
1666     return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1669 /**
1670  * Set a volatile flag
1671  *
1672  * @param string $type the "type" namespace for the key
1673  * @param string $name the key to set
1674  * @param string $value the value to set (without magic quotes) - null will remove the flag
1675  * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1676  * @return bool Always returns true
1677  */
1678 function set_cache_flag($type, $name, $value, $expiry = null) {
1679     global $DB;
1681     $timemodified = time();
1682     if ($expiry === null || $expiry < $timemodified) {
1683         $expiry = $timemodified + 24 * 60 * 60;
1684     } else {
1685         $expiry = (int)$expiry;
1686     }
1688     if ($value === null) {
1689         unset_cache_flag($type, $name);
1690         return true;
1691     }
1693     if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1694         // This is a potential problem in DEBUG_DEVELOPER.
1695         if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1696             return true; // No need to update.
1697         }
1698         $f->value        = $value;
1699         $f->expiry       = $expiry;
1700         $f->timemodified = $timemodified;
1701         $DB->update_record('cache_flags', $f);
1702     } else {
1703         $f = new stdClass();
1704         $f->flagtype     = $type;
1705         $f->name         = $name;
1706         $f->value        = $value;
1707         $f->expiry       = $expiry;
1708         $f->timemodified = $timemodified;
1709         $DB->insert_record('cache_flags', $f);
1710     }
1711     return true;
1714 /**
1715  * Removes a single volatile flag
1716  *
1717  * @param string $type the "type" namespace for the key
1718  * @param string $name the key to set
1719  * @return bool
1720  */
1721 function unset_cache_flag($type, $name) {
1722     global $DB;
1723     $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1724     return true;
1727 /**
1728  * Garbage-collect volatile flags
1729  *
1730  * @return bool Always returns true
1731  */
1732 function gc_cache_flags() {
1733     global $DB;
1734     $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1735     return true;
1738 // USER PREFERENCE API.
1740 /**
1741  * Refresh user preference cache. This is used most often for $USER
1742  * object that is stored in session, but it also helps with performance in cron script.
1743  *
1744  * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1745  *
1746  * @package  core
1747  * @category preference
1748  * @access   public
1749  * @param    stdClass         $user          User object. Preferences are preloaded into 'preference' property
1750  * @param    int              $cachelifetime Cache life time on the current page (in seconds)
1751  * @throws   coding_exception
1752  * @return   null
1753  */
1754 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1755     global $DB;
1756     // Static cache, we need to check on each page load, not only every 2 minutes.
1757     static $loadedusers = array();
1759     if (!isset($user->id)) {
1760         throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1761     }
1763     if (empty($user->id) or isguestuser($user->id)) {
1764         // No permanent storage for not-logged-in users and guest.
1765         if (!isset($user->preference)) {
1766             $user->preference = array();
1767         }
1768         return;
1769     }
1771     $timenow = time();
1773     if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1774         // Already loaded at least once on this page. Are we up to date?
1775         if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1776             // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1777             return;
1779         } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1780             // No change since the lastcheck on this page.
1781             $user->preference['_lastloaded'] = $timenow;
1782             return;
1783         }
1784     }
1786     // OK, so we have to reload all preferences.
1787     $loadedusers[$user->id] = true;
1788     $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1789     $user->preference['_lastloaded'] = $timenow;
1792 /**
1793  * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1794  *
1795  * NOTE: internal function, do not call from other code.
1796  *
1797  * @package core
1798  * @access private
1799  * @param integer $userid the user whose prefs were changed.
1800  */
1801 function mark_user_preferences_changed($userid) {
1802     global $CFG;
1804     if (empty($userid) or isguestuser($userid)) {
1805         // No cache flags for guest and not-logged-in users.
1806         return;
1807     }
1809     set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1812 /**
1813  * Sets a preference for the specified user.
1814  *
1815  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1816  *
1817  * @package  core
1818  * @category preference
1819  * @access   public
1820  * @param    string            $name  The key to set as preference for the specified user
1821  * @param    string            $value The value to set for the $name key in the specified user's
1822  *                                    record, null means delete current value.
1823  * @param    stdClass|int|null $user  A moodle user object or id, null means current user
1824  * @throws   coding_exception
1825  * @return   bool                     Always true or exception
1826  */
1827 function set_user_preference($name, $value, $user = null) {
1828     global $USER, $DB;
1830     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1831         throw new coding_exception('Invalid preference name in set_user_preference() call');
1832     }
1834     if (is_null($value)) {
1835         // Null means delete current.
1836         return unset_user_preference($name, $user);
1837     } else if (is_object($value)) {
1838         throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1839     } else if (is_array($value)) {
1840         throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1841     }
1842     // Value column maximum length is 1333 characters.
1843     $value = (string)$value;
1844     if (core_text::strlen($value) > 1333) {
1845         throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1846     }
1848     if (is_null($user)) {
1849         $user = $USER;
1850     } else if (isset($user->id)) {
1851         // It is a valid object.
1852     } else if (is_numeric($user)) {
1853         $user = (object)array('id' => (int)$user);
1854     } else {
1855         throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1856     }
1858     check_user_preferences_loaded($user);
1860     if (empty($user->id) or isguestuser($user->id)) {
1861         // No permanent storage for not-logged-in users and guest.
1862         $user->preference[$name] = $value;
1863         return true;
1864     }
1866     if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1867         if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1868             // Preference already set to this value.
1869             return true;
1870         }
1871         $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1873     } else {
1874         $preference = new stdClass();
1875         $preference->userid = $user->id;
1876         $preference->name   = $name;
1877         $preference->value  = $value;
1878         $DB->insert_record('user_preferences', $preference);
1879     }
1881     // Update value in cache.
1882     $user->preference[$name] = $value;
1884     // Set reload flag for other sessions.
1885     mark_user_preferences_changed($user->id);
1887     return true;
1890 /**
1891  * Sets a whole array of preferences for the current user
1892  *
1893  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1894  *
1895  * @package  core
1896  * @category preference
1897  * @access   public
1898  * @param    array             $prefarray An array of key/value pairs to be set
1899  * @param    stdClass|int|null $user      A moodle user object or id, null means current user
1900  * @return   bool                         Always true or exception
1901  */
1902 function set_user_preferences(array $prefarray, $user = null) {
1903     foreach ($prefarray as $name => $value) {
1904         set_user_preference($name, $value, $user);
1905     }
1906     return true;
1909 /**
1910  * Unsets a preference completely by deleting it from the database
1911  *
1912  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1913  *
1914  * @package  core
1915  * @category preference
1916  * @access   public
1917  * @param    string            $name The key to unset as preference for the specified user
1918  * @param    stdClass|int|null $user A moodle user object or id, null means current user
1919  * @throws   coding_exception
1920  * @return   bool                    Always true or exception
1921  */
1922 function unset_user_preference($name, $user = null) {
1923     global $USER, $DB;
1925     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1926         throw new coding_exception('Invalid preference name in unset_user_preference() call');
1927     }
1929     if (is_null($user)) {
1930         $user = $USER;
1931     } else if (isset($user->id)) {
1932         // It is a valid object.
1933     } else if (is_numeric($user)) {
1934         $user = (object)array('id' => (int)$user);
1935     } else {
1936         throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1937     }
1939     check_user_preferences_loaded($user);
1941     if (empty($user->id) or isguestuser($user->id)) {
1942         // No permanent storage for not-logged-in user and guest.
1943         unset($user->preference[$name]);
1944         return true;
1945     }
1947     // Delete from DB.
1948     $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1950     // Delete the preference from cache.
1951     unset($user->preference[$name]);
1953     // Set reload flag for other sessions.
1954     mark_user_preferences_changed($user->id);
1956     return true;
1959 /**
1960  * Used to fetch user preference(s)
1961  *
1962  * If no arguments are supplied this function will return
1963  * all of the current user preferences as an array.
1964  *
1965  * If a name is specified then this function
1966  * attempts to return that particular preference value.  If
1967  * none is found, then the optional value $default is returned,
1968  * otherwise null.
1969  *
1970  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1971  *
1972  * @package  core
1973  * @category preference
1974  * @access   public
1975  * @param    string            $name    Name of the key to use in finding a preference value
1976  * @param    mixed|null        $default Value to be returned if the $name key is not set in the user preferences
1977  * @param    stdClass|int|null $user    A moodle user object or id, null means current user
1978  * @throws   coding_exception
1979  * @return   string|mixed|null          A string containing the value of a single preference. An
1980  *                                      array with all of the preferences or null
1981  */
1982 function get_user_preferences($name = null, $default = null, $user = null) {
1983     global $USER;
1985     if (is_null($name)) {
1986         // All prefs.
1987     } else if (is_numeric($name) or $name === '_lastloaded') {
1988         throw new coding_exception('Invalid preference name in get_user_preferences() call');
1989     }
1991     if (is_null($user)) {
1992         $user = $USER;
1993     } else if (isset($user->id)) {
1994         // Is a valid object.
1995     } else if (is_numeric($user)) {
1996         $user = (object)array('id' => (int)$user);
1997     } else {
1998         throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1999     }
2001     check_user_preferences_loaded($user);
2003     if (empty($name)) {
2004         // All values.
2005         return $user->preference;
2006     } else if (isset($user->preference[$name])) {
2007         // The single string value.
2008         return $user->preference[$name];
2009     } else {
2010         // Default value (null if not specified).
2011         return $default;
2012     }
2015 // FUNCTIONS FOR HANDLING TIME.
2017 /**
2018  * Given date parts in user time produce a GMT timestamp.
2019  *
2020  * @package core
2021  * @category time
2022  * @param int $year The year part to create timestamp of
2023  * @param int $month The month part to create timestamp of
2024  * @param int $day The day part to create timestamp of
2025  * @param int $hour The hour part to create timestamp of
2026  * @param int $minute The minute part to create timestamp of
2027  * @param int $second The second part to create timestamp of
2028  * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2029  *             if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2030  * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2031  *             applied only if timezone is 99 or string.
2032  * @return int GMT timestamp
2033  */
2034 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2036     // Save input timezone, required for dst offset check.
2037     $passedtimezone = $timezone;
2039     $timezone = get_user_timezone_offset($timezone);
2041     if (abs($timezone) > 13) {
2042         // Server time.
2043         $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2044     } else {
2045         $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2046         $time = usertime($time, $timezone);
2048         // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
2049         if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
2050             $time -= dst_offset_on($time, $passedtimezone);
2051         }
2052     }
2054     return $time;
2058 /**
2059  * Format a date/time (seconds) as weeks, days, hours etc as needed
2060  *
2061  * Given an amount of time in seconds, returns string
2062  * formatted nicely as weeks, days, hours etc as needed
2063  *
2064  * @package core
2065  * @category time
2066  * @uses MINSECS
2067  * @uses HOURSECS
2068  * @uses DAYSECS
2069  * @uses YEARSECS
2070  * @param int $totalsecs Time in seconds
2071  * @param stdClass $str Should be a time object
2072  * @return string A nicely formatted date/time string
2073  */
2074 function format_time($totalsecs, $str = null) {
2076     $totalsecs = abs($totalsecs);
2078     if (!$str) {
2079         // Create the str structure the slow way.
2080         $str = new stdClass();
2081         $str->day   = get_string('day');
2082         $str->days  = get_string('days');
2083         $str->hour  = get_string('hour');
2084         $str->hours = get_string('hours');
2085         $str->min   = get_string('min');
2086         $str->mins  = get_string('mins');
2087         $str->sec   = get_string('sec');
2088         $str->secs  = get_string('secs');
2089         $str->year  = get_string('year');
2090         $str->years = get_string('years');
2091     }
2093     $years     = floor($totalsecs/YEARSECS);
2094     $remainder = $totalsecs - ($years*YEARSECS);
2095     $days      = floor($remainder/DAYSECS);
2096     $remainder = $totalsecs - ($days*DAYSECS);
2097     $hours     = floor($remainder/HOURSECS);
2098     $remainder = $remainder - ($hours*HOURSECS);
2099     $mins      = floor($remainder/MINSECS);
2100     $secs      = $remainder - ($mins*MINSECS);
2102     $ss = ($secs == 1)  ? $str->sec  : $str->secs;
2103     $sm = ($mins == 1)  ? $str->min  : $str->mins;
2104     $sh = ($hours == 1) ? $str->hour : $str->hours;
2105     $sd = ($days == 1)  ? $str->day  : $str->days;
2106     $sy = ($years == 1)  ? $str->year  : $str->years;
2108     $oyears = '';
2109     $odays = '';
2110     $ohours = '';
2111     $omins = '';
2112     $osecs = '';
2114     if ($years) {
2115         $oyears  = $years .' '. $sy;
2116     }
2117     if ($days) {
2118         $odays  = $days .' '. $sd;
2119     }
2120     if ($hours) {
2121         $ohours = $hours .' '. $sh;
2122     }
2123     if ($mins) {
2124         $omins  = $mins .' '. $sm;
2125     }
2126     if ($secs) {
2127         $osecs  = $secs .' '. $ss;
2128     }
2130     if ($years) {
2131         return trim($oyears .' '. $odays);
2132     }
2133     if ($days) {
2134         return trim($odays .' '. $ohours);
2135     }
2136     if ($hours) {
2137         return trim($ohours .' '. $omins);
2138     }
2139     if ($mins) {
2140         return trim($omins .' '. $osecs);
2141     }
2142     if ($secs) {
2143         return $osecs;
2144     }
2145     return get_string('now');
2148 /**
2149  * Returns a formatted string that represents a date in user time.
2150  *
2151  * @package core
2152  * @category time
2153  * @param int $date the timestamp in UTC, as obtained from the database.
2154  * @param string $format strftime format. You should probably get this using
2155  *        get_string('strftime...', 'langconfig');
2156  * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2157  *        not 99 then daylight saving will not be added.
2158  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2159  * @param bool $fixday If true (default) then the leading zero from %d is removed.
2160  *        If false then the leading zero is maintained.
2161  * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2162  * @return string the formatted date/time.
2163  */
2164 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2165     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2166     return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2169 /**
2170  * Returns a formatted date ensuring it is UTF-8.
2171  *
2172  * If we are running under Windows convert to Windows encoding and then back to UTF-8
2173  * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2174  *
2175  * This function does not do any calculation regarding the user preferences and should
2176  * therefore receive the final date timestamp, format and timezone. Timezone being only used
2177  * to differentiate the use of server time or not (strftime() against gmstrftime()).
2178  *
2179  * @param int $date the timestamp.
2180  * @param string $format strftime format.
2181  * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2182  * @return string the formatted date/time.
2183  * @since Moodle 2.3.3
2184  */
2185 function date_format_string($date, $format, $tz = 99) {
2186     global $CFG;
2188     $localewincharset = null;
2189     // Get the calendar type user is using.
2190     if ($CFG->ostype == 'WINDOWS') {
2191         $calendartype = \core_calendar\type_factory::get_calendar_instance();
2192         $localewincharset = $calendartype->locale_win_charset();
2193     }
2195     if (abs($tz) > 13) {
2196         if ($localewincharset) {
2197             $format = core_text::convert($format, 'utf-8', $localewincharset);
2198             $datestring = strftime($format, $date);
2199             $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2200         } else {
2201             $datestring = strftime($format, $date);
2202         }
2203     } else {
2204         if ($localewincharset) {
2205             $format = core_text::convert($format, 'utf-8', $localewincharset);
2206             $datestring = gmstrftime($format, $date);
2207             $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2208         } else {
2209             $datestring = gmstrftime($format, $date);
2210         }
2211     }
2212     return $datestring;
2215 /**
2216  * Given a $time timestamp in GMT (seconds since epoch),
2217  * returns an array that represents the date in user time
2218  *
2219  * @package core
2220  * @category time
2221  * @uses HOURSECS
2222  * @param int $time Timestamp in GMT
2223  * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2224  *        dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
2225  * @return array An array that represents the date in user time
2226  */
2227 function usergetdate($time, $timezone=99) {
2229     // Save input timezone, required for dst offset check.
2230     $passedtimezone = $timezone;
2232     $timezone = get_user_timezone_offset($timezone);
2234     if (abs($timezone) > 13) {
2235         // Server time.
2236         return getdate($time);
2237     }
2239     // Add daylight saving offset for string timezones only, as we can't get dst for
2240     // float values. if timezone is 99 (user default timezone), then try update dst.
2241     if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2242         $time += dst_offset_on($time, $passedtimezone);
2243     }
2245     $time += intval((float)$timezone * HOURSECS);
2247     $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2249     // Be careful to ensure the returned array matches that produced by getdate() above.
2250     list(
2251         $getdate['month'],
2252         $getdate['weekday'],
2253         $getdate['yday'],
2254         $getdate['year'],
2255         $getdate['mon'],
2256         $getdate['wday'],
2257         $getdate['mday'],
2258         $getdate['hours'],
2259         $getdate['minutes'],
2260         $getdate['seconds']
2261     ) = explode('_', $datestring);
2263     // Set correct datatype to match with getdate().
2264     $getdate['seconds'] = (int)$getdate['seconds'];
2265     $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
2266     $getdate['year'] = (int)$getdate['year'];
2267     $getdate['mon'] = (int)$getdate['mon'];
2268     $getdate['wday'] = (int)$getdate['wday'];
2269     $getdate['mday'] = (int)$getdate['mday'];
2270     $getdate['hours'] = (int)$getdate['hours'];
2271     $getdate['minutes'] = (int)$getdate['minutes'];
2272     return $getdate;
2275 /**
2276  * Given a GMT timestamp (seconds since epoch), offsets it by
2277  * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2278  *
2279  * @package core
2280  * @category time
2281  * @uses HOURSECS
2282  * @param int $date Timestamp in GMT
2283  * @param float|int|string $timezone timezone to calculate GMT time offset before
2284  *        calculating user time, 99 is default user timezone
2285  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2286  * @return int
2287  */
2288 function usertime($date, $timezone=99) {
2290     $timezone = get_user_timezone_offset($timezone);
2292     if (abs($timezone) > 13) {
2293         return $date;
2294     }
2295     return $date - (int)($timezone * HOURSECS);
2298 /**
2299  * Given a time, return the GMT timestamp of the most recent midnight
2300  * for the current user.
2301  *
2302  * @package core
2303  * @category time
2304  * @param int $date Timestamp in GMT
2305  * @param float|int|string $timezone timezone to calculate GMT time offset before
2306  *        calculating user midnight time, 99 is default user timezone
2307  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2308  * @return int Returns a GMT timestamp
2309  */
2310 function usergetmidnight($date, $timezone=99) {
2312     $userdate = usergetdate($date, $timezone);
2314     // Time of midnight of this user's day, in GMT.
2315     return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2319 /**
2320  * Returns a string that prints the user's timezone
2321  *
2322  * @package core
2323  * @category time
2324  * @param float|int|string $timezone timezone to calculate GMT time offset before
2325  *        calculating user timezone, 99 is default user timezone
2326  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2327  * @return string
2328  */
2329 function usertimezone($timezone=99) {
2331     $tz = get_user_timezone($timezone);
2333     if (!is_float($tz)) {
2334         return $tz;
2335     }
2337     if (abs($tz) > 13) {
2338         // Server time.
2339         return get_string('serverlocaltime');
2340     }
2342     if ($tz == intval($tz)) {
2343         // Don't show .0 for whole hours.
2344         $tz = intval($tz);
2345     }
2347     if ($tz == 0) {
2348         return 'UTC';
2349     } else if ($tz > 0) {
2350         return 'UTC+'.$tz;
2351     } else {
2352         return 'UTC'.$tz;
2353     }
2357 /**
2358  * Returns a float which represents the user's timezone difference from GMT in hours
2359  * Checks various settings and picks the most dominant of those which have a value
2360  *
2361  * @package core
2362  * @category time
2363  * @param float|int|string $tz timezone to calculate GMT time offset for user,
2364  *        99 is default user timezone
2365  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2366  * @return float
2367  */
2368 function get_user_timezone_offset($tz = 99) {
2369     $tz = get_user_timezone($tz);
2371     if (is_float($tz)) {
2372         return $tz;
2373     } else {
2374         $tzrecord = get_timezone_record($tz);
2375         if (empty($tzrecord)) {
2376             return 99.0;
2377         }
2378         return (float)$tzrecord->gmtoff / HOURMINS;
2379     }
2382 /**
2383  * Returns an int which represents the systems's timezone difference from GMT in seconds
2384  *
2385  * @package core
2386  * @category time
2387  * @param float|int|string $tz timezone for which offset is required.
2388  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2389  * @return int|bool if found, false is timezone 99 or error
2390  */
2391 function get_timezone_offset($tz) {
2392     if ($tz == 99) {
2393         return false;
2394     }
2396     if (is_numeric($tz)) {
2397         return intval($tz * 60*60);
2398     }
2400     if (!$tzrecord = get_timezone_record($tz)) {
2401         return false;
2402     }
2403     return intval($tzrecord->gmtoff * 60);
2406 /**
2407  * Returns a float or a string which denotes the user's timezone
2408  * 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)
2409  * means that for this timezone there are also DST rules to be taken into account
2410  * Checks various settings and picks the most dominant of those which have a value
2411  *
2412  * @package core
2413  * @category time
2414  * @param float|int|string $tz timezone to calculate GMT time offset before
2415  *        calculating user timezone, 99 is default user timezone
2416  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2417  * @return float|string
2418  */
2419 function get_user_timezone($tz = 99) {
2420     global $USER, $CFG;
2422     $timezones = array(
2423         $tz,
2424         isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2425         isset($USER->timezone) ? $USER->timezone : 99,
2426         isset($CFG->timezone) ? $CFG->timezone : 99,
2427         );
2429     $tz = 99;
2431     // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2432     while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2433         $tz = $next['value'];
2434     }
2435     return is_numeric($tz) ? (float) $tz : $tz;
2438 /**
2439  * Returns cached timezone record for given $timezonename
2440  *
2441  * @package core
2442  * @param string $timezonename name of the timezone
2443  * @return stdClass|bool timezonerecord or false
2444  */
2445 function get_timezone_record($timezonename) {
2446     global $DB;
2447     static $cache = null;
2449     if ($cache === null) {
2450         $cache = array();
2451     }
2453     if (isset($cache[$timezonename])) {
2454         return $cache[$timezonename];
2455     }
2457     return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2458                                                         WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2461 /**
2462  * Build and store the users Daylight Saving Time (DST) table
2463  *
2464  * @package core
2465  * @param int $fromyear Start year for the table, defaults to 1971
2466  * @param int $toyear End year for the table, defaults to 2035
2467  * @param int|float|string $strtimezone timezone to check if dst should be applied.
2468  * @return bool
2469  */
2470 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2471     global $SESSION, $DB;
2473     $usertz = get_user_timezone($strtimezone);
2475     if (is_float($usertz)) {
2476         // Trivial timezone, no DST.
2477         return false;
2478     }
2480     if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2481         // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
2482         unset($SESSION->dst_offsets);
2483         unset($SESSION->dst_range);
2484     }
2486     if (!empty($SESSION->dst_offsets) && empty($fromyear) && empty($toyear)) {
2487         // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
2488         // This will be the return path most of the time, pretty light computationally.
2489         return true;
2490     }
2492     // Reaching here means we either need to extend our table or create it from scratch.
2494     // Remember which TZ we calculated these changes for.
2495     $SESSION->dst_offsettz = $usertz;
2497     if (empty($SESSION->dst_offsets)) {
2498         // If we 're creating from scratch, put the two guard elements in there.
2499         $SESSION->dst_offsets = array(1 => null, 0 => null);
2500     }
2501     if (empty($SESSION->dst_range)) {
2502         // If creating from scratch.
2503         $from = max((empty($fromyear) ? intval(date('Y')) - 3 : $fromyear), 1971);
2504         $to   = min((empty($toyear)   ? intval(date('Y')) + 3 : $toyear),   2035);
2506         // Fill in the array with the extra years we need to process.
2507         $yearstoprocess = array();
2508         for ($i = $from; $i <= $to; ++$i) {
2509             $yearstoprocess[] = $i;
2510         }
2512         // Take note of which years we have processed for future calls.
2513         $SESSION->dst_range = array($from, $to);
2514     } else {
2515         // If needing to extend the table, do the same.
2516         $yearstoprocess = array();
2518         $from = max((empty($fromyear) ? $SESSION->dst_range[0] : $fromyear), 1971);
2519         $to   = min((empty($toyear)   ? $SESSION->dst_range[1] : $toyear),   2035);
2521         if ($from < $SESSION->dst_range[0]) {
2522             // Take note of which years we need to process and then note that we have processed them for future calls.
2523             for ($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2524                 $yearstoprocess[] = $i;
2525             }
2526             $SESSION->dst_range[0] = $from;
2527         }
2528         if ($to > $SESSION->dst_range[1]) {
2529             // Take note of which years we need to process and then note that we have processed them for future calls.
2530             for ($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2531                 $yearstoprocess[] = $i;
2532             }
2533             $SESSION->dst_range[1] = $to;
2534         }
2535     }
2537     if (empty($yearstoprocess)) {
2538         // This means that there was a call requesting a SMALLER range than we have already calculated.
2539         return true;
2540     }
2542     // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2543     // Also, the array is sorted in descending timestamp order!
2545     // Get DB data.
2547     static $presetscache = array();
2548     if (!isset($presetscache[$usertz])) {
2549         $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
2550             'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
2551             'std_startday, std_weekday, std_skipweeks, std_time');
2552     }
2553     if (empty($presetscache[$usertz])) {
2554         return false;
2555     }
2557     // Remove ending guard (first element of the array).
2558     reset($SESSION->dst_offsets);
2559     unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2561     // Add all required change timestamps.
2562     foreach ($yearstoprocess as $y) {
2563         // Find the record which is in effect for the year $y.
2564         foreach ($presetscache[$usertz] as $year => $preset) {
2565             if ($year <= $y) {
2566                 break;
2567             }
2568         }
2570         $changes = dst_changes_for_year($y, $preset);
2572         if ($changes === null) {
2573             continue;
2574         }
2575         if ($changes['dst'] != 0) {
2576             $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2577         }
2578         if ($changes['std'] != 0) {
2579             $SESSION->dst_offsets[$changes['std']] = 0;
2580         }
2581     }
2583     // Put in a guard element at the top.
2584     $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2585     $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = null; // DAYSECS is arbitrary, any "small" number will do.
2587     // Sort again.
2588     krsort($SESSION->dst_offsets);
2590     return true;
2593 /**
2594  * Calculates the required DST change and returns a Timestamp Array
2595  *
2596  * @package core
2597  * @category time
2598  * @uses HOURSECS
2599  * @uses MINSECS
2600  * @param int|string $year Int or String Year to focus on
2601  * @param object $timezone Instatiated Timezone object
2602  * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
2603  */
2604 function dst_changes_for_year($year, $timezone) {
2606     if ($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 &&
2607         $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2608         return null;
2609     }
2611     $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2612     $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2614     list($dsthour, $dstmin) = explode(':', $timezone->dst_time);
2615     list($stdhour, $stdmin) = explode(':', $timezone->std_time);
2617     $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2618     $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2620     // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2621     // This has the advantage of being able to have negative values for hour, i.e. for timezones
2622     // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2624     $timedst += $dsthour * HOURSECS + $dstmin * MINSECS;
2625     $timestd += $stdhour * HOURSECS + $stdmin * MINSECS;
2627     return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2630 /**
2631  * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2632  * - Note: Daylight saving only works for string timezones and not for float.
2633  *
2634  * @package core
2635  * @category time
2636  * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2637  * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2638  *        then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2639  * @return int
2640  */
2641 function dst_offset_on($time, $strtimezone = null) {
2642     global $SESSION;
2644     if (!calculate_user_dst_table(null, null, $strtimezone) || empty($SESSION->dst_offsets)) {
2645         return 0;
2646     }
2648     reset($SESSION->dst_offsets);
2649     while (list($from, $offset) = each($SESSION->dst_offsets)) {
2650         if ($from <= $time) {
2651             break;
2652         }
2653     }
2655     // This is the normal return path.
2656     if ($offset !== null) {
2657         return $offset;
2658     }
2660     // Reaching this point means we haven't calculated far enough, do it now:
2661     // Calculate extra DST changes if needed and recurse. The recursion always
2662     // moves toward the stopping condition, so will always end.
2664     if ($from == 0) {
2665         // We need a year smaller than $SESSION->dst_range[0].
2666         if ($SESSION->dst_range[0] == 1971) {
2667             return 0;
2668         }
2669         calculate_user_dst_table($SESSION->dst_range[0] - 5, null, $strtimezone);
2670         return dst_offset_on($time, $strtimezone);
2671     } else {
2672         // We need a year larger than $SESSION->dst_range[1].
2673         if ($SESSION->dst_range[1] == 2035) {
2674             return 0;
2675         }
2676         calculate_user_dst_table(null, $SESSION->dst_range[1] + 5, $strtimezone);
2677         return dst_offset_on($time, $strtimezone);
2678     }
2681 /**
2682  * Calculates when the day appears in specific month
2683  *
2684  * @package core
2685  * @category time
2686  * @param int $startday starting day of the month
2687  * @param int $weekday The day when week starts (normally taken from user preferences)
2688  * @param int $month The month whose day is sought
2689  * @param int $year The year of the month whose day is sought
2690  * @return int
2691  */
2692 function find_day_in_month($startday, $weekday, $month, $year) {
2693     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2695     $daysinmonth = days_in_month($month, $year);
2696     $daysinweek = count($calendartype->get_weekdays());
2698     if ($weekday == -1) {
2699         // Don't care about weekday, so return:
2700         //    abs($startday) if $startday != -1
2701         //    $daysinmonth otherwise.
2702         return ($startday == -1) ? $daysinmonth : abs($startday);
2703     }
2705     // From now on we 're looking for a specific weekday.
2706     // Give "end of month" its actual value, since we know it.
2707     if ($startday == -1) {
2708         $startday = -1 * $daysinmonth;
2709     }
2711     // Starting from day $startday, the sign is the direction.
2712     if ($startday < 1) {
2713         $startday = abs($startday);
2714         $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2716         // This is the last such weekday of the month.
2717         $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2718         if ($lastinmonth > $daysinmonth) {
2719             $lastinmonth -= $daysinweek;
2720         }
2722         // Find the first such weekday <= $startday.
2723         while ($lastinmonth > $startday) {
2724             $lastinmonth -= $daysinweek;
2725         }
2727         return $lastinmonth;
2728     } else {
2729         $indexweekday = dayofweek($startday, $month, $year);
2731         $diff = $weekday - $indexweekday;
2732         if ($diff < 0) {
2733             $diff += $daysinweek;
2734         }
2736         // This is the first such weekday of the month equal to or after $startday.
2737         $firstfromindex = $startday + $diff;
2739         return $firstfromindex;
2740     }
2743 /**
2744  * Calculate the number of days in a given month
2745  *
2746  * @package core
2747  * @category time
2748  * @param int $month The month whose day count is sought
2749  * @param int $year The year of the month whose day count is sought
2750  * @return int
2751  */
2752 function days_in_month($month, $year) {
2753     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2754     return $calendartype->get_num_days_in_month($year, $month);
2757 /**
2758  * Calculate the position in the week of a specific calendar day
2759  *
2760  * @package core
2761  * @category time
2762  * @param int $day The day of the date whose position in the week is sought
2763  * @param int $month The month of the date whose position in the week is sought
2764  * @param int $year The year of the date whose position in the week is sought
2765  * @return int
2766  */
2767 function dayofweek($day, $month, $year) {
2768     $calendartype = \core_calendar\type_factory::get_calendar_instance();
2769     return $calendartype->get_weekday($year, $month, $day);
2772 // USER AUTHENTICATION AND LOGIN.
2774 /**
2775  * Returns full login url.
2776  *
2777  * @return string login url
2778  */
2779 function get_login_url() {
2780     global $CFG;
2782     $url = "$CFG->wwwroot/login/index.php";
2784     if (!empty($CFG->loginhttps)) {
2785         $url = str_replace('http:', 'https:', $url);
2786     }
2788     return $url;
2791 /**
2792  * This function checks that the current user is logged in and has the
2793  * required privileges
2794  *
2795  * This function checks that the current user is logged in, and optionally
2796  * whether they are allowed to be in a particular course and view a particular
2797  * course module.
2798  * If they are not logged in, then it redirects them to the site login unless
2799  * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2800  * case they are automatically logged in as guests.
2801  * If $courseid is given and the user is not enrolled in that course then the
2802  * user is redirected to the course enrolment page.
2803  * If $cm is given and the course module is hidden and the user is not a teacher
2804  * in the course then the user is redirected to the course home page.
2805  *
2806  * When $cm parameter specified, this function sets page layout to 'module'.
2807  * You need to change it manually later if some other layout needed.
2808  *
2809  * @package    core_access
2810  * @category   access
2811  *
2812  * @param mixed $courseorid id of the course or course object
2813  * @param bool $autologinguest default true
2814  * @param object $cm course module object
2815  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2816  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2817  *             in order to keep redirects working properly. MDL-14495
2818  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2819  * @return mixed Void, exit, and die depending on path
2820  * @throws coding_exception
2821  * @throws require_login_exception
2822  */
2823 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2824     global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2826     // Must not redirect when byteserving already started.
2827     if (!empty($_SERVER['HTTP_RANGE'])) {
2828         $preventredirect = true;
2829     }
2831     // Setup global $COURSE, themes, language and locale.
2832     if (!empty($courseorid)) {
2833         if (is_object($courseorid)) {
2834             $course = $courseorid;
2835         } else if ($courseorid == SITEID) {
2836             $course = clone($SITE);
2837         } else {
2838             $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2839         }
2840         if ($cm) {
2841             if ($cm->course != $course->id) {
2842                 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2843             }
2844             // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2845             if (!($cm instanceof cm_info)) {
2846                 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2847                 // db queries so this is not really a performance concern, however it is obviously
2848                 // better if you use get_fast_modinfo to get the cm before calling this.
2849                 $modinfo = get_fast_modinfo($course);
2850                 $cm = $modinfo->get_cm($cm->id);
2851             }
2852             $PAGE->set_cm($cm, $course); // Set's up global $COURSE.
2853             $PAGE->set_pagelayout('incourse');
2854         } else {
2855             $PAGE->set_course($course); // Set's up global $COURSE.
2856         }
2857     } else {
2858         // Do not touch global $COURSE via $PAGE->set_course(),
2859         // the reasons is we need to be able to call require_login() at any time!!
2860         $course = $SITE;
2861         if ($cm) {
2862             throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2863         }
2864     }
2866     // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2867     // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2868     // risk leading the user back to the AJAX request URL.
2869     if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2870         $setwantsurltome = false;
2871     }
2873     // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2874     if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2875         if ($setwantsurltome) {
2876             $SESSION->wantsurl = qualified_me();
2877         }
2878         redirect(get_login_url());
2879     }
2881     // If the user is not even logged in yet then make sure they are.
2882     if (!isloggedin()) {
2883         if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2884             if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2885                 // Misconfigured site guest, just redirect to login page.
2886                 redirect(get_login_url());
2887                 exit; // Never reached.
2888             }
2889             $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2890             complete_user_login($guest);
2891             $USER->autologinguest = true;
2892             $SESSION->lang = $lang;
2893         } else {
2894             // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2895             if ($preventredirect) {
2896                 throw new require_login_exception('You are not logged in');
2897             }
2899             if ($setwantsurltome) {
2900                 $SESSION->wantsurl = qualified_me();
2901             }
2902             if (!empty($_SERVER['HTTP_REFERER'])) {
2903                 $SESSION->fromurl  = $_SERVER['HTTP_REFERER'];
2904             }
2905             redirect(get_login_url());
2906             exit; // Never reached.
2907         }
2908     }
2910     // Loginas as redirection if needed.
2911     if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2912         if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2913             if ($USER->loginascontext->instanceid != $course->id) {
2914                 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2915             }
2916         }
2917     }
2919     // Check whether the user should be changing password (but only if it is REALLY them).
2920     if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2921         $userauth = get_auth_plugin($USER->auth);
2922         if ($userauth->can_change_password() and !$preventredirect) {
2923             if ($setwantsurltome) {
2924                 $SESSION->wantsurl = qualified_me();
2925             }
2926             if ($changeurl = $userauth->change_password_url()) {
2927                 // Use plugin custom url.
2928                 redirect($changeurl);
2929             } else {
2930                 // Use moodle internal method.
2931                 if (empty($CFG->loginhttps)) {
2932                     redirect($CFG->wwwroot .'/login/change_password.php');
2933                 } else {
2934                     $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2935                     redirect($wwwroot .'/login/change_password.php');
2936                 }
2937             }
2938         } else {
2939             print_error('nopasswordchangeforced', 'auth');
2940         }
2941     }
2943     // Check that the user account is properly set up.
2944     if (user_not_fully_set_up($USER)) {
2945         if ($preventredirect) {
2946             throw new require_login_exception('User not fully set-up');
2947         }
2948         if ($setwantsurltome) {
2949             $SESSION->wantsurl = qualified_me();
2950         }
2951         redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2952     }
2954     // Make sure the USER has a sesskey set up. Used for CSRF protection.
2955     sesskey();
2957     // Do not bother admins with any formalities.
2958     if (is_siteadmin()) {
2959         // Set accesstime or the user will appear offline which messes up messaging.
2960         user_accesstime_log($course->id);
2961         return;
2962     }
2964     // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2965     if (!$USER->policyagreed and !is_siteadmin()) {
2966         if (!empty($CFG->sitepolicy) and !isguestuser()) {
2967             if ($preventredirect) {
2968                 throw new require_login_exception('Policy not agreed');
2969             }
2970             if ($setwantsurltome) {
2971                 $SESSION->wantsurl = qualified_me();
2972             }
2973             redirect($CFG->wwwroot .'/user/policy.php');
2974         } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2975             if ($preventredirect) {
2976                 throw new require_login_exception('Policy not agreed');
2977             }
2978             if ($setwantsurltome) {
2979                 $SESSION->wantsurl = qualified_me();
2980             }
2981             redirect($CFG->wwwroot .'/user/policy.php');
2982         }
2983     }
2985     // Fetch the system context, the course context, and prefetch its child contexts.
2986     $sysctx = context_system::instance();
2987     $coursecontext = context_course::instance($course->id, MUST_EXIST);
2988     if ($cm) {
2989         $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2990     } else {
2991         $cmcontext = null;
2992     }
2994     // If the site is currently under maintenance, then print a message.
2995     if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2996         if ($preventredirect) {
2997             throw new require_login_exception('Maintenance in progress');
2998         }
3000         print_maintenance_message();
3001     }
3003     // Make sure the course itself is not hidden.
3004     if ($course->id == SITEID) {
3005         // Frontpage can not be hidden.
3006     } else {
3007         if (is_role_switched($course->id)) {
3008             // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3009         } else {
3010             if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3011                 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3012                 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3013                 if ($preventredirect) {
3014                     throw new require_login_exception('Course is hidden');
3015                 }
3016                 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3017                 // the navigation will mess up when trying to find it.
3018                 navigation_node::override_active_url(new moodle_url('/'));
3019                 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3020             }
3021         }
3022     }
3024     // Is the user enrolled?
3025     if ($course->id == SITEID) {
3026         // Everybody is enrolled on the frontpage.
3027     } else {
3028         if (\core\session\manager::is_loggedinas()) {
3029             // Make sure the REAL person can access this course first.
3030             $realuser = \core\session\manager::get_realuser();
3031             if (!is_enrolled($coursecontext, $realuser->id, '', true) and
3032                 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3033                 if ($preventredirect) {
3034                     throw new require_login_exception('Invalid course login-as access');
3035                 }
3036                 echo $OUTPUT->header();
3037                 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3038             }
3039         }
3041         $access = false;
3043         if (is_role_switched($course->id)) {
3044             // Ok, user had to be inside this course before the switch.
3045             $access = true;
3047         } else if (is_viewing($coursecontext, $USER)) {
3048             // Ok, no need to mess with enrol.
3049             $access = true;
3051         } else {
3052             if (isset($USER->enrol['enrolled'][$course->id])) {
3053                 if ($USER->enrol['enrolled'][$course->id] > time()) {
3054                     $access = true;
3055                     if (isset($USER->enrol['tempguest'][$course->id])) {
3056                         unset($USER->enrol['tempguest'][$course->id]);
3057                         remove_temp_course_roles($coursecontext);
3058                     }
3059                 } else {
3060                     // Expired.
3061                     unset($USER->enrol['enrolled'][$course->id]);
3062                 }
3063             }
3064             if (isset($USER->enrol['tempguest'][$course->id])) {
3065                 if ($USER->enrol['tempguest'][$course->id] == 0) {
3066                     $access = true;
3067                 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3068                     $access = true;
3069                 } else {
3070                     // Expired.
3071                     unset($USER->enrol['tempguest'][$course->id]);
3072                     remove_temp_course_roles($coursecontext);
3073                 }
3074             }
3076             if (!$access) {
3077                 // Cache not ok.
3078                 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3079                 if ($until !== false) {
3080                     // Active participants may always access, a timestamp in the future, 0 (always) or false.
3081                     if ($until == 0) {
3082                         $until = ENROL_MAX_TIMESTAMP;
3083                     }
3084                     $USER->enrol['enrolled'][$course->id] = $until;
3085                     $access = true;
3087                 } else {
3088                     $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3089                     $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3090                     $enrols = enrol_get_plugins(true);
3091                     // First ask all enabled enrol instances in course if they want to auto enrol user.
3092                     foreach ($instances as $instance) {
3093                         if (!isset($enrols[$instance->enrol])) {
3094                             continue;
3095                         }
3096                         // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3097                         $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3098                         if ($until !== false) {
3099                             if ($until == 0) {
3100                                 $until = ENROL_MAX_TIMESTAMP;
3101                             }
3102                             $USER->enrol['enrolled'][$course->id] = $until;
3103                             $access = true;
3104                             break;
3105                         }
3106                     }
3107                     // If not enrolled yet try to gain temporary guest access.
3108                     if (!$access) {
3109                         foreach ($instances as $instance) {
3110                             if (!isset($enrols[$instance->enrol])) {
3111                                 continue;
3112                             }
3113                             // Get a duration for the guest access, a timestamp in the future or false.
3114                             $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3115                             if ($until !== false and $until > time()) {
3116                                 $USER->enrol['tempguest'][$course->id] = $until;
3117                                 $access = true;
3118                                 break;
3119                             }
3120                         }
3121                     }
3122                 }
3123             }
3124         }
3126         if (!$access) {
3127             if ($preventredirect) {
3128                 throw new require_login_exception('Not enrolled');
3129             }
3130             if ($setwantsurltome) {
3131                 $SESSION->wantsurl = qualified_me();
3132             }
3133             redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3134         }
3135     }
3137     // Check visibility of activity to current user; includes visible flag, groupmembersonly, conditional availability, etc.
3138     if ($cm && !$cm->uservisible) {
3139         if ($preventredirect) {
3140             throw new require_login_exception('Activity is hidden');
3141         }
3142         if ($course->id != SITEID) {
3143             $url = new moodle_url('/course/view.php', array('id' => $course->id));
3144         } else {
3145             $url = new moodle_url('/');
3146         }
3147         redirect($url, get_string('activityiscurrentlyhidden'));
3148     }
3150     // Finally access granted, update lastaccess times.
3151     user_accesstime_log($course->id);
3155 /**
3156  * This function just makes sure a user is logged out.
3157  *
3158  * @package    core_access
3159  * @category   access
3160  */
3161 function require_logout() {
3162     global $USER, $DB;
3164     if (!isloggedin()) {
3165         // This should not happen often, no need for hooks or events here.
3166         \core\session\manager::terminate_current();
3167         return;
3168     }
3170     // Execute hooks before action.
3171     $authplugins = array();
3172     $authsequence = get_enabled_auth_plugins();
3173     foreach ($authsequence as $authname) {
3174         $authplugins[$authname] = get_auth_plugin($authname);
3175         $authplugins[$authname]->prelogout_hook();
3176     }
3178     // Store info that gets removed during logout.
3179     $sid = session_id();
3180     $event = \core\event\user_loggedout::create(
3181         array(
3182             'userid' => $USER->id,
3183             'objectid' => $USER->id,
3184             'other' => array('sessionid' => $sid),
3185         )
3186     );
3187     if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3188         $event->add_record_snapshot('sessions', $session);
3189     }
3191     // Clone of $USER object to be used by auth plugins.
3192     $user = fullclone($USER);
3194     // Delete session record and drop $_SESSION content.
3195     \core\session\manager::terminate_current();
3197     // Trigger event AFTER action.
3198     $event->trigger();
3200     // Hook to execute auth plugins redirection after event trigger.
3201     foreach ($authplugins as $authplugin) {
3202         $authplugin->postlogout_hook($user);
3203     }
3206 /**
3207  * Weaker version of require_login()
3208  *
3209  * This is a weaker version of {@link require_login()} which only requires login
3210  * when called from within a course rather than the site page, unless
3211  * the forcelogin option is turned on.
3212  * @see require_login()
3213  *
3214  * @package    core_access
3215  * @category   access
3216  *
3217  * @param mixed $courseorid The course object or id in question
3218  * @param bool $autologinguest Allow autologin guests if that is wanted
3219  * @param object $cm Course activity module if known
3220  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3221  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3222  *             in order to keep redirects working properly. MDL-14495
3223  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3224  * @return void
3225  * @throws coding_exception
3226  */
3227 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3228     global $CFG, $PAGE, $SITE;
3229     $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3230           or (!is_object($courseorid) and $courseorid == SITEID));
3231     if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3232         // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3233         // db queries so this is not really a performance concern, however it is obviously
3234         // better if you use get_fast_modinfo to get the cm before calling this.
3235         if (is_object($courseorid)) {
3236             $course = $courseorid;
3237         } else {
3238             $course = clone($SITE);
3239         }
3240         $modinfo = get_fast_modinfo($course);
3241         $cm = $modinfo->get_cm($cm->id);
3242     }
3243     if (!empty($CFG->forcelogin)) {
3244         // Login required for both SITE and courses.
3245         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3247     } else if ($issite && !empty($cm) and !$cm->uservisible) {
3248         // Always login for hidden activities.
3249         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3251     } else if ($issite) {
3252         // Login for SITE not required.
3253         if ($cm and empty($cm->visible)) {
3254             // Hidden activities are not accessible without login.
3255             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3256         } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3257             // Not-logged-in users do not have any group membership.
3258             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3259         } else {
3260             // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3261             if (!empty($courseorid)) {
3262                 if (is_object($courseorid)) {
3263                     $course = $courseorid;
3264                 } else {
3265                     $course = clone($SITE);
3266                 }
3267                 if ($cm) {
3268                     if ($cm->course != $course->id) {
3269                         throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3270                     }
3271                     $PAGE->set_cm($cm, $course);
3272                     $PAGE->set_pagelayout('incourse');
3273                 } else {
3274                     $PAGE->set_course($course);
3275                 }
3276             } else {
3277                 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3278                 $PAGE->set_course($PAGE->course);
3279             }
3280             // TODO: verify conditional activities here.
3281             user_accesstime_log(SITEID);
3282             return;
3283         }
3285     } else {
3286         // Course login always required.
3287         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3288     }
3291 /**
3292  * Require key login. Function terminates with error if key not found or incorrect.
3293  *
3294  * @uses NO_MOODLE_COOKIES
3295  * @uses PARAM_ALPHANUM
3296  * @param string $script unique script identifier
3297  * @param int $instance optional instance id
3298  * @return int Instance ID
3299  */
3300 function require_user_key_login($script, $instance=null) {
3301     global $DB;
3303     if (!NO_MOODLE_COOKIES) {
3304         print_error('sessioncookiesdisable');
3305     }
3307     // Extra safety.
3308     \core\session\manager::write_close();
3310     $keyvalue = required_param('key', PARAM_ALPHANUM);
3312     if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3313         print_error('invalidkey');
3314     }
3316     if (!empty($key->validuntil) and $key->validuntil < time()) {
3317         print_error('expiredkey');
3318     }
3320     if ($key->iprestriction) {
3321         $remoteaddr = getremoteaddr(null);
3322         if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3323             print_error('ipmismatch');
3324         }
3325     }
3327     if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3328         print_error('invaliduserid');
3329     }
3331     // Emulate normal session.
3332     enrol_check_plugins($user);
3333     \core\session\manager::set_user($user);
3335     // Note we are not using normal login.
3336     if (!defined('USER_KEY_LOGIN')) {
3337         define('USER_KEY_LOGIN', true);
3338     }
3340     // Return instance id - it might be empty.
3341     return $key->instance;
3344 /**
3345  * Creates a new private user access key.
3346  *
3347  * @param string $script unique target identifier
3348  * @param int $userid
3349  * @param int $instance optional instance id
3350  * @param string $iprestriction optional ip restricted access
3351  * @param timestamp $validuntil key valid only until given data
3352  * @return string access key value
3353  */
3354 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3355     global $DB;
3357     $key = new stdClass();
3358     $key->script        = $script;
3359     $key->userid        = $userid;
3360     $key->instance      = $instance;
3361     $key->iprestriction = $iprestriction;
3362     $key->validuntil    = $validuntil;
3363     $key->timecreated   = time();
3365     // Something long and unique.
3366     $key->value         = md5($userid.'_'.time().random_string(40));
3367     while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3368         // Must be unique.
3369         $key->value     = md5($userid.'_'.time().random_string(40));
3370     }
3371     $DB->insert_record('user_private_key', $key);
3372     return $key->value;
3375 /**
3376  * Delete the user's new private user access keys for a particular script.
3377  *
3378  * @param string $script unique target identifier
3379  * @param int $userid
3380  * @return void
3381  */
3382 function delete_user_key($script, $userid) {
3383     global $DB;
3384     $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3387 /**
3388  * Gets a private user access key (and creates one if one doesn't exist).
3389  *
3390  * @param string $script unique target identifier
3391  * @param int $userid
3392  * @param int $instance optional instance id
3393  * @param string $iprestriction optional ip restricted access
3394  * @param timestamp $validuntil key valid only until given data
3395  * @return string access key value
3396  */
3397 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3398     global $DB;
3400     if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3401                                                          'instance' => $instance, 'iprestriction' => $iprestriction,
3402                                                          'validuntil' => $validuntil))) {
3403         return $key->value;
3404     } else {
3405         return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3406     }
3410 /**
3411  * Modify the user table by setting the currently logged in user's last login to now.
3412  *
3413  * @return bool Always returns true
3414  */
3415 function update_user_login_times() {
3416     global $USER, $DB;
3418     if (isguestuser()) {
3419         // Do not update guest access times/ips for performance.
3420         return true;
3421     }
3423     $now = time();
3425     $user = new stdClass();
3426     $user->id = $USER->id;
3428     // Make sure all users that logged in have some firstaccess.
3429     if ($USER->firstaccess == 0) {
3430         $USER->firstaccess = $user->firstaccess = $now;
3431     }
3433     // Store the previous current as lastlogin.
3434     $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3436     $USER->currentlogin = $user->currentlogin = $now;
3438     // Function user_accesstime_log() may not update immediately, better do it here.
3439     $USER->lastaccess = $user->lastaccess = $now;
3440     $USER->lastip = $user->lastip = getremoteaddr();
3442     // Note: do not call user_update_user() here because this is part of the login process,
3443     //       the login event means that these fields were updated.
3444     $DB->update_record('user', $user);
3445     return true;
3448 /**
3449  * Determines if a user has completed setting up their account.
3450  *
3451  * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3452  * @return bool
3453  */
3454 function user_not_fully_set_up($user) {
3455     if (isguestuser($user)) {
3456         return false;
3457     }
3458     return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3461 /**
3462  * Check whether the user has exceeded the bounce threshold
3463  *
3464  * @param stdClass $user A {@link $USER} object
3465  * @return bool true => User has exceeded bounce threshold
3466  */
3467 function over_bounce_threshold($user) {
3468     global $CFG, $DB;
3470     if (empty($CFG->handlebounces)) {
3471         return false;
3472     }
3474     if (empty($user->id)) {
3475         // No real (DB) user, nothing to do here.
3476         return false;
3477     }
3479     // Set sensible defaults.
3480     if (empty($CFG->minbounces)) {
3481         $CFG->minbounces = 10;
3482     }
3483     if (empty($CFG->bounceratio)) {
3484         $CFG->bounceratio = .20;
3485     }
3486     $bouncecount = 0;
3487     $sendcount = 0;
3488     if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3489         $bouncecount = $bounce->value;
3490     }
3491     if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3492         $sendcount = $send->value;
3493     }
3494     return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3497 /**
3498  * Used to increment or reset email sent count
3499  *
3500  * @param stdClass $user object containing an id
3501  * @param bool $reset will reset the count to 0
3502  * @return void
3503  */
3504 function set_send_count($user, $reset=false) {
3505     global $DB;
3507     if (empty($user->id)) {
3508         // No real (DB) user, nothing to do here.
3509         return;
3510     }
3512     if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3513         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3514         $DB->update_record('user_preferences', $pref);
3515     } else if (!empty($reset)) {
3516         // If it's not there and we're resetting, don't bother. Make a new one.
3517         $pref = new stdClass();
3518         $pref->name   = 'email_send_count';
3519         $pref->value  = 1;
3520         $pref->userid = $user->id;
3521         $DB->insert_record('user_preferences', $pref, false);
3522     }
3525 /**
3526  * Increment or reset user's email bounce count
3527  *
3528  * @param stdClass $user object containing an id
3529  * @param bool $reset will reset the count to 0
3530  */
3531 function set_bounce_count($user, $reset=false) {
3532     global $DB;
3534     if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3535         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3536         $DB->update_record('user_preferences', $pref);
3537     } else if (!empty($reset)) {
3538         // If it's not there and we're resetting, don't bother. Make a new one.
3539         $pref = new stdClass();
3540         $pref->name   = 'email_bounce_count';
3541         $pref->value  = 1;
3542         $pref->userid = $user->id;
3543         $DB->insert_record('user_preferences', $pref, false);
3544     }
3547 /**
3548  * Determines if the logged in user is currently moving an activity
3549  *
3550  * @param int $courseid The id of the course being tested
3551  * @return bool
3552  */
3553 function ismoving($courseid) {
3554     global $USER;
3556     if (!empty($USER->activitycopy)) {
3557         return ($USER->activitycopycourse == $courseid);
3558     }
3559     return false;
3562 /**
3563  * Returns a persons full name
3564  *
3565  * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3566  * The result may depend on system settings or language.  'override' will force both names to be used even if system settings
3567  * specify one.
3568  *
3569  * @param stdClass $user A {@link $USER} object to get full name of.
3570  * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3571  * @return string
3572  */
3573 function fullname($user, $override=false) {
3574     global $CFG, $SESSION;
3576     if (!isset($user->firstname) and !isset($user->lastname)) {
3577         return '';
3578     }
3580     // Get all of the name fields.
3581     $allnames = get_all_user_name_fields();
3582     if ($CFG->debugdeveloper) {
3583         foreach ($allnames as $allname) {
3584             if (!array_key_exists($allname, $user)) {
3585                 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3586                 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3587                 // Message has been sent, no point in sending the message multiple times.
3588                 break;
3589             }
3590         }
3591     }
3593     if (!$override) {
3594         if (!empty($CFG->forcefirstname)) {
3595             $user->firstname = $CFG->forcefirstname;
3596         }
3597         if (!empty($CFG->forcelastname)) {
3598             $user->lastname = $CFG->forcelastname;
3599         }
3600     }
3602     if (!empty($SESSION->fullnamedisplay)) {
3603         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3604     }
3606     $template = null;
3607     // If the fullnamedisplay setting is available, set the template to that.
3608     if (isset($CFG->fullnamedisplay)) {
3609         $template = $CFG->fullnamedisplay;
3610     }
3611     // If the template is empty, or set to language, or $override is set, return the language string.
3612     if (empty($template) || $template == 'language' || $override) {
3613         return get_string('fullnamedisplay', null, $user);
3614     }
3616     $requirednames = array();
3617     // With each name, see if it is in the display name template, and add it to the required names array if it is.
3618     foreach ($allnames as $allname) {
3619         if (strpos($template, $allname) !== false) {
3620             $requirednames[] = $allname;
3621         }
3622     }
3624     $displayname = $template;
3625     // Switch in the actual data into the template.
3626     foreach ($requirednames as $altname) {
3627         if (isset($user->$altname)) {
3628             // Using empty() on the below if statement causes breakages.
3629             if ((string)$user->$altname == '') {
3630                 $displayname = str_replace($altname, 'EMPTY', $displayname);
3631             } else {
3632                 $displayname = str_replace($altname, $user->$altname, $displayname);
3633             }
3634         } else {
3635             $displayname = str_replace($altname, 'EMPTY', $displayname);
3636         }
3637     }
3638     // Tidy up any misc. characters (Not perfect, but gets most characters).
3639     // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3640     // katakana and parenthesis.
3641     $patterns = array();
3642     // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3643     // filled in by a user.
3644     // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3645     $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3646     // This regular expression is to remove any double spaces in the display name.
3647     $patterns[] = '/\s{2,}/u';
3648     foreach ($patterns as $pattern) {
3649         $displayname = preg_replace($pattern, ' ', $displayname);
3650     }
3652     // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3653     $displayname = trim($displayname);