5cf9d50d8a50851ee5bc4806931d8f92d5ffb7d5
[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.  //////////////
76 /**
77  * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
78  */
79 define('PARAM_ALPHA',    'alpha');
81 /**
82  * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
83  * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
84  */
85 define('PARAM_ALPHAEXT', 'alphaext');
87 /**
88  * PARAM_ALPHANUM - expected numbers and letters only.
89  */
90 define('PARAM_ALPHANUM', 'alphanum');
92 /**
93  * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
94  */
95 define('PARAM_ALPHANUMEXT', 'alphanumext');
97 /**
98  * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
99  */
100 define('PARAM_AUTH',  'auth');
102 /**
103  * PARAM_BASE64 - Base 64 encoded format
104  */
105 define('PARAM_BASE64',   'base64');
107 /**
108  * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
109  */
110 define('PARAM_BOOL',     'bool');
112 /**
113  * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
114  * checked against the list of capabilities in the database.
115  */
116 define('PARAM_CAPABILITY',   'capability');
118 /**
119  * PARAM_CLEANHTML - cleans submitted HTML code. use only for text in HTML format. This cleaning may fix xhtml strictness too.
120  */
121 define('PARAM_CLEANHTML', 'cleanhtml');
123 /**
124  * PARAM_EMAIL - an email address following the RFC
125  */
126 define('PARAM_EMAIL',   'email');
128 /**
129  * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
130  */
131 define('PARAM_FILE',   'file');
133 /**
134  * PARAM_FLOAT - a real/floating point number.
135  */
136 define('PARAM_FLOAT',  'float');
138 /**
139  * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
140  */
141 define('PARAM_HOST',     'host');
143 /**
144  * PARAM_INT - integers only, use when expecting only numbers.
145  */
146 define('PARAM_INT',      'int');
148 /**
149  * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
150  */
151 define('PARAM_LANG',  'lang');
153 /**
154  * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
155  */
156 define('PARAM_LOCALURL', 'localurl');
158 /**
159  * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
160  */
161 define('PARAM_NOTAGS',   'notags');
163 /**
164  * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
165  * note: the leading slash is not removed, window drive letter is not allowed
166  */
167 define('PARAM_PATH',     'path');
169 /**
170  * PARAM_PEM - Privacy Enhanced Mail format
171  */
172 define('PARAM_PEM',      'pem');
174 /**
175  * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
176  */
177 define('PARAM_PERMISSION',   'permission');
179 /**
180  * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
181  */
182 define('PARAM_RAW', 'raw');
184 /**
185  * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
186  */
187 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
189 /**
190  * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
191  */
192 define('PARAM_SAFEDIR',  'safedir');
194 /**
195  * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
196  */
197 define('PARAM_SAFEPATH',  'safepath');
199 /**
200  * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9.  Numbers and comma only.
201  */
202 define('PARAM_SEQUENCE',  'sequence');
204 /**
205  * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
206  */
207 define('PARAM_TAG',   'tag');
209 /**
210  * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
211  */
212 define('PARAM_TAGLIST',   'taglist');
214 /**
215  * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
216  */
217 define('PARAM_TEXT',  'text');
219 /**
220  * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
221  */
222 define('PARAM_THEME',  'theme');
224 /**
225  * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
226  */
227 define('PARAM_URL',      'url');
229 /**
230  * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user accounts, do NOT use when syncing with external systems!!
231  */
232 define('PARAM_USERNAME',    'username');
234 /**
235  * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
236  */
237 define('PARAM_STRINGID',    'stringid');
239 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE  /////
240 /**
241  * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
242  * It was one of the first types, that is why it is abused so much ;-)
243  * @deprecated since 2.0
244  */
245 define('PARAM_CLEAN',    'clean');
247 /**
248  * PARAM_INTEGER - deprecated alias for PARAM_INT
249  */
250 define('PARAM_INTEGER',  'int');
252 /**
253  * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
254  */
255 define('PARAM_NUMBER',  'float');
257 /**
258  * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
259  * NOTE: originally alias for PARAM_APLHA
260  */
261 define('PARAM_ACTION',   'alphanumext');
263 /**
264  * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
265  * NOTE: originally alias for PARAM_APLHA
266  */
267 define('PARAM_FORMAT',   'alphanumext');
269 /**
270  * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
271  */
272 define('PARAM_MULTILANG',  'text');
274 /**
275  * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
276  * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
277  * America/Port-au-Prince)
278  */
279 define('PARAM_TIMEZONE', 'timezone');
281 /**
282  * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
283  */
284 define('PARAM_CLEANFILE', 'file');
286 /**
287  * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
288  * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
289  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
290  * NOTE: numbers and underscores are strongly discouraged in plugin names!
291  */
292 define('PARAM_COMPONENT', 'component');
294 /**
295  * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
296  * It is usually used together with context id and component.
297  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
298  */
299 define('PARAM_AREA', 'area');
301 /**
302  * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
303  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
304  * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
305  */
306 define('PARAM_PLUGIN', 'plugin');
309 /// Web Services ///
311 /**
312  * VALUE_REQUIRED - if the parameter is not supplied, there is an error
313  */
314 define('VALUE_REQUIRED', 1);
316 /**
317  * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
318  */
319 define('VALUE_OPTIONAL', 2);
321 /**
322  * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
323  */
324 define('VALUE_DEFAULT', 0);
326 /**
327  * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
328  */
329 define('NULL_NOT_ALLOWED', false);
331 /**
332  * NULL_ALLOWED - the parameter can be set to null in the database
333  */
334 define('NULL_ALLOWED', true);
336 /// Page types ///
337 /**
338  * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
339  */
340 define('PAGE_COURSE_VIEW', 'course-view');
342 /** Get remote addr constant */
343 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
344 /** Get remote addr constant */
345 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
347 /// Blog access level constant declaration ///
348 define ('BLOG_USER_LEVEL', 1);
349 define ('BLOG_GROUP_LEVEL', 2);
350 define ('BLOG_COURSE_LEVEL', 3);
351 define ('BLOG_SITE_LEVEL', 4);
352 define ('BLOG_GLOBAL_LEVEL', 5);
355 ///Tag constants///
356 /**
357  * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
358  * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
359  * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
360  *
361  * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
362  */
363 define('TAG_MAX_LENGTH', 50);
365 /// Password policy constants ///
366 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
367 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
368 define ('PASSWORD_DIGITS', '0123456789');
369 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
371 /// Feature constants ///
372 // Used for plugin_supports() to report features that are, or are not, supported by a module.
374 /** True if module can provide a grade */
375 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
376 /** True if module supports outcomes */
377 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
378 /** True if module supports advanced grading methods */
379 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
381 /** True if module has code to track whether somebody viewed it */
382 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
383 /** True if module has custom completion rules */
384 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
386 /** True if module has no 'view' page (like label) */
387 define('FEATURE_NO_VIEW_LINK', 'viewlink');
388 /** True if module supports outcomes */
389 define('FEATURE_IDNUMBER', 'idnumber');
390 /** True if module supports groups */
391 define('FEATURE_GROUPS', 'groups');
392 /** True if module supports groupings */
393 define('FEATURE_GROUPINGS', 'groupings');
394 /** True if module supports groupmembersonly */
395 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
397 /** Type of module */
398 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
399 /** True if module supports intro editor */
400 define('FEATURE_MOD_INTRO', 'mod_intro');
401 /** True if module has default completion */
402 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
404 define('FEATURE_COMMENT', 'comment');
406 define('FEATURE_RATE', 'rate');
407 /** True if module supports backup/restore of moodle2 format */
408 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
410 /** True if module can show description on course main page */
411 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
413 /** Unspecified module archetype */
414 define('MOD_ARCHETYPE_OTHER', 0);
415 /** Resource-like type module */
416 define('MOD_ARCHETYPE_RESOURCE', 1);
417 /** Assignment module archetype */
418 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
419 /** System (not user-addable) module archetype */
420 define('MOD_ARCHETYPE_SYSTEM', 3);
422 /**
423  * Security token used for allowing access
424  * from external application such as web services.
425  * Scripts do not use any session, performance is relatively
426  * low because we need to load access info in each request.
427  * Scripts are executed in parallel.
428  */
429 define('EXTERNAL_TOKEN_PERMANENT', 0);
431 /**
432  * Security token used for allowing access
433  * of embedded applications, the code is executed in the
434  * active user session. Token is invalidated after user logs out.
435  * Scripts are executed serially - normal session locking is used.
436  */
437 define('EXTERNAL_TOKEN_EMBEDDED', 1);
439 /**
440  * The home page should be the site home
441  */
442 define('HOMEPAGE_SITE', 0);
443 /**
444  * The home page should be the users my page
445  */
446 define('HOMEPAGE_MY', 1);
447 /**
448  * The home page can be chosen by the user
449  */
450 define('HOMEPAGE_USER', 2);
452 /**
453  * Hub directory url (should be moodle.org)
454  */
455 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
458 /**
459  * Moodle.org url (should be moodle.org)
460  */
461 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
463 /**
464  * Moodle mobile app service name
465  */
466 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
468 /// PARAMETER HANDLING ////////////////////////////////////////////////////
470 /**
471  * Returns a particular value for the named variable, taken from
472  * POST or GET.  If the parameter doesn't exist then an error is
473  * thrown because we require this variable.
474  *
475  * This function should be used to initialise all required values
476  * in a script that are based on parameters.  Usually it will be
477  * used like this:
478  *    $id = required_param('id', PARAM_INT);
479  *
480  * Please note the $type parameter is now required and the value can not be array.
481  *
482  * @param string $parname the name of the page parameter we want
483  * @param string $type expected type of parameter
484  * @return mixed
485  */
486 function required_param($parname, $type) {
487     if (func_num_args() != 2 or empty($parname) or empty($type)) {
488         throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
489     }
490     if (isset($_POST[$parname])) {       // POST has precedence
491         $param = $_POST[$parname];
492     } else if (isset($_GET[$parname])) {
493         $param = $_GET[$parname];
494     } else {
495         print_error('missingparam', '', '', $parname);
496     }
498     if (is_array($param)) {
499         debugging('Invalid array parameter detected in required_param(): '.$parname);
500         // TODO: switch to fatal error in Moodle 2.3
501         //print_error('missingparam', '', '', $parname);
502         return required_param_array($parname, $type);
503     }
505     return clean_param($param, $type);
508 /**
509  * Returns a particular array value for the named variable, taken from
510  * POST or GET.  If the parameter doesn't exist then an error is
511  * thrown because we require this variable.
512  *
513  * This function should be used to initialise all required values
514  * in a script that are based on parameters.  Usually it will be
515  * used like this:
516  *    $ids = required_param_array('ids', PARAM_INT);
517  *
518  *  Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
519  *
520  * @param string $parname the name of the page parameter we want
521  * @param string $type expected type of parameter
522  * @return array
523  */
524 function required_param_array($parname, $type) {
525     if (func_num_args() != 2 or empty($parname) or empty($type)) {
526         throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
527     }
528     if (isset($_POST[$parname])) {       // POST has precedence
529         $param = $_POST[$parname];
530     } else if (isset($_GET[$parname])) {
531         $param = $_GET[$parname];
532     } else {
533         print_error('missingparam', '', '', $parname);
534     }
535     if (!is_array($param)) {
536         print_error('missingparam', '', '', $parname);
537     }
539     $result = array();
540     foreach($param as $key=>$value) {
541         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
542             debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
543             continue;
544         }
545         $result[$key] = clean_param($value, $type);
546     }
548     return $result;
551 /**
552  * Returns a particular value for the named variable, taken from
553  * POST or GET, otherwise returning a given default.
554  *
555  * This function should be used to initialise all optional values
556  * in a script that are based on parameters.  Usually it will be
557  * used like this:
558  *    $name = optional_param('name', 'Fred', PARAM_TEXT);
559  *
560  * Please note the $type parameter is now required and the value can not be array.
561  *
562  * @param string $parname the name of the page parameter we want
563  * @param mixed  $default the default value to return if nothing is found
564  * @param string $type expected type of parameter
565  * @return mixed
566  */
567 function optional_param($parname, $default, $type) {
568     if (func_num_args() != 3 or empty($parname) or empty($type)) {
569         throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
570     }
571     if (!isset($default)) {
572         $default = null;
573     }
575     if (isset($_POST[$parname])) {       // POST has precedence
576         $param = $_POST[$parname];
577     } else if (isset($_GET[$parname])) {
578         $param = $_GET[$parname];
579     } else {
580         return $default;
581     }
583     if (is_array($param)) {
584         debugging('Invalid array parameter detected in required_param(): '.$parname);
585         // TODO: switch to $default in Moodle 2.3
586         //return $default;
587         return optional_param_array($parname, $default, $type);
588     }
590     return clean_param($param, $type);
593 /**
594  * Returns a particular array value for the named variable, taken from
595  * POST or GET, otherwise returning a given default.
596  *
597  * This function should be used to initialise all optional values
598  * in a script that are based on parameters.  Usually it will be
599  * used like this:
600  *    $ids = optional_param('id', array(), PARAM_INT);
601  *
602  *  Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
603  *
604  * @param string $parname the name of the page parameter we want
605  * @param mixed  $default the default value to return if nothing is found
606  * @param string $type expected type of parameter
607  * @return array
608  */
609 function optional_param_array($parname, $default, $type) {
610     if (func_num_args() != 3 or empty($parname) or empty($type)) {
611         throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
612     }
614     if (isset($_POST[$parname])) {       // POST has precedence
615         $param = $_POST[$parname];
616     } else if (isset($_GET[$parname])) {
617         $param = $_GET[$parname];
618     } else {
619         return $default;
620     }
621     if (!is_array($param)) {
622         debugging('optional_param_array() expects array parameters only: '.$parname);
623         return $default;
624     }
626     $result = array();
627     foreach($param as $key=>$value) {
628         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
629             debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
630             continue;
631         }
632         $result[$key] = clean_param($value, $type);
633     }
635     return $result;
638 /**
639  * Strict validation of parameter values, the values are only converted
640  * to requested PHP type. Internally it is using clean_param, the values
641  * before and after cleaning must be equal - otherwise
642  * an invalid_parameter_exception is thrown.
643  * Objects and classes are not accepted.
644  *
645  * @param mixed $param
646  * @param string $type PARAM_ constant
647  * @param bool $allownull are nulls valid value?
648  * @param string $debuginfo optional debug information
649  * @return mixed the $param value converted to PHP type or invalid_parameter_exception
650  */
651 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
652     if (is_null($param)) {
653         if ($allownull == NULL_ALLOWED) {
654             return null;
655         } else {
656             throw new invalid_parameter_exception($debuginfo);
657         }
658     }
659     if (is_array($param) or is_object($param)) {
660         throw new invalid_parameter_exception($debuginfo);
661     }
663     $cleaned = clean_param($param, $type);
664     if ((string)$param !== (string)$cleaned) {
665         // conversion to string is usually lossless
666         throw new invalid_parameter_exception($debuginfo);
667     }
669     return $cleaned;
672 /**
673  * Makes sure array contains only the allowed types,
674  * this function does not validate array key names!
675  * <code>
676  * $options = clean_param($options, PARAM_INT);
677  * </code>
678  *
679  * @param array $param the variable array we are cleaning
680  * @param string $type expected format of param after cleaning.
681  * @param bool $recursive clean recursive arrays
682  * @return array
683  */
684 function clean_param_array(array $param = null, $type, $recursive = false) {
685     $param = (array)$param; // convert null to empty array
686     foreach ($param as $key => $value) {
687         if (is_array($value)) {
688             if ($recursive) {
689                 $param[$key] = clean_param_array($value, $type, true);
690             } else {
691                 throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
692             }
693         } else {
694             $param[$key] = clean_param($value, $type);
695         }
696     }
697     return $param;
700 /**
701  * Used by {@link optional_param()} and {@link required_param()} to
702  * clean the variables and/or cast to specific types, based on
703  * an options field.
704  * <code>
705  * $course->format = clean_param($course->format, PARAM_ALPHA);
706  * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
707  * </code>
708  *
709  * @param mixed $param the variable we are cleaning
710  * @param string $type expected format of param after cleaning.
711  * @return mixed
712  */
713 function clean_param($param, $type) {
715     global $CFG;
717     if (is_array($param)) {
718         throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
719     } else if (is_object($param)) {
720         if (method_exists($param, '__toString')) {
721             $param = $param->__toString();
722         } else {
723             throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
724         }
725     }
727     switch ($type) {
728         case PARAM_RAW:          // no cleaning at all
729             $param = fix_utf8($param);
730             return $param;
732         case PARAM_RAW_TRIMMED:         // no cleaning, but strip leading and trailing whitespace.
733             $param = fix_utf8($param);
734             return trim($param);
736         case PARAM_CLEAN:        // General HTML cleaning, try to use more specific type if possible
737             // this is deprecated!, please use more specific type instead
738             if (is_numeric($param)) {
739                 return $param;
740             }
741             $param = fix_utf8($param);
742             return clean_text($param);     // Sweep for scripts, etc
744         case PARAM_CLEANHTML:    // clean html fragment
745             $param = fix_utf8($param);
746             $param = clean_text($param, FORMAT_HTML);     // Sweep for scripts, etc
747             return trim($param);
749         case PARAM_INT:
750             return (int)$param;  // Convert to integer
752         case PARAM_FLOAT:
753         case PARAM_NUMBER:
754             return (float)$param;  // Convert to float
756         case PARAM_ALPHA:        // Remove everything not a-z
757             return preg_replace('/[^a-zA-Z]/i', '', $param);
759         case PARAM_ALPHAEXT:     // Remove everything not a-zA-Z_- (originally allowed "/" too)
760             return preg_replace('/[^a-zA-Z_-]/i', '', $param);
762         case PARAM_ALPHANUM:     // Remove everything not a-zA-Z0-9
763             return preg_replace('/[^A-Za-z0-9]/i', '', $param);
765         case PARAM_ALPHANUMEXT:     // Remove everything not a-zA-Z0-9_-
766             return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
768         case PARAM_SEQUENCE:     // Remove everything not 0-9,
769             return preg_replace('/[^0-9,]/i', '', $param);
771         case PARAM_BOOL:         // Convert to 1 or 0
772             $tempstr = strtolower($param);
773             if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
774                 $param = 1;
775             } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
776                 $param = 0;
777             } else {
778                 $param = empty($param) ? 0 : 1;
779             }
780             return $param;
782         case PARAM_NOTAGS:       // Strip all tags
783             $param = fix_utf8($param);
784             return strip_tags($param);
786         case PARAM_TEXT:    // leave only tags needed for multilang
787             $param = fix_utf8($param);
788             // if the multilang syntax is not correct we strip all tags
789             // because it would break xhtml strict which is required for accessibility standards
790             // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
791             do {
792                 if (strpos($param, '</lang>') !== false) {
793                     // old and future mutilang syntax
794                     $param = strip_tags($param, '<lang>');
795                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
796                         break;
797                     }
798                     $open = false;
799                     foreach ($matches[0] as $match) {
800                         if ($match === '</lang>') {
801                             if ($open) {
802                                 $open = false;
803                                 continue;
804                             } else {
805                                 break 2;
806                             }
807                         }
808                         if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
809                             break 2;
810                         } else {
811                             $open = true;
812                         }
813                     }
814                     if ($open) {
815                         break;
816                     }
817                     return $param;
819                 } else if (strpos($param, '</span>') !== false) {
820                     // current problematic multilang syntax
821                     $param = strip_tags($param, '<span>');
822                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
823                         break;
824                     }
825                     $open = false;
826                     foreach ($matches[0] as $match) {
827                         if ($match === '</span>') {
828                             if ($open) {
829                                 $open = false;
830                                 continue;
831                             } else {
832                                 break 2;
833                             }
834                         }
835                         if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
836                             break 2;
837                         } else {
838                             $open = true;
839                         }
840                     }
841                     if ($open) {
842                         break;
843                     }
844                     return $param;
845                 }
846             } while (false);
847             // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
848             return strip_tags($param);
850         case PARAM_COMPONENT:
851             // we do not want any guessing here, either the name is correct or not
852             // please note only normalised component names are accepted
853             if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
854                 return '';
855             }
856             if (strpos($param, '__') !== false) {
857                 return '';
858             }
859             if (strpos($param, 'mod_') === 0) {
860                 // module names must not contain underscores because we need to differentiate them from invalid plugin types
861                 if (substr_count($param, '_') != 1) {
862                     return '';
863                 }
864             }
865             return $param;
867         case PARAM_PLUGIN:
868         case PARAM_AREA:
869             // we do not want any guessing here, either the name is correct or not
870             if (!preg_match('/^[a-z][a-z0-9_]*[a-z0-9]$/', $param)) {
871                 return '';
872             }
873             if (strpos($param, '__') !== false) {
874                 return '';
875             }
876             return $param;
878         case PARAM_SAFEDIR:      // Remove everything not a-zA-Z0-9_-
879             return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
881         case PARAM_SAFEPATH:     // Remove everything not a-zA-Z0-9/_-
882             return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
884         case PARAM_FILE:         // Strip all suspicious characters from filename
885             $param = fix_utf8($param);
886             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
887             $param = preg_replace('~\.\.+~', '', $param);
888             if ($param === '.') {
889                 $param = '';
890             }
891             return $param;
893         case PARAM_PATH:         // Strip all suspicious characters from file path
894             $param = fix_utf8($param);
895             $param = str_replace('\\', '/', $param);
896             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
897             $param = preg_replace('~\.\.+~', '', $param);
898             $param = preg_replace('~//+~', '/', $param);
899             return preg_replace('~/(\./)+~', '/', $param);
901         case PARAM_HOST:         // allow FQDN or IPv4 dotted quad
902             $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
903             // match ipv4 dotted quad
904             if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
905                 // confirm values are ok
906                 if ( $match[0] > 255
907                      || $match[1] > 255
908                      || $match[3] > 255
909                      || $match[4] > 255 ) {
910                     // hmmm, what kind of dotted quad is this?
911                     $param = '';
912                 }
913             } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
914                        && !preg_match('/^[\.-]/',  $param) // no leading dots/hyphens
915                        && !preg_match('/[\.-]$/',  $param) // no trailing dots/hyphens
916                        ) {
917                 // all is ok - $param is respected
918             } else {
919                 // all is not ok...
920                 $param='';
921             }
922             return $param;
924         case PARAM_URL:          // allow safe ftp, http, mailto urls
925             $param = fix_utf8($param);
926             include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
927             if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
928                 // all is ok, param is respected
929             } else {
930                 $param =''; // not really ok
931             }
932             return $param;
934         case PARAM_LOCALURL:     // allow http absolute, root relative and relative URLs within wwwroot
935             $param = clean_param($param, PARAM_URL);
936             if (!empty($param)) {
937                 if (preg_match(':^/:', $param)) {
938                     // root-relative, ok!
939                 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
940                     // absolute, and matches our wwwroot
941                 } else {
942                     // relative - let's make sure there are no tricks
943                     if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
944                         // looks ok.
945                     } else {
946                         $param = '';
947                     }
948                 }
949             }
950             return $param;
952         case PARAM_PEM:
953             $param = trim($param);
954             // PEM formatted strings may contain letters/numbers and the symbols
955             // forward slash: /
956             // plus sign:     +
957             // equal sign:    =
958             // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
959             if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
960                 list($wholething, $body) = $matches;
961                 unset($wholething, $matches);
962                 $b64 = clean_param($body, PARAM_BASE64);
963                 if (!empty($b64)) {
964                     return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
965                 } else {
966                     return '';
967                 }
968             }
969             return '';
971         case PARAM_BASE64:
972             if (!empty($param)) {
973                 // PEM formatted strings may contain letters/numbers and the symbols
974                 // forward slash: /
975                 // plus sign:     +
976                 // equal sign:    =
977                 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
978                     return '';
979                 }
980                 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
981                 // Each line of base64 encoded data must be 64 characters in
982                 // length, except for the last line which may be less than (or
983                 // equal to) 64 characters long.
984                 for ($i=0, $j=count($lines); $i < $j; $i++) {
985                     if ($i + 1 == $j) {
986                         if (64 < strlen($lines[$i])) {
987                             return '';
988                         }
989                         continue;
990                     }
992                     if (64 != strlen($lines[$i])) {
993                         return '';
994                     }
995                 }
996                 return implode("\n",$lines);
997             } else {
998                 return '';
999             }
1001         case PARAM_TAG:
1002             $param = fix_utf8($param);
1003             // Please note it is not safe to use the tag name directly anywhere,
1004             // it must be processed with s(), urlencode() before embedding anywhere.
1005             // remove some nasties
1006             $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1007             //convert many whitespace chars into one
1008             $param = preg_replace('/\s+/', ' ', $param);
1009             $textlib = textlib_get_instance();
1010             $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
1011             return $param;
1013         case PARAM_TAGLIST:
1014             $param = fix_utf8($param);
1015             $tags = explode(',', $param);
1016             $result = array();
1017             foreach ($tags as $tag) {
1018                 $res = clean_param($tag, PARAM_TAG);
1019                 if ($res !== '') {
1020                     $result[] = $res;
1021                 }
1022             }
1023             if ($result) {
1024                 return implode(',', $result);
1025             } else {
1026                 return '';
1027             }
1029         case PARAM_CAPABILITY:
1030             if (get_capability_info($param)) {
1031                 return $param;
1032             } else {
1033                 return '';
1034             }
1036         case PARAM_PERMISSION:
1037             $param = (int)$param;
1038             if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1039                 return $param;
1040             } else {
1041                 return CAP_INHERIT;
1042             }
1044         case PARAM_AUTH:
1045             $param = clean_param($param, PARAM_PLUGIN);
1046             if (empty($param)) {
1047                 return '';
1048             } else if (exists_auth_plugin($param)) {
1049                 return $param;
1050             } else {
1051                 return '';
1052             }
1054         case PARAM_LANG:
1055             $param = clean_param($param, PARAM_SAFEDIR);
1056             if (get_string_manager()->translation_exists($param)) {
1057                 return $param;
1058             } else {
1059                 return ''; // Specified language is not installed or param malformed
1060             }
1062         case PARAM_THEME:
1063             $param = clean_param($param, PARAM_PLUGIN);
1064             if (empty($param)) {
1065                 return '';
1066             } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1067                 return $param;
1068             } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1069                 return $param;
1070             } else {
1071                 return '';  // Specified theme is not installed
1072             }
1074         case PARAM_USERNAME:
1075             $param = fix_utf8($param);
1076             $param = str_replace(" " , "", $param);
1077             $param = moodle_strtolower($param);  // Convert uppercase to lowercase MDL-16919
1078             if (empty($CFG->extendedusernamechars)) {
1079                 // regular expression, eliminate all chars EXCEPT:
1080                 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1081                 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1082             }
1083             return $param;
1085         case PARAM_EMAIL:
1086             $param = fix_utf8($param);
1087             if (validate_email($param)) {
1088                 return $param;
1089             } else {
1090                 return '';
1091             }
1093         case PARAM_STRINGID:
1094             if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1095                 return $param;
1096             } else {
1097                 return '';
1098             }
1100         case PARAM_TIMEZONE:    //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1101             $param = fix_utf8($param);
1102             $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1103             if (preg_match($timezonepattern, $param)) {
1104                 return $param;
1105             } else {
1106                 return '';
1107             }
1109         default:                 // throw error, switched parameters in optional_param or another serious problem
1110             print_error("unknownparamtype", '', '', $type);
1111     }
1114 /**
1115  * Makes sure the data is using valid utf8, invalid characters are discarded.
1116  *
1117  * Note: this function is not intended for full objects with methods and private properties.
1118  *
1119  * @param mixed $value
1120  * @return mixed with proper utf-8 encoding
1121  */
1122 function fix_utf8($value) {
1123     if (is_null($value) or $value === '') {
1124         return $value;
1126     } else if (is_string($value)) {
1127         if ((string)(int)$value === $value) {
1128             // shortcut
1129             return $value;
1130         }
1131         return iconv('UTF-8', 'UTF-8//IGNORE', $value);
1133     } else if (is_array($value)) {
1134         foreach ($value as $k=>$v) {
1135             $value[$k] = fix_utf8($v);
1136         }
1137         return $value;
1139     } else if (is_object($value)) {
1140         $value = clone($value); // do not modify original
1141         foreach ($value as $k=>$v) {
1142             $value->$k = fix_utf8($v);
1143         }
1144         return $value;
1146     } else {
1147         // this is some other type, no utf-8 here
1148         return $value;
1149     }
1152 /**
1153  * Return true if given value is integer or string with integer value
1154  *
1155  * @param mixed $value String or Int
1156  * @return bool true if number, false if not
1157  */
1158 function is_number($value) {
1159     if (is_int($value)) {
1160         return true;
1161     } else if (is_string($value)) {
1162         return ((string)(int)$value) === $value;
1163     } else {
1164         return false;
1165     }
1168 /**
1169  * Returns host part from url
1170  * @param string $url full url
1171  * @return string host, null if not found
1172  */
1173 function get_host_from_url($url) {
1174     preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1175     if ($matches) {
1176         return $matches[1];
1177     }
1178     return null;
1181 /**
1182  * Tests whether anything was returned by text editor
1183  *
1184  * This function is useful for testing whether something you got back from
1185  * the HTML editor actually contains anything. Sometimes the HTML editor
1186  * appear to be empty, but actually you get back a <br> tag or something.
1187  *
1188  * @param string $string a string containing HTML.
1189  * @return boolean does the string contain any actual content - that is text,
1190  * images, objects, etc.
1191  */
1192 function html_is_blank($string) {
1193     return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1196 /**
1197  * Set a key in global configuration
1198  *
1199  * Set a key/value pair in both this session's {@link $CFG} global variable
1200  * and in the 'config' database table for future sessions.
1201  *
1202  * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1203  * In that case it doesn't affect $CFG.
1204  *
1205  * A NULL value will delete the entry.
1206  *
1207  * @global object
1208  * @global object
1209  * @param string $name the key to set
1210  * @param string $value the value to set (without magic quotes)
1211  * @param string $plugin (optional) the plugin scope, default NULL
1212  * @return bool true or exception
1213  */
1214 function set_config($name, $value, $plugin=NULL) {
1215     global $CFG, $DB;
1217     if (empty($plugin)) {
1218         if (!array_key_exists($name, $CFG->config_php_settings)) {
1219             // So it's defined for this invocation at least
1220             if (is_null($value)) {
1221                 unset($CFG->$name);
1222             } else {
1223                 $CFG->$name = (string)$value; // settings from db are always strings
1224             }
1225         }
1227         if ($DB->get_field('config', 'name', array('name'=>$name))) {
1228             if ($value === null) {
1229                 $DB->delete_records('config', array('name'=>$name));
1230             } else {
1231                 $DB->set_field('config', 'value', $value, array('name'=>$name));
1232             }
1233         } else {
1234             if ($value !== null) {
1235                 $config = new stdClass();
1236                 $config->name  = $name;
1237                 $config->value = $value;
1238                 $DB->insert_record('config', $config, false);
1239             }
1240         }
1242     } else { // plugin scope
1243         if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1244             if ($value===null) {
1245                 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1246             } else {
1247                 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1248             }
1249         } else {
1250             if ($value !== null) {
1251                 $config = new stdClass();
1252                 $config->plugin = $plugin;
1253                 $config->name   = $name;
1254                 $config->value  = $value;
1255                 $DB->insert_record('config_plugins', $config, false);
1256             }
1257         }
1258     }
1260     return true;
1263 /**
1264  * Get configuration values from the global config table
1265  * or the config_plugins table.
1266  *
1267  * If called with one parameter, it will load all the config
1268  * variables for one plugin, and return them as an object.
1269  *
1270  * If called with 2 parameters it will return a string single
1271  * value or false if the value is not found.
1272  *
1273  * @param string $plugin full component name
1274  * @param string $name default NULL
1275  * @return mixed hash-like object or single value, return false no config found
1276  */
1277 function get_config($plugin, $name = NULL) {
1278     global $CFG, $DB;
1280     // normalise component name
1281     if ($plugin === 'moodle' or $plugin === 'core') {
1282         $plugin = NULL;
1283     }
1285     if (!empty($name)) { // the user is asking for a specific value
1286         if (!empty($plugin)) {
1287             if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1288                 // setting forced in config file
1289                 return $CFG->forced_plugin_settings[$plugin][$name];
1290             } else {
1291                 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1292             }
1293         } else {
1294             if (array_key_exists($name, $CFG->config_php_settings)) {
1295                 // setting force in config file
1296                 return $CFG->config_php_settings[$name];
1297             } else {
1298                 return $DB->get_field('config', 'value', array('name'=>$name));
1299             }
1300         }
1301     }
1303     // the user is after a recordset
1304     if ($plugin) {
1305         $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1306         if (isset($CFG->forced_plugin_settings[$plugin])) {
1307             foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1308                 if (is_null($v) or is_array($v) or is_object($v)) {
1309                     // we do not want any extra mess here, just real settings that could be saved in db
1310                     unset($localcfg[$n]);
1311                 } else {
1312                     //convert to string as if it went through the DB
1313                     $localcfg[$n] = (string)$v;
1314                 }
1315             }
1316         }
1317         if ($localcfg) {
1318             return (object)$localcfg;
1319         } else {
1320             return new stdClass();
1321         }
1323     } else {
1324         // this part is not really used any more, but anyway...
1325         $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1326         foreach($CFG->config_php_settings as $n=>$v) {
1327             if (is_null($v) or is_array($v) or is_object($v)) {
1328                 // we do not want any extra mess here, just real settings that could be saved in db
1329                 unset($localcfg[$n]);
1330             } else {
1331                 //convert to string as if it went through the DB
1332                 $localcfg[$n] = (string)$v;
1333             }
1334         }
1335         return (object)$localcfg;
1336     }
1339 /**
1340  * Removes a key from global configuration
1341  *
1342  * @param string $name the key to set
1343  * @param string $plugin (optional) the plugin scope
1344  * @global object
1345  * @return boolean whether the operation succeeded.
1346  */
1347 function unset_config($name, $plugin=NULL) {
1348     global $CFG, $DB;
1350     if (empty($plugin)) {
1351         unset($CFG->$name);
1352         $DB->delete_records('config', array('name'=>$name));
1353     } else {
1354         $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1355     }
1357     return true;
1360 /**
1361  * Remove all the config variables for a given plugin.
1362  *
1363  * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1364  * @return boolean whether the operation succeeded.
1365  */
1366 function unset_all_config_for_plugin($plugin) {
1367     global $DB;
1368     $DB->delete_records('config_plugins', array('plugin' => $plugin));
1369     $like = $DB->sql_like('name', '?', true, true, false, '|');
1370     $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1371     $DB->delete_records_select('config', $like, $params);
1372     return true;
1375 /**
1376  * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1377  *
1378  * All users are verified if they still have the necessary capability.
1379  *
1380  * @param string $value the value of the config setting.
1381  * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1382  * @param bool $include admins, include administrators
1383  * @return array of user objects.
1384  */
1385 function get_users_from_config($value, $capability, $includeadmins = true) {
1386     global $CFG, $DB;
1388     if (empty($value) or $value === '$@NONE@$') {
1389         return array();
1390     }
1392     // we have to make sure that users still have the necessary capability,
1393     // it should be faster to fetch them all first and then test if they are present
1394     // instead of validating them one-by-one
1395     $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1396     if ($includeadmins) {
1397         $admins = get_admins();
1398         foreach ($admins as $admin) {
1399             $users[$admin->id] = $admin;
1400         }
1401     }
1403     if ($value === '$@ALL@$') {
1404         return $users;
1405     }
1407     $result = array(); // result in correct order
1408     $allowed = explode(',', $value);
1409     foreach ($allowed as $uid) {
1410         if (isset($users[$uid])) {
1411             $user = $users[$uid];
1412             $result[$user->id] = $user;
1413         }
1414     }
1416     return $result;
1420 /**
1421  * Invalidates browser caches and cached data in temp
1422  * @return void
1423  */
1424 function purge_all_caches() {
1425     global $CFG;
1427     reset_text_filters_cache();
1428     js_reset_all_caches();
1429     theme_reset_all_caches();
1430     get_string_manager()->reset_caches();
1432     // purge all other caches: rss, simplepie, etc.
1433     remove_dir($CFG->cachedir.'', true);
1435     // make sure cache dir is writable, throws exception if not
1436     make_cache_directory('');
1438     // hack: this script may get called after the purifier was initialised,
1439     // but we do not want to verify repeatedly this exists in each call
1440     make_cache_directory('htmlpurifier');
1443 /**
1444  * Get volatile flags
1445  *
1446  * @param string $type
1447  * @param int    $changedsince default null
1448  * @return records array
1449  */
1450 function get_cache_flags($type, $changedsince=NULL) {
1451     global $DB;
1453     $params = array('type'=>$type, 'expiry'=>time());
1454     $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1455     if ($changedsince !== NULL) {
1456         $params['changedsince'] = $changedsince;
1457         $sqlwhere .= " AND timemodified > :changedsince";
1458     }
1459     $cf = array();
1461     if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1462         foreach ($flags as $flag) {
1463             $cf[$flag->name] = $flag->value;
1464         }
1465     }
1466     return $cf;
1469 /**
1470  * Get volatile flags
1471  *
1472  * @param string $type
1473  * @param string $name
1474  * @param int    $changedsince default null
1475  * @return records array
1476  */
1477 function get_cache_flag($type, $name, $changedsince=NULL) {
1478     global $DB;
1480     $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1482     $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1483     if ($changedsince !== NULL) {
1484         $params['changedsince'] = $changedsince;
1485         $sqlwhere .= " AND timemodified > :changedsince";
1486     }
1488     return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1491 /**
1492  * Set a volatile flag
1493  *
1494  * @param string $type the "type" namespace for the key
1495  * @param string $name the key to set
1496  * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1497  * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1498  * @return bool Always returns true
1499  */
1500 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1501     global $DB;
1503     $timemodified = time();
1504     if ($expiry===NULL || $expiry < $timemodified) {
1505         $expiry = $timemodified + 24 * 60 * 60;
1506     } else {
1507         $expiry = (int)$expiry;
1508     }
1510     if ($value === NULL) {
1511         unset_cache_flag($type,$name);
1512         return true;
1513     }
1515     if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1516         if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1517             return true; //no need to update; helps rcache too
1518         }
1519         $f->value        = $value;
1520         $f->expiry       = $expiry;
1521         $f->timemodified = $timemodified;
1522         $DB->update_record('cache_flags', $f);
1523     } else {
1524         $f = new stdClass();
1525         $f->flagtype     = $type;
1526         $f->name         = $name;
1527         $f->value        = $value;
1528         $f->expiry       = $expiry;
1529         $f->timemodified = $timemodified;
1530         $DB->insert_record('cache_flags', $f);
1531     }
1532     return true;
1535 /**
1536  * Removes a single volatile flag
1537  *
1538  * @global object
1539  * @param string $type the "type" namespace for the key
1540  * @param string $name the key to set
1541  * @return bool
1542  */
1543 function unset_cache_flag($type, $name) {
1544     global $DB;
1545     $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1546     return true;
1549 /**
1550  * Garbage-collect volatile flags
1551  *
1552  * @return bool Always returns true
1553  */
1554 function gc_cache_flags() {
1555     global $DB;
1556     $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1557     return true;
1560 // USER PREFERENCE API
1562 /**
1563  * Refresh user preference cache. This is used most often for $USER
1564  * object that is stored in session, but it also helps with performance in cron script.
1565  *
1566  * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1567  *
1568  * @package  core
1569  * @category preference
1570  * @access   public
1571  * @param    stdClass         $user          User object. Preferences are preloaded into 'preference' property
1572  * @param    int              $cachelifetime Cache life time on the current page (in seconds)
1573  * @throws   coding_exception
1574  * @return   null
1575  */
1576 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1577     global $DB;
1578     static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1580     if (!isset($user->id)) {
1581         throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1582     }
1584     if (empty($user->id) or isguestuser($user->id)) {
1585         // No permanent storage for not-logged-in users and guest
1586         if (!isset($user->preference)) {
1587             $user->preference = array();
1588         }
1589         return;
1590     }
1592     $timenow = time();
1594     if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1595         // Already loaded at least once on this page. Are we up to date?
1596         if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1597             // no need to reload - we are on the same page and we loaded prefs just a moment ago
1598             return;
1600         } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1601             // no change since the lastcheck on this page
1602             $user->preference['_lastloaded'] = $timenow;
1603             return;
1604         }
1605     }
1607     // OK, so we have to reload all preferences
1608     $loadedusers[$user->id] = true;
1609     $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1610     $user->preference['_lastloaded'] = $timenow;
1613 /**
1614  * Called from set/unset_user_preferences, so that the prefs can
1615  * be correctly reloaded in different sessions.
1616  *
1617  * NOTE: internal function, do not call from other code.
1618  *
1619  * @package core
1620  * @access  private
1621  * @param   integer         $userid the user whose prefs were changed.
1622  */
1623 function mark_user_preferences_changed($userid) {
1624     global $CFG;
1626     if (empty($userid) or isguestuser($userid)) {
1627         // no cache flags for guest and not-logged-in users
1628         return;
1629     }
1631     set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1634 /**
1635  * Sets a preference for the specified user.
1636  *
1637  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1638  *
1639  * @package  core
1640  * @category preference
1641  * @access   public
1642  * @param    string            $name  The key to set as preference for the specified user
1643  * @param    string            $value The value to set for the $name key in the specified user's
1644  *                                    record, null means delete current value.
1645  * @param    stdClass|int|null $user  A moodle user object or id, null means current user
1646  * @throws   coding_exception
1647  * @return   bool                     Always true or exception
1648  */
1649 function set_user_preference($name, $value, $user = null) {
1650     global $USER, $DB;
1652     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1653         throw new coding_exception('Invalid preference name in set_user_preference() call');
1654     }
1656     if (is_null($value)) {
1657         // null means delete current
1658         return unset_user_preference($name, $user);
1659     } else if (is_object($value)) {
1660         throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1661     } else if (is_array($value)) {
1662         throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1663     }
1664     $value = (string)$value;
1665     if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1666         throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1667     }
1669     if (is_null($user)) {
1670         $user = $USER;
1671     } else if (isset($user->id)) {
1672         // $user is valid object
1673     } else if (is_numeric($user)) {
1674         $user = (object)array('id'=>(int)$user);
1675     } else {
1676         throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1677     }
1679     check_user_preferences_loaded($user);
1681     if (empty($user->id) or isguestuser($user->id)) {
1682         // no permanent storage for not-logged-in users and guest
1683         $user->preference[$name] = $value;
1684         return true;
1685     }
1687     if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1688         if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1689             // preference already set to this value
1690             return true;
1691         }
1692         $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1694     } else {
1695         $preference = new stdClass();
1696         $preference->userid = $user->id;
1697         $preference->name   = $name;
1698         $preference->value  = $value;
1699         $DB->insert_record('user_preferences', $preference);
1700     }
1702     // update value in cache
1703     $user->preference[$name] = $value;
1705     // set reload flag for other sessions
1706     mark_user_preferences_changed($user->id);
1708     return true;
1711 /**
1712  * Sets a whole array of preferences for the current user
1713  *
1714  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1715  *
1716  * @package  core
1717  * @category preference
1718  * @access   public
1719  * @param    array             $prefarray An array of key/value pairs to be set
1720  * @param    stdClass|int|null $user      A moodle user object or id, null means current user
1721  * @return   bool                         Always true or exception
1722  */
1723 function set_user_preferences(array $prefarray, $user = null) {
1724     foreach ($prefarray as $name => $value) {
1725         set_user_preference($name, $value, $user);
1726     }
1727     return true;
1730 /**
1731  * Unsets a preference completely by deleting it from the database
1732  *
1733  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1734  *
1735  * @package  core
1736  * @category preference
1737  * @access   public
1738  * @param    string            $name The key to unset as preference for the specified user
1739  * @param    stdClass|int|null $user A moodle user object or id, null means current user
1740  * @throws   coding_exception
1741  * @return   bool                    Always true or exception
1742  */
1743 function unset_user_preference($name, $user = null) {
1744     global $USER, $DB;
1746     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1747         throw new coding_exception('Invalid preference name in unset_user_preference() call');
1748     }
1750     if (is_null($user)) {
1751         $user = $USER;
1752     } else if (isset($user->id)) {
1753         // $user is valid object
1754     } else if (is_numeric($user)) {
1755         $user = (object)array('id'=>(int)$user);
1756     } else {
1757         throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1758     }
1760     check_user_preferences_loaded($user);
1762     if (empty($user->id) or isguestuser($user->id)) {
1763         // no permanent storage for not-logged-in user and guest
1764         unset($user->preference[$name]);
1765         return true;
1766     }
1768     // delete from DB
1769     $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1771     // delete the preference from cache
1772     unset($user->preference[$name]);
1774     // set reload flag for other sessions
1775     mark_user_preferences_changed($user->id);
1777     return true;
1780 /**
1781  * Used to fetch user preference(s)
1782  *
1783  * If no arguments are supplied this function will return
1784  * all of the current user preferences as an array.
1785  *
1786  * If a name is specified then this function
1787  * attempts to return that particular preference value.  If
1788  * none is found, then the optional value $default is returned,
1789  * otherwise NULL.
1790  *
1791  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1792  *
1793  * @package  core
1794  * @category preference
1795  * @access   public
1796  * @param    string            $name    Name of the key to use in finding a preference value
1797  * @param    mixed|null        $default Value to be returned if the $name key is not set in the user preferences
1798  * @param    stdClass|int|null $user    A moodle user object or id, null means current user
1799  * @throws   coding_exception
1800  * @return   string|mixed|null          A string containing the value of a single preference. An
1801  *                                      array with all of the preferences or null
1802  */
1803 function get_user_preferences($name = null, $default = null, $user = null) {
1804     global $USER;
1806     if (is_null($name)) {
1807         // all prefs
1808     } else if (is_numeric($name) or $name === '_lastloaded') {
1809         throw new coding_exception('Invalid preference name in get_user_preferences() call');
1810     }
1812     if (is_null($user)) {
1813         $user = $USER;
1814     } else if (isset($user->id)) {
1815         // $user is valid object
1816     } else if (is_numeric($user)) {
1817         $user = (object)array('id'=>(int)$user);
1818     } else {
1819         throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1820     }
1822     check_user_preferences_loaded($user);
1824     if (empty($name)) {
1825         return $user->preference; // All values
1826     } else if (isset($user->preference[$name])) {
1827         return $user->preference[$name]; // The single string value
1828     } else {
1829         return $default; // Default value (null if not specified)
1830     }
1833 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1835 /**
1836  * Given date parts in user time produce a GMT timestamp.
1837  *
1838  * @package core
1839  * @category time
1840  * @param int $year The year part to create timestamp of
1841  * @param int $month The month part to create timestamp of
1842  * @param int $day The day part to create timestamp of
1843  * @param int $hour The hour part to create timestamp of
1844  * @param int $minute The minute part to create timestamp of
1845  * @param int $second The second part to create timestamp of
1846  * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1847  *             if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
1848  * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1849  *             applied only if timezone is 99 or string.
1850  * @return int GMT timestamp
1851  */
1852 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1854     //save input timezone, required for dst offset check.
1855     $passedtimezone = $timezone;
1857     $timezone = get_user_timezone_offset($timezone);
1859     if (abs($timezone) > 13) {  //server time
1860         $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1861     } else {
1862         $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1863         $time = usertime($time, $timezone);
1865         //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1866         if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1867             $time -= dst_offset_on($time, $passedtimezone);
1868         }
1869     }
1871     return $time;
1875 /**
1876  * Format a date/time (seconds) as weeks, days, hours etc as needed
1877  *
1878  * Given an amount of time in seconds, returns string
1879  * formatted nicely as weeks, days, hours etc as needed
1880  *
1881  * @package core
1882  * @category time
1883  * @uses MINSECS
1884  * @uses HOURSECS
1885  * @uses DAYSECS
1886  * @uses YEARSECS
1887  * @param int $totalsecs Time in seconds
1888  * @param object $str Should be a time object
1889  * @return string A nicely formatted date/time string
1890  */
1891  function format_time($totalsecs, $str=NULL) {
1893     $totalsecs = abs($totalsecs);
1895     if (!$str) {  // Create the str structure the slow way
1896         $str = new stdClass();
1897         $str->day   = get_string('day');
1898         $str->days  = get_string('days');
1899         $str->hour  = get_string('hour');
1900         $str->hours = get_string('hours');
1901         $str->min   = get_string('min');
1902         $str->mins  = get_string('mins');
1903         $str->sec   = get_string('sec');
1904         $str->secs  = get_string('secs');
1905         $str->year  = get_string('year');
1906         $str->years = get_string('years');
1907     }
1910     $years     = floor($totalsecs/YEARSECS);
1911     $remainder = $totalsecs - ($years*YEARSECS);
1912     $days      = floor($remainder/DAYSECS);
1913     $remainder = $totalsecs - ($days*DAYSECS);
1914     $hours     = floor($remainder/HOURSECS);
1915     $remainder = $remainder - ($hours*HOURSECS);
1916     $mins      = floor($remainder/MINSECS);
1917     $secs      = $remainder - ($mins*MINSECS);
1919     $ss = ($secs == 1)  ? $str->sec  : $str->secs;
1920     $sm = ($mins == 1)  ? $str->min  : $str->mins;
1921     $sh = ($hours == 1) ? $str->hour : $str->hours;
1922     $sd = ($days == 1)  ? $str->day  : $str->days;
1923     $sy = ($years == 1)  ? $str->year  : $str->years;
1925     $oyears = '';
1926     $odays = '';
1927     $ohours = '';
1928     $omins = '';
1929     $osecs = '';
1931     if ($years)  $oyears  = $years .' '. $sy;
1932     if ($days)  $odays  = $days .' '. $sd;
1933     if ($hours) $ohours = $hours .' '. $sh;
1934     if ($mins)  $omins  = $mins .' '. $sm;
1935     if ($secs)  $osecs  = $secs .' '. $ss;
1937     if ($years) return trim($oyears .' '. $odays);
1938     if ($days)  return trim($odays .' '. $ohours);
1939     if ($hours) return trim($ohours .' '. $omins);
1940     if ($mins)  return trim($omins .' '. $osecs);
1941     if ($secs)  return $osecs;
1942     return get_string('now');
1945 /**
1946  * Returns a formatted string that represents a date in user time
1947  *
1948  * Returns a formatted string that represents a date in user time
1949  * <b>WARNING: note that the format is for strftime(), not date().</b>
1950  * Because of a bug in most Windows time libraries, we can't use
1951  * the nicer %e, so we have to use %d which has leading zeroes.
1952  * A lot of the fuss in the function is just getting rid of these leading
1953  * zeroes as efficiently as possible.
1954  *
1955  * If parameter fixday = true (default), then take off leading
1956  * zero from %d, else maintain it.
1957  *
1958  * @package core
1959  * @category time
1960  * @param int $date the timestamp in UTC, as obtained from the database.
1961  * @param string $format strftime format. You should probably get this using
1962  *        get_string('strftime...', 'langconfig');
1963  * @param int|float|string  $timezone by default, uses the user's time zone. if numeric and
1964  *        not 99 then daylight saving will not be added.
1965  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
1966  * @param bool $fixday If true (default) then the leading zero from %d is removed.
1967  *        If false then the leading zero is maintained.
1968  * @param bool $fixhour If true (default) then the leading zero from %I is removed.
1969  * @return string the formatted date/time.
1970  */
1971 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
1973     global $CFG;
1975     if (empty($format)) {
1976         $format = get_string('strftimedaydatetime', 'langconfig');
1977     }
1979     if (!empty($CFG->nofixday)) {  // Config.php can force %d not to be fixed.
1980         $fixday = false;
1981     } else if ($fixday) {
1982         $formatnoday = str_replace('%d', 'DD', $format);
1983         $fixday = ($formatnoday != $format);
1984         $format = $formatnoday;
1985     }
1987     // Note: This logic about fixing 12-hour time to remove unnecessary leading
1988     // zero is required because on Windows, PHP strftime function does not
1989     // support the correct 'hour without leading zero' parameter (%l).
1990     if (!empty($CFG->nofixhour)) {
1991         // Config.php can force %I not to be fixed.
1992         $fixhour = false;
1993     } else if ($fixhour) {
1994         $formatnohour = str_replace('%I', 'HH', $format);
1995         $fixhour = ($formatnohour != $format);
1996         $format = $formatnohour;
1997     }
1999     //add daylight saving offset for string timezones only, as we can't get dst for
2000     //float values. if timezone is 99 (user default timezone), then try update dst.
2001     if ((99 == $timezone) || !is_numeric($timezone)) {
2002         $date += dst_offset_on($date, $timezone);
2003     }
2005     $timezone = get_user_timezone_offset($timezone);
2007     if (abs($timezone) > 13) {   /// Server time
2008         $datestring = strftime($format, $date);
2009         if ($fixday) {
2010             $daystring  = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
2011             $datestring = str_replace('DD', $daystring, $datestring);
2012         }
2013         if ($fixhour) {
2014             $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2015             $datestring = str_replace('HH', $hourstring, $datestring);
2016         }
2017     } else {
2018         $date += (int)($timezone * 3600);
2019         $datestring = gmstrftime($format, $date);
2020         if ($fixday) {
2021             $daystring  = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
2022             $datestring = str_replace('DD', $daystring, $datestring);
2023         }
2024         if ($fixhour) {
2025             $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2026             $datestring = str_replace('HH', $hourstring, $datestring);
2027         }
2028     }
2030 /// If we are running under Windows convert from windows encoding to UTF-8
2031 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
2033    if ($CFG->ostype == 'WINDOWS') {
2034        if ($localewincharset = get_string('localewincharset', 'langconfig')) {
2035            $textlib = textlib_get_instance();
2036            $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
2037        }
2038     }
2040     return $datestring;
2043 /**
2044  * Given a $time timestamp in GMT (seconds since epoch),
2045  * returns an array that represents the date in user time
2046  *
2047  * @package core
2048  * @category time
2049  * @uses HOURSECS
2050  * @param int $time Timestamp in GMT
2051  * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2052  *        dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
2053  * @return array An array that represents the date in user time
2054  */
2055 function usergetdate($time, $timezone=99) {
2057     //save input timezone, required for dst offset check.
2058     $passedtimezone = $timezone;
2060     $timezone = get_user_timezone_offset($timezone);
2062     if (abs($timezone) > 13) {    // Server time
2063         return getdate($time);
2064     }
2066     //add daylight saving offset for string timezones only, as we can't get dst for
2067     //float values. if timezone is 99 (user default timezone), then try update dst.
2068     if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2069         $time += dst_offset_on($time, $passedtimezone);
2070     }
2072     $time += intval((float)$timezone * HOURSECS);
2074     $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2076     //be careful to ensure the returned array matches that produced by getdate() above
2077     list(
2078         $getdate['month'],
2079         $getdate['weekday'],
2080         $getdate['yday'],
2081         $getdate['year'],
2082         $getdate['mon'],
2083         $getdate['wday'],
2084         $getdate['mday'],
2085         $getdate['hours'],
2086         $getdate['minutes'],
2087         $getdate['seconds']
2088     ) = explode('_', $datestring);
2090     return $getdate;
2093 /**
2094  * Given a GMT timestamp (seconds since epoch), offsets it by
2095  * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2096  *
2097  * @package core
2098  * @category time
2099  * @uses HOURSECS
2100  * @param int $date Timestamp in GMT
2101  * @param float|int|string $timezone timezone to calculate GMT time offset before
2102  *        calculating user time, 99 is default user timezone
2103  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2104  * @return int
2105  */
2106 function usertime($date, $timezone=99) {
2108     $timezone = get_user_timezone_offset($timezone);
2110     if (abs($timezone) > 13) {
2111         return $date;
2112     }
2113     return $date - (int)($timezone * HOURSECS);
2116 /**
2117  * Given a time, return the GMT timestamp of the most recent midnight
2118  * for the current user.
2119  *
2120  * @package core
2121  * @category time
2122  * @param int $date Timestamp in GMT
2123  * @param float|int|string $timezone timezone to calculate GMT time offset before
2124  *        calculating user midnight time, 99 is default user timezone
2125  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2126  * @return int Returns a GMT timestamp
2127  */
2128 function usergetmidnight($date, $timezone=99) {
2130     $userdate = usergetdate($date, $timezone);
2132     // Time of midnight of this user's day, in GMT
2133     return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2137 /**
2138  * Returns a string that prints the user's timezone
2139  *
2140  * @package core
2141  * @category time
2142  * @param float|int|string $timezone timezone to calculate GMT time offset before
2143  *        calculating user timezone, 99 is default user timezone
2144  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2145  * @return string
2146  */
2147 function usertimezone($timezone=99) {
2149     $tz = get_user_timezone($timezone);
2151     if (!is_float($tz)) {
2152         return $tz;
2153     }
2155     if(abs($tz) > 13) { // Server time
2156         return get_string('serverlocaltime');
2157     }
2159     if($tz == intval($tz)) {
2160         // Don't show .0 for whole hours
2161         $tz = intval($tz);
2162     }
2164     if($tz == 0) {
2165         return 'UTC';
2166     }
2167     else if($tz > 0) {
2168         return 'UTC+'.$tz;
2169     }
2170     else {
2171         return 'UTC'.$tz;
2172     }
2176 /**
2177  * Returns a float which represents the user's timezone difference from GMT in hours
2178  * Checks various settings and picks the most dominant of those which have a value
2179  *
2180  * @package core
2181  * @category time
2182  * @param float|int|string $tz timezone to calculate GMT time offset for user,
2183  *        99 is default user timezone
2184  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2185  * @return float
2186  */
2187 function get_user_timezone_offset($tz = 99) {
2189     global $USER, $CFG;
2191     $tz = get_user_timezone($tz);
2193     if (is_float($tz)) {
2194         return $tz;
2195     } else {
2196         $tzrecord = get_timezone_record($tz);
2197         if (empty($tzrecord)) {
2198             return 99.0;
2199         }
2200         return (float)$tzrecord->gmtoff / HOURMINS;
2201     }
2204 /**
2205  * Returns an int which represents the systems's timezone difference from GMT in seconds
2206  *
2207  * @package core
2208  * @category time
2209  * @param float|int|string $tz timezone for which offset is required.
2210  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2211  * @return int|bool if found, false is timezone 99 or error
2212  */
2213 function get_timezone_offset($tz) {
2214     global $CFG;
2216     if ($tz == 99) {
2217         return false;
2218     }
2220     if (is_numeric($tz)) {
2221         return intval($tz * 60*60);
2222     }
2224     if (!$tzrecord = get_timezone_record($tz)) {
2225         return false;
2226     }
2227     return intval($tzrecord->gmtoff * 60);
2230 /**
2231  * Returns a float or a string which denotes the user's timezone
2232  * 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)
2233  * means that for this timezone there are also DST rules to be taken into account
2234  * Checks various settings and picks the most dominant of those which have a value
2235  *
2236  * @package core
2237  * @category time
2238  * @param float|int|string $tz timezone to calculate GMT time offset before
2239  *        calculating user timezone, 99 is default user timezone
2240  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2241  * @return float|string
2242  */
2243 function get_user_timezone($tz = 99) {
2244     global $USER, $CFG;
2246     $timezones = array(
2247         $tz,
2248         isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2249         isset($USER->timezone) ? $USER->timezone : 99,
2250         isset($CFG->timezone) ? $CFG->timezone : 99,
2251         );
2253     $tz = 99;
2255     while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
2256         $tz = $next['value'];
2257     }
2259     return is_numeric($tz) ? (float) $tz : $tz;
2262 /**
2263  * Returns cached timezone record for given $timezonename
2264  *
2265  * @package core
2266  * @param string $timezonename name of the timezone
2267  * @return stdClass|bool timezonerecord or false
2268  */
2269 function get_timezone_record($timezonename) {
2270     global $CFG, $DB;
2271     static $cache = NULL;
2273     if ($cache === NULL) {
2274         $cache = array();
2275     }
2277     if (isset($cache[$timezonename])) {
2278         return $cache[$timezonename];
2279     }
2281     return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2282                                                         WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2285 /**
2286  * Build and store the users Daylight Saving Time (DST) table
2287  *
2288  * @package core
2289  * @param int $from_year Start year for the table, defaults to 1971
2290  * @param int $to_year End year for the table, defaults to 2035
2291  * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
2292  * @return bool
2293  */
2294 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2295     global $CFG, $SESSION, $DB;
2297     $usertz = get_user_timezone($strtimezone);
2299     if (is_float($usertz)) {
2300         // Trivial timezone, no DST
2301         return false;
2302     }
2304     if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2305         // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2306         unset($SESSION->dst_offsets);
2307         unset($SESSION->dst_range);
2308     }
2310     if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2311         // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2312         // This will be the return path most of the time, pretty light computationally
2313         return true;
2314     }
2316     // Reaching here means we either need to extend our table or create it from scratch
2318     // Remember which TZ we calculated these changes for
2319     $SESSION->dst_offsettz = $usertz;
2321     if(empty($SESSION->dst_offsets)) {
2322         // If we 're creating from scratch, put the two guard elements in there
2323         $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2324     }
2325     if(empty($SESSION->dst_range)) {
2326         // If creating from scratch
2327         $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2328         $to   = min((empty($to_year)   ? intval(date('Y')) + 3 : $to_year),   2035);
2330         // Fill in the array with the extra years we need to process
2331         $yearstoprocess = array();
2332         for($i = $from; $i <= $to; ++$i) {
2333             $yearstoprocess[] = $i;
2334         }
2336         // Take note of which years we have processed for future calls
2337         $SESSION->dst_range = array($from, $to);
2338     }
2339     else {
2340         // If needing to extend the table, do the same
2341         $yearstoprocess = array();
2343         $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2344         $to   = min((empty($to_year)   ? $SESSION->dst_range[1] : $to_year),   2035);
2346         if($from < $SESSION->dst_range[0]) {
2347             // Take note of which years we need to process and then note that we have processed them for future calls
2348             for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2349                 $yearstoprocess[] = $i;
2350             }
2351             $SESSION->dst_range[0] = $from;
2352         }
2353         if($to > $SESSION->dst_range[1]) {
2354             // Take note of which years we need to process and then note that we have processed them for future calls
2355             for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2356                 $yearstoprocess[] = $i;
2357             }
2358             $SESSION->dst_range[1] = $to;
2359         }
2360     }
2362     if(empty($yearstoprocess)) {
2363         // This means that there was a call requesting a SMALLER range than we have already calculated
2364         return true;
2365     }
2367     // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2368     // Also, the array is sorted in descending timestamp order!
2370     // Get DB data
2372     static $presets_cache = array();
2373     if (!isset($presets_cache[$usertz])) {
2374         $presets_cache[$usertz] = $DB->get_records('timezone', array('name'=>$usertz), 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, std_startday, std_weekday, std_skipweeks, std_time');
2375     }
2376     if(empty($presets_cache[$usertz])) {
2377         return false;
2378     }
2380     // Remove ending guard (first element of the array)
2381     reset($SESSION->dst_offsets);
2382     unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2384     // Add all required change timestamps
2385     foreach($yearstoprocess as $y) {
2386         // Find the record which is in effect for the year $y
2387         foreach($presets_cache[$usertz] as $year => $preset) {
2388             if($year <= $y) {
2389                 break;
2390             }
2391         }
2393         $changes = dst_changes_for_year($y, $preset);
2395         if($changes === NULL) {
2396             continue;
2397         }
2398         if($changes['dst'] != 0) {
2399             $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2400         }
2401         if($changes['std'] != 0) {
2402             $SESSION->dst_offsets[$changes['std']] = 0;
2403         }
2404     }
2406     // Put in a guard element at the top
2407     $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2408     $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2410     // Sort again
2411     krsort($SESSION->dst_offsets);
2413     return true;
2416 /**
2417  * Calculates the required DST change and returns a Timestamp Array
2418  *
2419  * @package core
2420  * @category time
2421  * @uses HOURSECS
2422  * @uses MINSECS
2423  * @param int|string $year Int or String Year to focus on
2424  * @param object $timezone Instatiated Timezone object
2425  * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
2426  */
2427 function dst_changes_for_year($year, $timezone) {
2429     if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2430         return NULL;
2431     }
2433     $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2434     $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2436     list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2437     list($std_hour, $std_min) = explode(':', $timezone->std_time);
2439     $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2440     $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2442     // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2443     // This has the advantage of being able to have negative values for hour, i.e. for timezones
2444     // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2446     $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2447     $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2449     return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2452 /**
2453  * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2454  * - Note: Daylight saving only works for string timezones and not for float.
2455  *
2456  * @package core
2457  * @category time
2458  * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2459  * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2460  *        then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2461  * @return int
2462  */
2463 function dst_offset_on($time, $strtimezone = NULL) {
2464     global $SESSION;
2466     if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2467         return 0;
2468     }
2470     reset($SESSION->dst_offsets);
2471     while(list($from, $offset) = each($SESSION->dst_offsets)) {
2472         if($from <= $time) {
2473             break;
2474         }
2475     }
2477     // This is the normal return path
2478     if($offset !== NULL) {
2479         return $offset;
2480     }
2482     // Reaching this point means we haven't calculated far enough, do it now:
2483     // Calculate extra DST changes if needed and recurse. The recursion always
2484     // moves toward the stopping condition, so will always end.
2486     if($from == 0) {
2487         // We need a year smaller than $SESSION->dst_range[0]
2488         if($SESSION->dst_range[0] == 1971) {
2489             return 0;
2490         }
2491         calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2492         return dst_offset_on($time, $strtimezone);
2493     }
2494     else {
2495         // We need a year larger than $SESSION->dst_range[1]
2496         if($SESSION->dst_range[1] == 2035) {
2497             return 0;
2498         }
2499         calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2500         return dst_offset_on($time, $strtimezone);
2501     }
2504 /**
2505  * Calculates when the day appears in specific month
2506  *
2507  * @package core
2508  * @category time
2509  * @param int $startday starting day of the month
2510  * @param int $weekday The day when week starts (normally taken from user preferences)
2511  * @param int $month The month whose day is sought
2512  * @param int $year The year of the month whose day is sought
2513  * @return int
2514  */
2515 function find_day_in_month($startday, $weekday, $month, $year) {
2517     $daysinmonth = days_in_month($month, $year);
2519     if($weekday == -1) {
2520         // Don't care about weekday, so return:
2521         //    abs($startday) if $startday != -1
2522         //    $daysinmonth otherwise
2523         return ($startday == -1) ? $daysinmonth : abs($startday);
2524     }
2526     // From now on we 're looking for a specific weekday
2528     // Give "end of month" its actual value, since we know it
2529     if($startday == -1) {
2530         $startday = -1 * $daysinmonth;
2531     }
2533     // Starting from day $startday, the sign is the direction
2535     if($startday < 1) {
2537         $startday = abs($startday);
2538         $lastmonthweekday  = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2540         // This is the last such weekday of the month
2541         $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2542         if($lastinmonth > $daysinmonth) {
2543             $lastinmonth -= 7;
2544         }
2546         // Find the first such weekday <= $startday
2547         while($lastinmonth > $startday) {
2548             $lastinmonth -= 7;
2549         }
2551         return $lastinmonth;
2553     }
2554     else {
2556         $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2558         $diff = $weekday - $indexweekday;
2559         if($diff < 0) {
2560             $diff += 7;
2561         }
2563         // This is the first such weekday of the month equal to or after $startday
2564         $firstfromindex = $startday + $diff;
2566         return $firstfromindex;
2568     }
2571 /**
2572  * Calculate the number of days in a given month
2573  *
2574  * @package core
2575  * @category time
2576  * @param int $month The month whose day count is sought
2577  * @param int $year The year of the month whose day count is sought
2578  * @return int
2579  */
2580 function days_in_month($month, $year) {
2581    return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2584 /**
2585  * Calculate the position in the week of a specific calendar day
2586  *
2587  * @package core
2588  * @category time
2589  * @param int $day The day of the date whose position in the week is sought
2590  * @param int $month The month of the date whose position in the week is sought
2591  * @param int $year The year of the date whose position in the week is sought
2592  * @return int
2593  */
2594 function dayofweek($day, $month, $year) {
2595     // I wonder if this is any different from
2596     // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2597     return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2600 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2602 /**
2603  * Returns full login url.
2604  *
2605  * @return string login url
2606  */
2607 function get_login_url() {
2608     global $CFG;
2610     $url = "$CFG->wwwroot/login/index.php";
2612     if (!empty($CFG->loginhttps)) {
2613         $url = str_replace('http:', 'https:', $url);
2614     }
2616     return $url;
2619 /**
2620  * This function checks that the current user is logged in and has the
2621  * required privileges
2622  *
2623  * This function checks that the current user is logged in, and optionally
2624  * whether they are allowed to be in a particular course and view a particular
2625  * course module.
2626  * If they are not logged in, then it redirects them to the site login unless
2627  * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2628  * case they are automatically logged in as guests.
2629  * If $courseid is given and the user is not enrolled in that course then the
2630  * user is redirected to the course enrolment page.
2631  * If $cm is given and the course module is hidden and the user is not a teacher
2632  * in the course then the user is redirected to the course home page.
2633  *
2634  * When $cm parameter specified, this function sets page layout to 'module'.
2635  * You need to change it manually later if some other layout needed.
2636  *
2637  * @param mixed $courseorid id of the course or course object
2638  * @param bool $autologinguest default true
2639  * @param object $cm course module object
2640  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2641  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2642  *             in order to keep redirects working properly. MDL-14495
2643  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2644  * @return mixed Void, exit, and die depending on path
2645  */
2646 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2647     global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2649     // setup global $COURSE, themes, language and locale
2650     if (!empty($courseorid)) {
2651         if (is_object($courseorid)) {
2652             $course = $courseorid;
2653         } else if ($courseorid == SITEID) {
2654             $course = clone($SITE);
2655         } else {
2656             $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2657         }
2658         if ($cm) {
2659             if ($cm->course != $course->id) {
2660                 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2661             }
2662             // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2663             if (!($cm instanceof cm_info)) {
2664                 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2665                 // db queries so this is not really a performance concern, however it is obviously
2666                 // better if you use get_fast_modinfo to get the cm before calling this.
2667                 $modinfo = get_fast_modinfo($course);
2668                 $cm = $modinfo->get_cm($cm->id);
2669             }
2670             $PAGE->set_cm($cm, $course); // set's up global $COURSE
2671             $PAGE->set_pagelayout('incourse');
2672         } else {
2673             $PAGE->set_course($course); // set's up global $COURSE
2674         }
2675     } else {
2676         // do not touch global $COURSE via $PAGE->set_course(),
2677         // the reasons is we need to be able to call require_login() at any time!!
2678         $course = $SITE;
2679         if ($cm) {
2680             throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2681         }
2682     }
2684     // If the user is not even logged in yet then make sure they are
2685     if (!isloggedin()) {
2686         if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2687             if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2688                 // misconfigured site guest, just redirect to login page
2689                 redirect(get_login_url());
2690                 exit; // never reached
2691             }
2692             $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2693             complete_user_login($guest);
2694             $USER->autologinguest = true;
2695             $SESSION->lang = $lang;
2696         } else {
2697             //NOTE: $USER->site check was obsoleted by session test cookie,
2698             //      $USER->confirmed test is in login/index.php
2699             if ($preventredirect) {
2700                 throw new require_login_exception('You are not logged in');
2701             }
2703             if ($setwantsurltome) {
2704                 // TODO: switch to PAGE->url
2705                 $SESSION->wantsurl = $FULLME;
2706             }
2707             if (!empty($_SERVER['HTTP_REFERER'])) {
2708                 $SESSION->fromurl  = $_SERVER['HTTP_REFERER'];
2709             }
2710             redirect(get_login_url());
2711             exit; // never reached
2712         }
2713     }
2715     // loginas as redirection if needed
2716     if ($course->id != SITEID and session_is_loggedinas()) {
2717         if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2718             if ($USER->loginascontext->instanceid != $course->id) {
2719                 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2720             }
2721         }
2722     }
2724     // check whether the user should be changing password (but only if it is REALLY them)
2725     if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2726         $userauth = get_auth_plugin($USER->auth);
2727         if ($userauth->can_change_password() and !$preventredirect) {
2728             $SESSION->wantsurl = $FULLME;
2729             if ($changeurl = $userauth->change_password_url()) {
2730                 //use plugin custom url
2731                 redirect($changeurl);
2732             } else {
2733                 //use moodle internal method
2734                 if (empty($CFG->loginhttps)) {
2735                     redirect($CFG->wwwroot .'/login/change_password.php');
2736                 } else {
2737                     $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2738                     redirect($wwwroot .'/login/change_password.php');
2739                 }
2740             }
2741         } else {
2742             print_error('nopasswordchangeforced', 'auth');
2743         }
2744     }
2746     // Check that the user account is properly set up
2747     if (user_not_fully_set_up($USER)) {
2748         if ($preventredirect) {
2749             throw new require_login_exception('User not fully set-up');
2750         }
2751         $SESSION->wantsurl = $FULLME;
2752         redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2753     }
2755     // Make sure the USER has a sesskey set up. Used for CSRF protection.
2756     sesskey();
2758     // Do not bother admins with any formalities
2759     if (is_siteadmin()) {
2760         //set accesstime or the user will appear offline which messes up messaging
2761         user_accesstime_log($course->id);
2762         return;
2763     }
2765     // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2766     if (!$USER->policyagreed and !is_siteadmin()) {
2767         if (!empty($CFG->sitepolicy) and !isguestuser()) {
2768             if ($preventredirect) {
2769                 throw new require_login_exception('Policy not agreed');
2770             }
2771             $SESSION->wantsurl = $FULLME;
2772             redirect($CFG->wwwroot .'/user/policy.php');
2773         } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2774             if ($preventredirect) {
2775                 throw new require_login_exception('Policy not agreed');
2776             }
2777             $SESSION->wantsurl = $FULLME;
2778             redirect($CFG->wwwroot .'/user/policy.php');
2779         }
2780     }
2782     // Fetch the system context, the course context, and prefetch its child contexts
2783     $sysctx = get_context_instance(CONTEXT_SYSTEM);
2784     $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2785     if ($cm) {
2786         $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2787     } else {
2788         $cmcontext = null;
2789     }
2791     // If the site is currently under maintenance, then print a message
2792     if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2793         if ($preventredirect) {
2794             throw new require_login_exception('Maintenance in progress');
2795         }
2797         print_maintenance_message();
2798     }
2800     // make sure the course itself is not hidden
2801     if ($course->id == SITEID) {
2802         // frontpage can not be hidden
2803     } else {
2804         if (is_role_switched($course->id)) {
2805             // when switching roles ignore the hidden flag - user had to be in course to do the switch
2806         } else {
2807             if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2808                 // originally there was also test of parent category visibility,
2809                 // BUT is was very slow in complex queries involving "my courses"
2810                 // now it is also possible to simply hide all courses user is not enrolled in :-)
2811                 if ($preventredirect) {
2812                     throw new require_login_exception('Course is hidden');
2813                 }
2814                 // We need to override the navigation URL as the course won't have
2815                 // been added to the navigation and thus the navigation will mess up
2816                 // when trying to find it.
2817                 navigation_node::override_active_url(new moodle_url('/'));
2818                 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2819             }
2820         }
2821     }
2823     // is the user enrolled?
2824     if ($course->id == SITEID) {
2825         // everybody is enrolled on the frontpage
2827     } else {
2828         if (session_is_loggedinas()) {
2829             // Make sure the REAL person can access this course first
2830             $realuser = session_get_realuser();
2831             if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2832                 if ($preventredirect) {
2833                     throw new require_login_exception('Invalid course login-as access');
2834                 }
2835                 echo $OUTPUT->header();
2836                 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2837             }
2838         }
2840         $access = false;
2842         if (is_role_switched($course->id)) {
2843             // ok, user had to be inside this course before the switch
2844             $access = true;
2846         } else if (is_viewing($coursecontext, $USER)) {
2847             // ok, no need to mess with enrol
2848             $access = true;
2850         } else {
2851             if (isset($USER->enrol['enrolled'][$course->id])) {
2852                 if ($USER->enrol['enrolled'][$course->id] > time()) {
2853                     $access = true;
2854                     if (isset($USER->enrol['tempguest'][$course->id])) {
2855                         unset($USER->enrol['tempguest'][$course->id]);
2856                         remove_temp_course_roles($coursecontext);
2857                     }
2858                 } else {
2859                     //expired
2860                     unset($USER->enrol['enrolled'][$course->id]);
2861                 }
2862             }
2863             if (isset($USER->enrol['tempguest'][$course->id])) {
2864                 if ($USER->enrol['tempguest'][$course->id] == 0) {
2865                     $access = true;
2866                 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2867                     $access = true;
2868                 } else {
2869                     //expired
2870                     unset($USER->enrol['tempguest'][$course->id]);
2871                     remove_temp_course_roles($coursecontext);
2872                 }
2873             }
2875             if ($access) {
2876                 // cache ok
2877             } else {
2878                 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2879                 if ($until !== false) {
2880                     // active participants may always access, a timestamp in the future, 0 (always) or false.
2881                     if ($until == 0) {
2882                         $until = ENROL_MAX_TIMESTAMP;
2883                     }
2884                     $USER->enrol['enrolled'][$course->id] = $until;
2885                     $access = true;
2887                 } else {
2888                     $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2889                     $enrols = enrol_get_plugins(true);
2890                     // first ask all enabled enrol instances in course if they want to auto enrol user
2891                     foreach($instances as $instance) {
2892                         if (!isset($enrols[$instance->enrol])) {
2893                             continue;
2894                         }
2895                         // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2896                         $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2897                         if ($until !== false) {
2898                             if ($until == 0) {
2899                                 $until = ENROL_MAX_TIMESTAMP;
2900                             }
2901                             $USER->enrol['enrolled'][$course->id] = $until;
2902                             $access = true;
2903                             break;
2904                         }
2905                     }
2906                     // if not enrolled yet try to gain temporary guest access
2907                     if (!$access) {
2908                         foreach($instances as $instance) {
2909                             if (!isset($enrols[$instance->enrol])) {
2910                                 continue;
2911                             }
2912                             // Get a duration for the guest access, a timestamp in the future or false.
2913                             $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2914                             if ($until !== false and $until > time()) {
2915                                 $USER->enrol['tempguest'][$course->id] = $until;
2916                                 $access = true;
2917                                 break;
2918                             }
2919                         }
2920                     }
2921                 }
2922             }
2923         }
2925         if (!$access) {
2926             if ($preventredirect) {
2927                 throw new require_login_exception('Not enrolled');
2928             }
2929             $SESSION->wantsurl = $FULLME;
2930             redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2931         }
2932     }
2934     // Check visibility of activity to current user; includes visible flag, groupmembersonly,
2935     // conditional availability, etc
2936     if ($cm && !$cm->uservisible) {
2937         if ($preventredirect) {
2938             throw new require_login_exception('Activity is hidden');
2939         }
2940         redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2941     }
2943     // Finally access granted, update lastaccess times
2944     user_accesstime_log($course->id);
2948 /**
2949  * This function just makes sure a user is logged out.
2950  *
2951  * @global object
2952  */
2953 function require_logout() {
2954     global $USER;
2956     $params = $USER;
2958     if (isloggedin()) {
2959         add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2961         $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2962         foreach($authsequence as $authname) {
2963             $authplugin = get_auth_plugin($authname);
2964             $authplugin->prelogout_hook();
2965         }
2966     }
2968     events_trigger('user_logout', $params);
2969     session_get_instance()->terminate_current();
2970     unset($params);
2973 /**
2974  * Weaker version of require_login()
2975  *
2976  * This is a weaker version of {@link require_login()} which only requires login
2977  * when called from within a course rather than the site page, unless
2978  * the forcelogin option is turned on.
2979  * @see require_login()
2980  *
2981  * @global object
2982  * @param mixed $courseorid The course object or id in question
2983  * @param bool $autologinguest Allow autologin guests if that is wanted
2984  * @param object $cm Course activity module if known
2985  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2986  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2987  *             in order to keep redirects working properly. MDL-14495
2988  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2989  * @return void
2990  */
2991 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2992     global $CFG, $PAGE, $SITE;
2993     $issite = (is_object($courseorid) and $courseorid->id == SITEID)
2994           or (!is_object($courseorid) and $courseorid == SITEID);
2995     if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2996         // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2997         // db queries so this is not really a performance concern, however it is obviously
2998         // better if you use get_fast_modinfo to get the cm before calling this.
2999         if (is_object($courseorid)) {
3000             $course = $courseorid;
3001         } else {
3002             $course = clone($SITE);
3003         }
3004         $modinfo = get_fast_modinfo($course);
3005         $cm = $modinfo->get_cm($cm->id);
3006     }
3007     if (!empty($CFG->forcelogin)) {
3008         // login required for both SITE and courses
3009         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3011     } else if ($issite && !empty($cm) and !$cm->uservisible) {
3012         // always login for hidden activities
3013         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3015     } else if ($issite) {
3016               //login for SITE not required
3017         if ($cm and empty($cm->visible)) {
3018             // hidden activities are not accessible without login
3019             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3020         } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3021             // not-logged-in users do not have any group membership
3022             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3023         } else {
3024             // We still need to instatiate PAGE vars properly so that things
3025             // that rely on it like navigation function correctly.
3026             if (!empty($courseorid)) {
3027                 if (is_object($courseorid)) {
3028                     $course = $courseorid;
3029                 } else {
3030                     $course = clone($SITE);
3031                 }
3032                 if ($cm) {
3033                     if ($cm->course != $course->id) {
3034                         throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3035                     }
3036                     $PAGE->set_cm($cm, $course);
3037                     $PAGE->set_pagelayout('incourse');
3038                 } else {
3039                     $PAGE->set_course($course);
3040                 }
3041             } else {
3042                 // If $PAGE->course, and hence $PAGE->context, have not already been set
3043                 // up properly, set them up now.
3044                 $PAGE->set_course($PAGE->course);
3045             }
3046             //TODO: verify conditional activities here
3047             user_accesstime_log(SITEID);
3048             return;
3049         }
3051     } else {
3052         // course login always required
3053         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3054     }
3057 /**
3058  * Require key login. Function terminates with error if key not found or incorrect.
3059  *
3060  * @global object
3061  * @global object
3062  * @global object
3063  * @global object
3064  * @uses NO_MOODLE_COOKIES
3065  * @uses PARAM_ALPHANUM
3066  * @param string $script unique script identifier
3067  * @param int $instance optional instance id
3068  * @return int Instance ID
3069  */
3070 function require_user_key_login($script, $instance=null) {
3071     global $USER, $SESSION, $CFG, $DB;
3073     if (!NO_MOODLE_COOKIES) {
3074         print_error('sessioncookiesdisable');
3075     }
3077 /// extra safety
3078     @session_write_close();
3080     $keyvalue = required_param('key', PARAM_ALPHANUM);
3082     if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3083         print_error('invalidkey');
3084     }
3086     if (!empty($key->validuntil) and $key->validuntil < time()) {
3087         print_error('expiredkey');
3088     }
3090     if ($key->iprestriction) {
3091         $remoteaddr = getremoteaddr(null);
3092         if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3093             print_error('ipmismatch');
3094         }
3095     }
3097     if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
3098         print_error('invaliduserid');
3099     }
3101 /// emulate normal session
3102     enrol_check_plugins($user);
3103     session_set_user($user);
3105 /// note we are not using normal login
3106     if (!defined('USER_KEY_LOGIN')) {
3107         define('USER_KEY_LOGIN', true);
3108     }
3110 /// return instance id - it might be empty
3111     return $key->instance;
3114 /**
3115  * Creates a new private user access key.
3116  *
3117  * @global object
3118  * @param string $script unique target identifier
3119  * @param int $userid
3120  * @param int $instance optional instance id
3121  * @param string $iprestriction optional ip restricted access
3122  * @param timestamp $validuntil key valid only until given data
3123  * @return string access key value
3124  */
3125 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3126     global $DB;
3128     $key = new stdClass();
3129     $key->script        = $script;
3130     $key->userid        = $userid;
3131     $key->instance      = $instance;
3132     $key->iprestriction = $iprestriction;
3133     $key->validuntil    = $validuntil;
3134     $key->timecreated   = time();
3136     $key->value         = md5($userid.'_'.time().random_string(40)); // something long and unique
3137     while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3138         // must be unique
3139         $key->value     = md5($userid.'_'.time().random_string(40));
3140     }
3141     $DB->insert_record('user_private_key', $key);
3142     return $key->value;
3145 /**
3146  * Delete the user's new private user access keys for a particular script.
3147  *
3148  * @global object
3149  * @param string $script unique target identifier
3150  * @param int $userid
3151  * @return void
3152  */
3153 function delete_user_key($script,$userid) {
3154     global $DB;
3155     $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3158 /**
3159  * Gets a private user access key (and creates one if one doesn't exist).
3160  *
3161  * @global object
3162  * @param string $script unique target identifier
3163  * @param int $userid
3164  * @param int $instance optional instance id
3165  * @param string $iprestriction optional ip restricted access
3166  * @param timestamp $validuntil key valid only until given data
3167  * @return string access key value
3168  */
3169 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3170     global $DB;
3172     if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3173                                                          'instance'=>$instance, 'iprestriction'=>$iprestriction,
3174                                                          'validuntil'=>$validuntil))) {
3175         return $key->value;
3176     } else {
3177         return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3178     }
3182 /**
3183  * Modify the user table by setting the currently logged in user's
3184  * last login to now.
3185  *
3186  * @global object
3187  * @global object
3188  * @return bool Always returns true
3189  */
3190 function update_user_login_times() {
3191     global $USER, $DB;
3193     $user = new stdClass();
3194     $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3195     $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
3197     $user->id = $USER->id;
3199     $DB->update_record('user', $user);
3200     return true;
3203 /**
3204  * Determines if a user has completed setting up their account.
3205  *
3206  * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3207  * @return bool
3208  */
3209 function user_not_fully_set_up($user) {
3210     if (isguestuser($user)) {
3211         return false;
3212     }
3213     return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3216 /**
3217  * Check whether the user has exceeded the bounce threshold
3218  *
3219  * @global object
3220  * @global object
3221  * @param user $user A {@link $USER} object
3222  * @return bool true=>User has exceeded bounce threshold
3223  */
3224 function over_bounce_threshold($user) {
3225     global $CFG, $DB;
3227     if (empty($CFG->handlebounces)) {
3228         return false;
3229     }
3231     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3232         return false;
3233     }
3235     // set sensible defaults
3236     if (empty($CFG->minbounces)) {
3237         $CFG->minbounces = 10;
3238     }
3239     if (empty($CFG->bounceratio)) {
3240         $CFG->bounceratio = .20;
3241     }
3242     $bouncecount = 0;
3243     $sendcount = 0;
3244     if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3245         $bouncecount = $bounce->value;
3246     }
3247     if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3248         $sendcount = $send->value;
3249     }
3250     return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3253 /**
3254  * Used to increment or reset email sent count
3255  *
3256  * @global object
3257  * @param user $user object containing an id
3258  * @param bool $reset will reset the count to 0
3259  * @return void
3260  */
3261 function set_send_count($user,$reset=false) {
3262     global $DB;
3264     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3265         return;
3266     }
3268     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3269         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3270         $DB->update_record('user_preferences', $pref);
3271     }
3272     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3273         // make a new one
3274         $pref = new stdClass();
3275         $pref->name   = 'email_send_count';
3276         $pref->value  = 1;
3277         $pref->userid = $user->id;
3278         $DB->insert_record('user_preferences', $pref, false);
3279     }
3282 /**
3283  * Increment or reset user's email bounce count
3284  *
3285  * @global object
3286  * @param user $user object containing an id
3287  * @param bool $reset will reset the count to 0
3288  */
3289 function set_bounce_count($user,$reset=false) {
3290     global $DB;
3292     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3293         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3294         $DB->update_record('user_preferences', $pref);
3295     }
3296     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3297         // make a new one
3298         $pref = new stdClass();
3299         $pref->name   = 'email_bounce_count';
3300         $pref->value  = 1;
3301         $pref->userid = $user->id;
3302         $DB->insert_record('user_preferences', $pref, false);
3303     }
3306 /**
3307  * Keeps track of login attempts
3308  *
3309  * @global object
3310  */
3311 function update_login_count() {
3312     global $SESSION;
3314     $max_logins = 10;
3316     if (empty($SESSION->logincount)) {
3317         $SESSION->logincount = 1;
3318     } else {
3319         $SESSION->logincount++;
3320     }
3322     if ($SESSION->logincount > $max_logins) {
3323         unset($SESSION->wantsurl);
3324         print_error('errortoomanylogins');
3325     }
3328 /**
3329  * Resets login attempts
3330  *
3331  * @global object
3332  */
3333 function reset_login_count() {
3334     global $SESSION;
3336     $SESSION->logincount = 0;
3339 /**
3340  * Determines if the currently logged in user is in editing mode.
3341  * Note: originally this function had $userid parameter - it was not usable anyway
3342  *
3343  * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3344  * @todo Deprecated function remove when ready
3345  *
3346  * @global object
3347  * @uses DEBUG_DEVELOPER
3348  * @return bool
3349  */
3350 function isediting() {
3351     global $PAGE;
3352     debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3353     return $PAGE->user_is_editing();
3356 /**
3357  * Determines if the logged in user is currently moving an activity
3358  *
3359  * @global object
3360  * @param int $courseid The id of the course being tested
3361  * @return bool
3362  */
3363 function ismoving($courseid) {
3364     global $USER;
3366     if (!empty($USER->activitycopy)) {
3367         return ($USER->activitycopycourse == $courseid);
3368     }
3369     return false;
3372 /**
3373  * Returns a persons full name
3374  *
3375  * Given an object containing firstname and lastname
3376  * values, this function returns a string with the
3377  * full name of the person.
3378  * The result may depend on system settings
3379  * or language.  'override' will force both names
3380  * to be used even if system settings specify one.
3381  *
3382  * @global object
3383  * @global object
3384  * @param object $user A {@link $USER} object to get full name of
3385  * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3386  * @return string
3387  */
3388 function fullname($user, $override=false) {
3389     global $CFG, $SESSION;
3391     if (!isset($user->firstname) and !isset($user->lastname)) {
3392         return '';
3393     }
3395     if (!$override) {
3396         if (!empty($CFG->forcefirstname)) {
3397             $user->firstname = $CFG->forcefirstname;
3398         }
3399         if (!empty($CFG->forcelastname)) {
3400             $user->lastname = $CFG->forcelastname;
3401         }
3402     }
3404     if (!empty($SESSION->fullnamedisplay)) {
3405         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3406     }
3408     if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3409         return $user->firstname .' '. $user->lastname;
3411     } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3412         return $user->lastname .' '. $user->firstname;
3414     } else if ($CFG->fullnamedisplay == 'firstname') {
3415         if ($override) {
3416             return get_string('fullnamedisplay', '', $user);
3417         } else {
3418             return $user->firstname;
3419         }
3420     }
3422     return get_string('fullnamedisplay', '', $user);
3425 /**
3426  * Checks if current user is shown any extra fields when listing users.
3427  * @param object $context Context
3428  * @param array $already Array of fields that we're going to show anyway
3429  *   so don't bother listing them
3430  * @return array Array of field names from user table, not including anything
3431  *   listed in $already
3432  */
3433 function get_extra_user_fields($context, $already = array()) {
3434     global $CFG;
3436     // Only users with permission get the extra fields
3437     if (!has_capability('moodle/site:viewuseridentity', $context)) {
3438         return array();
3439     }
3441     // Split showuseridentity on comma
3442     if (empty($CFG->showuseridentity)) {
3443         // Explode gives wrong result with empty string
3444         $extra = array();
3445     } else {
3446         $extra =  explode(',', $CFG->showuseridentity);
3447     }
3448     $renumber = false;
3449     foreach ($extra as $key => $field) {
3450         if (in_array($field, $already)) {
3451             unset($extra[$key]);
3452             $renumber = true;
3453         }
3454     }
3455     if ($renumber) {
3456         // For consistency, if entries are removed from array, renumber it
3457         // so they are numbered as you would expect
3458         $extra = array_merge($extra);
3459     }
3460     return $extra;
3463 /**
3464  * If the current user is to be shown extra user fields when listing or
3465  * selecting users, returns a string suitable for including in an SQL select
3466  * clause to retrieve those fields.
3467  * @param object $context Context
3468  * @param string $alias Alias of user table, e.g. 'u' (default none)
3469  * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3470  * @param array $already Array of fields that we're going to include anyway
3471  *   so don't list them (default none)
3472  * @return string Partial SQL select clause, beginning with comma, for example
3473  *   ',u.idnumber,u.department' unless it is blank
3474  */
3475 function get_extra_user_fields_sql($context, $alias='', $prefix='',
3476         $already = array()) {
3477     $fields = get_extra_user_fields($context, $already);
3478     $result = '';
3479     // Add punctuation for alias
3480     if ($alias !== '') {
3481         $alias .= '.';
3482     }
3483     foreach ($fields as $field) {
3484         $result .= ', ' . $alias . $field;
3485         if ($prefix) {
3486             $result .= ' AS ' . $prefix . $field;
3487         }
3488     }
3489     return $result;
3492 /**
3493  * Returns the display name of a field in the user table. Works for most fields
3494  * that are commonly displayed to users.
3495  * @param string $field Field name, e.g. 'phone1'
3496  * @return string Text description taken from language file, e.g. 'Phone number'
3497  */
3498 function get_user_field_name($field) {
3499     // Some fields have language strings which are not the same as field name
3500     switch ($field) {
3501         case 'phone1' : return get_string('phone');
3502     }
3503     // Otherwise just use the same lang string
3504     return get_string($field);
3507 /**
3508  * Returns whether a given authentication plugin exists.
3509  *
3510  * @global object
3511  * @param string $auth Form of authentication to check for. Defaults to the
3512  *        global setting in {@link $CFG}.
3513  * @return boolean Whether the plugin is available.
3514  */
3515 function exists_auth_plugin($auth) {
3516     global $CFG;
3518     if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3519         return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3520     }
3521     return false;
3524 /**
3525  * Checks if a given plugin is in the list of enabled authentication plugins.
3526  *
3527  * @param string $auth Authentication plugin.
3528  * @return boolean Whether the plugin is enabled.
3529  */
3530 function is_enabled_auth($auth) {
3531     if (empty($auth)) {
3532         return false;
3533     }
3535     $enabled = get_enabled_auth_plugins();
3537     return in_array($auth, $enabled);
3540 /**
3541  * Returns an authentication plugin instance.
3542  *
3543  * @global object
3544  * @param string $auth name of authentication plugin
3545  * @return auth_plugin_base An instance of the required authentication plugin.
3546  */
3547 function get_auth_plugin($auth) {
3548     global $CFG;
3550     // check the plugin exists first
3551     if (! exists_auth_plugin($auth)) {
3552         print_error('authpluginnotfound', 'debug', '', $auth);
3553     }
3555     // return auth plugin instance
3556     require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3557     $class = "auth_plugin_$auth";
3558     return new $class;
3561 /**
3562  * Returns array of active auth plugins.
3563  *
3564  * @param bool $fix fix $CFG->auth if needed
3565  * @return array
3566  */
3567 function get_enabled_auth_plugins($fix=false) {
3568     global $CFG;
3570     $default = array('manual', 'nologin');
3572     if (empty($CFG->auth)) {
3573         $auths = array();
3574     } else {
3575         $auths = explode(',', $CFG->auth);
3576     }
3578     if ($fix) {
3579         $auths = array_unique($auths);
3580         foreach($auths as $k=>$authname) {
3581             if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3582                 unset($auths[$k]);
3583             }
3584         }
3585         $newconfig = implode(',', $auths);
3586         if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3587             set_config('auth', $newconfig);
3588         }
3589     }
3591     return (array_merge($default, $auths));
3594 /**
3595  * Returns true if an internal authentication method is being used.
3596  * if method not specified then, global default is assumed
3597  *
3598  * @param string $auth Form of authentication required
3599  * @return bool
3600  */
3601 function is_internal_auth($auth) {
3602     $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3603     return $authplugin->is_internal();
3606 /**
3607  * Returns true if the user is a 'restored' one
3608  *
3609  * Used in the login process to inform the user
3610  * and allow him/her to reset the password
3611  *
3612  * @uses $CFG
3613  * @uses $DB
3614  * @param string $username username to be checked
3615  * @return bool
3616  */
3617 function is_restored_user($username) {
3618     global $CFG, $DB;
3620     return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3623 /**
3624  * Returns an array of user fields
3625  *
3626  * @return array User field/column names
3627  */
3628 function get_user_fieldnames() {
3629     global $DB;
3631     $fieldarray = $DB->get_columns('user');
3632     unset($fieldarray['id']);
3633     $fieldarray = array_keys($fieldarray);
3635     return $fieldarray;
3638 /**
3639  * Creates a bare-bones user record
3640  *
3641  * @todo Outline auth types and provide code example
3642  *
3643  * @param string $username New user's username to add to record
3644  * @param string $password New user's password to add to record
3645  * @param string $auth Form of authentication required
3646  * @return stdClass A complete user object
3647  */
3648 function create_user_record($username, $password, $auth = 'manual') {
3649     global $CFG, $DB;
3651     //just in case check text case
3652     $username = trim(moodle_strtolower($username));
3654     $authplugin = get_auth_plugin($auth);
3656     $newuser = new stdClass();
3658     if ($newinfo = $authplugin->get_userinfo($username)) {
3659         $newinfo = truncate_userinfo($newinfo);
3660         foreach ($newinfo as $key => $value){
3661             $newuser->$key = $value;
3662         }
3663     }
3665     if (!empty($newuser->email)) {
3666         if (email_is_not_allowed($newuser->email)) {
3667             unset($newuser->email);
3668         }
3669     }
3671     if (!isset($newuser->city)) {
3672         $newuser->city = '';
3673     }
3675     $newuser->auth = $auth;
3676     $newuser->username = $username;
3678     // fix for MDL-8480
3679     // user CFG lang for user if $newuser->lang is empty
3680     // or $user->lang is not an installed language
3681     if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3682         $newuser->lang = $CFG->lang;
3683     }
3684     $newuser->confirmed = 1;
3685     $newuser->lastip = getremoteaddr();
3686     $newuser->timecreated = time();
3687     $newuser->timemodified = $newuser->timecreated;
3688     $newuser->mnethostid = $CFG->mnet_localhost_id;
3690     $newuser->id = $DB->insert_record('user', $newuser);
3691     $user = get_complete_user_data('id', $newuser->id);
3692     if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3693         set_user_preference('auth_forcepasswordchange', 1, $user);
3694     }
3695     update_internal_user_password($user, $password);
3697     // fetch full user record for the event, the complete user data contains too much info
3698     // and we want to be consistent with other places that trigger this event
3699     events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
3701     return $user;
3704 /**
3705  * Will update a local user record from an external source.
3706  * (MNET users can not be updated using this method!)
3707  *
3708  * @param string $username user's username to update the record
3709  * @return stdClass A complete user object
3710  */
3711 function update_user_record($username) {
3712     global $DB, $CFG;
3714     $username = trim(moodle_strtolower($username)); /// just in case check text case
3716     $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
3717     $newuser = array();
3718     $userauth = get_auth_plugin($oldinfo->auth);
3720     if ($newinfo = $userauth->get_userinfo($username)) {
3721         $newinfo = truncate_userinfo($newinfo);
3722         foreach ($newinfo as $key => $value){
3723             $key = strtolower($key);
3724             if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id'
3725                     or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3726                 // unknown or must not be changed
3727                 continue;
3728             }
3729             $confval = $userauth->config->{'field_updatelocal_' . $key};
3730             $lockval = $userauth->config->{'field_lock_' . $key};
3731             if (empty($confval) || empty($lockval)) {
3732                 continue;
3733             }
3734             if ($confval === 'onlogin') {
3735                 // MDL-4207 Don't overwrite modified user profile values with
3736                 // empty LDAP values when 'unlocked if empty' is set. The purpose
3737                 // of the setting 'unlocked if empty' is to allow the user to fill
3738                 // in a value for the selected field _if LDAP is giving
3739                 // nothing_ for this field. Thus it makes sense to let this value
3740                 // stand in until LDAP is giving a value for this field.
3741                 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3742                     if ((string)$oldinfo->$key !== (string)$value) {
3743                         $newuser[$key] = (string)$value;
3744                     }
3745                 }
3746             }
3747         }
3748         if ($newuser) {
3749             $newuser['id'] = $oldinfo->id;
3750             $newuser['timemodified'] = time();
3751             $DB->update_record('user', $newuser);
3752             // fetch full user record for the event, the complete user data contains too much info
3753             // and we want to be consistent with other places that trigger this event
3754             events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id)));
3755         }
3756     }
3758     return get_complete_user_data('id', $oldinfo->id);
3761 /**
3762  * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3763  * which may have large fields
3764  *
3765  * @todo Add vartype handling to ensure $info is an array
3766  *
3767  * @param array $info Array of user properties to truncate if needed
3768  * @return array The now truncated information that was passed in
3769  */
3770 function truncate_userinfo($info) {
3771     // define the limits
3772     $limit = array(
3773                     'username'    => 100,
3774                     'idnumber'    => 255,
3775                     'firstname'   => 100,
3776                     'lastname'    => 100,
3777                     'email'       => 100,
3778                     'icq'         =>  15,
3779                     'phone1'      =>  20,
3780                     'phone2'      =>  20,
3781                     'institution' =>  40,
3782                     'department'  =>  30,
3783                     'address'     =>  70,
3784                     'city'        => 120,
3785                     'country'     =>   2,
3786                     'url'         => 255,
3787                     );
3789     $textlib = textlib_get_instance();
3790     // apply where needed
3791     foreach (array_keys($info) as $key) {
3792         if (!empty($limit[$key])) {
3793             $info[$key] = trim($textlib->substr($info[$key],0, $limit[$key]));
3794         }
3795     }
3797     return $info;
3800 /**
3801  * Marks user deleted in internal user database and notifies the auth plugin.
3802  * Also unenrols user from all roles and does other cleanup.
3803  *
3804  * Any plugin that needs to purge user data should register the 'user_deleted' event.
3805  *
3806  * @param stdClass $user full user object before delete
3807  * @return boolean always true
3808  */
3809 function delete_user($user) {
3810     global $CFG, $DB;
3811     require_once($CFG->libdir.'/grouplib.php');
3812     require_once($CFG->libdir.'/gradelib.php');
3813     require_once($CFG->dirroot.'/message/lib.php');
3814     require_once($CFG->dirroot.'/tag/lib.php');
3816     // delete all grades - backup is kept in grade_grades_history table
3817     grade_user_delete($user->id);
3819     //move unread messages from this user to read
3820     message_move_userfrom_unread2read($user->id);
3822     // TODO: remove from cohorts using standard API here
3824     // remove user tags
3825     tag_set('user', $user->id, array());
3827     // unconditionally unenrol from all courses
3828     enrol_user_delete($user);
3830     // unenrol from all roles in all contexts
3831     role_unassign_all(array('userid'=>$user->id)); // this might be slow but it is really needed - modules might do some extra cleanup!
3833     //now do a brute force cleanup
3835     // remove from all cohorts
3836     $DB->delete_records('cohort_members', array('userid'=>$user->id));
3838     // remove from all groups
3839     $DB->delete_records('groups_members', array('userid'=>$user->id));
3841     // brute force unenrol from all courses
3842     $DB->delete_records('user_enrolments', array('userid'=>$user->id));
3844     // purge user preferences
3845     $DB->delete_records('user_preferences', array('userid'=>$user->id));
3847     // purge user extra profile info
3848     $DB->delete_records('user_info_data', array('userid'=>$user->id));
3850     // last course access not necessary either
3851     $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
3853     // remove all user tokens
3854     $DB->delete_records('external_tokens', array('userid'=>$user->id));
3856     // unauthorise the user for all services
3857     $DB->delete_records('external_services_users', array('userid'=>$user->id));
3859     // force logout - may fail if file based sessions used, sorry
3860     session_kill_user($user->id);
3862     // now do a final accesslib cleanup - removes all role assignments in user context and context itself
3863     delete_context(CONTEXT_USER, $user->id);
3865     // workaround for bulk deletes of users with the same email address
3866     $delname = "$user->email.".time();
3867     while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3868         $delname++;
3869     }
3871     // mark internal user record as "deleted"
3872     $updateuser = new stdClass();
3873     $updateuser->id           = $user->id;
3874     $updateuser->deleted      = 1;
3875     $updateuser->username     = $delname;            // Remember it just in case
3876     $updateuser->email        = md5($user->username);// Store hash of username, useful importing/restoring users
3877     $updateuser->idnumber     = '';                  // Clear this field to free it up
3878     $updateuser->timemodified = time();
3880     $DB->update_record('user', $updateuser);
3882     // We will update the user's timemodified, as it will be passed to the user_deleted event, which
3883     // should know about this updated property persisted to the user's table.
3884     $user->timemodified = $updateuser->timemodified;
3886     // notify auth plugin - do not block the delete even when plugin fails
3887     $authplugin = get_auth_plugin($user->auth);
3888     $authplugin->user_delete($user);
3890     // any plugin that needs to cleanup should register this event
3891     events_trigger('user_deleted', $user);
3893     return true;
3896 /**
3897  * Retrieve the guest user object
3898  *
3899  * @global object
3900  * @global object
3901  * @return user A {@link $USER} object
3902  */
3903 function guest_user() {
3904     global $CFG, $DB;
3906     if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
3907         $newuser->confirmed = 1;
3908         $newuser->lang = $CFG->lang;
3909         $newuser->lastip = getremoteaddr();
3910     }
3912     return $newuser;
3915 /**
3916  * Authenticates a user against the chosen authentication mechanism
3917  *
3918  * Given a username and password, this function looks them
3919  * up using the currently selected authentication mechanism,
3920  * and if the authentication is successful, it returns a
3921  * valid $user object from the 'user' table.
3922  *
3923  * Uses auth_ functions from the currently active auth module
3924  *
3925  * After authenticate_user_login() returns success, you will need to
3926  * log that the user has logged in, and call complete_user_login() to set
3927  * the session up.
3928  *
3929  * Note: this function works only with non-mnet accounts!
3930  *
3931  * @param string $username  User's username
3932  * @param string $password  User's password
3933  * @return user|flase A {@link $USER} object or false if error
3934  */
3935 function authenticate_user_login($username, $password) {
3936     global $CFG, $DB;
3938     $authsenabled = get_enabled_auth_plugins();
3940     if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
3941         $auth = empty($user->auth) ? 'manual' : $user->auth;  // use manual if auth not set
3942         if (!empty($user->suspended)) {
3943             add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3944             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Suspended Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3945             return false;
3946         }
3947         if ($auth=='nologin' or !is_enabled_auth($auth)) {
3948             add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3949             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Disabled Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3950             return false;
3951         }
3952         $auths = array($auth);
3954     } else {
3955         // check if there's a deleted record (cheaply)
3956         if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
3957             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Deleted Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3958             return false;
3959         }
3961         // User does not exist
3962         $auths = $authsenabled;
3963         $user = new stdClass();
3964         $user->id = 0;
3965     }
3967     foreach ($auths as $auth) {
3968         $authplugin = get_auth_plugin($auth);
3970         // on auth fail fall through to the next plugin
3971         if (!$authplugin->user_login($username, $password)) {
3972             continue;
3973         }
3975         // successful authentication
3976         if ($user->id) {                          // User already exists in database
3977             if (empty($user->auth)) {             // For some reason auth isn't set yet
3978                 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
3979                 $user->auth = $auth;
3980             }
3981             if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3982                 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
3983                 $user->firstaccess = $user->timemodified;
3984             }
3986             update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3988             if ($authplugin->is_synchronised_with_external()) { // update user record from external DB
3989                 $user = update_user_record($username);
3990             }
3991         } else {
3992             // if user not found and user creation is not disabled, create it
3993             if (empty($CFG->authpreventaccountcreation)) {
3994                 $user = create_user_record($username, $password, $auth);
3995             } else {
3996                 continue;
3997             }
3998         }
4000         $authplugin->sync_roles($user);
4002         foreach ($authsenabled as $hau) {
4003             $hauth = get_auth_plugin($hau);
4004             $hauth->user_authenticated_hook($user, $username, $password);
4005         }
4007         if (empty($user->id)) {
4008             return false;
4009         }
4011         if (!empty($user->suspended)) {
4012             // just in case some auth plugin suspended account
4013             add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4014             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Suspended Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
4015             return false;
4016         }
4018         return $user;
4019     }
4021     // failed if all the plugins have failed
4022     add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4023     if (debugging('', DEBUG_ALL)) {
4024         error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Failed Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
4025     }
4026     return false;
4029 /**
4030  * Call to complete the user login process after authenticate_user_login()
4031  * has succeeded. It will setup the $USER variable and other required bits
4032  * and pieces.
4033  *
4034  * NOTE:
4035  * - It will NOT log anything -- up to the caller to decide what to log.
4036  * - this function does not set any cookies any more!
4037  *
4038  * @param object $user
4039  * @return object A {@link $USER} object - BC only, do not use
4040  */
4041 function complete_user_login($user) {
4042     global $CFG, $USER;
4044     // regenerate session id and delete old session,
4045     // this helps prevent session fixation attacks from the same domain
4046     session_regenerate_id(true);
4048     // let enrol plugins deal with new enrolments if necessary
4049     enrol_check_plugins($user);
4051     // check enrolments, load caps and setup $USER object
4052     session_set_user($user);
4054     // reload preferences from DB
4055     unset($USER->preference);
4056     check_user_preferences_loaded($USER);
4058     // update login times
4059     update_user_login_times();
4061     // extra session prefs init
4062     set_login_session_preferences();
4064     if (isguestuser()) {
4065         // no need to continue when user is THE guest
4066         return $USER;
4067     }
4069     /// Select password change url
4070     $userauth = get_auth_plugin($USER->auth);
4072     /// check whether the user should be changing password
4073     if (get_user_preferences('auth_forcepasswordchange', false)){
4074         if ($userauth->can_change_password()) {
4075             if ($changeurl = $userauth->change_password_url()) {
4076                 redirect($changeurl);
4077             } else {
4078                 redirect($CFG->httpswwwroot.'/login/change_password.php');
4079             }
4080         } else {
4081             print_error('nopasswordchangeforced', 'auth');
4082         }
4083     }
4084     return $USER;
4087 /**
4088  * Compare password against hash stored in internal user table.
4089  * If necessary it also updates the stored hash to new format.
4090  *
4091  * @param stdClass $user (password property may be updated)
4092  * @param string $password plain text password
4093  * @return bool is password valid?
4094  */
4095 function validate_internal_user_password($user, $password) {
4096     global $CFG;
4098     if (!isset($CFG->passwordsaltmain)) {
4099         $CFG->passwordsaltmain = '';
4100     }
4102     $validated = false;
4104     if ($user->password === 'not cached') {
4105         // internal password is not used at all, it can not validate
4107     } else if ($user->password === md5($password.$CFG->passwordsaltmain)
4108             or $user->password === md5($password)
4109             or $user->password === md5(addslashes($password).$CFG->passwordsaltmain)
4110             or $user->password === md5(addslashes($password))) {
4111         // note: we are intentionally using the addslashes() here because we
4112         //       need to accept old password hashes of passwords with magic quotes
4113         $validated = true;
4115     } else {
4116         for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
4117             $alt = 'passwordsaltalt'.$i;
4118             if (!empty($CFG->$alt)) {
4119                 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4120                     $validated = true;
4121                     break;
4122                 }
4123             }
4124         }
4125     }
4127     if ($validated) {
4128         // force update of password hash using latest main password salt and encoding if needed
4129         update_internal_user_password($user, $password);
4130     }
4132     return $validated;
4135 /**
4136  * Calculate hashed value from password using current hash mechanism.
4137  *
4138  * @param string $password
4139  * @return string password hash
4140  */
4141 function hash_internal_user_password($password) {
4142     global $CFG;
4144     if (isset($CFG->passwordsaltmain)) {
4145         return md5($password.$CFG->passwordsaltmain);
4146     } else {
4147         return md5($password);
4148     }
4151 /**
4152  * Update password hash in user object.
4153  *
4154  * @param stdClass $user (password property may be updated)
4155  * @param string $password plain text password
4156  * @return bool always returns true
4157  */
4158 function update_internal_user_password($user, $password) {
4159     global $DB;
4161     $authplugin = get_auth_plugin($user->auth);
4162     if ($authplugin->prevent_local_passwords()) {
4163         $hashedpassword = 'not cached';
4164     } else {
4165         $hashedpassword = hash_internal_user_password($password);
4166     }
4168     if ($user->password !== $hashedpassword) {
4169         $DB->set_field('user', 'password',  $hashedpassword, array('id'=>$user->id));
4170         $user->password = $hashedpassword;
4171     }
4173     return true;
4176 /**
4177  * Get a complete user record, which includes all the info
4178  * in the user record.
4179  *
4180  * Intended for setting as $USER session variable
4181  *
4182  * @param string $field The user field to be checked for a given value.
4183  * @param string $value The value to match for $field.
4184  * @param int $mnethostid
4185  * @return mixed False, or A {@link $USER} object.
4186  */
4187 function get_complete_user_data($field, $value, $mnethostid = null) {
4188     global $CFG, $DB;
4190     if (!$field || !$value) {
4191         return false;
4192     }
4194 /// Build the WHERE clause for an SQL query
4195     $params = array('fieldval'=>$value);
4196     $constraints = "$field = :fieldval AND deleted <> 1";
4198     // If we are loading user data based on anything other than id,
4199     // we must also restrict our search based on mnet host.
4200     if ($field != 'id') {
4201         if (empty($mnethostid)) {
4202             // if empty, we restrict to local users
4203             $mnethostid = $CFG->mnet_localhost_id;
4204         }
4205     }
4206     if (!empty($mnethostid)) {
4207         $params['mnethostid'] = $mnethostid;
4208         $constraints .= " AND mnethostid = :mnethostid";
4209     }
4211 /// Get all the basic user data
4213     if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4214         return false;
4215     }
4217 /// Get various settings and preferences
4219     // preload preference cache
4220     check_user_preferences_loaded($user);
4222     // load course enrolment related stuff
4223     $user->lastcourseaccess    = array(); // during last session
4224     $user->currentcourseaccess = array(); // during current session
4225     if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid'=>$user->id))) {
4226         foreach ($lastaccesses as $lastaccess) {
4227             $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4228         }
4229     }
4231     $sql = "SELECT g.id, g.courseid
4232               FROM {groups} g, {groups_members} gm
4233              WHERE gm.groupid=g.id AND gm.userid=?";
4235     // this is a special hack to speedup calendar display
4236     $user->groupmember = array();
4237     if (!isguestuser($user)) {
4238         if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4239             foreach ($groups as $group) {
4240                 if (!array_key_exists($group->courseid, $user->groupmember)) {
4241                     $user->groupmember[$group->courseid] = array();
4242                 }
4243                 $user->groupmember[$group->courseid][$group->id] = $group->id;
4244             }
4245         }
4246     }
4248 /// Add the custom profile fields to the user record
4249     $user->profile = array();
4250     if (!isguestuser($user)) {
4251         require_once($CFG->dirroot.'/user/profile/lib.php');
4252         profile_load_custom_fields($user);
4253     }
4255 /// Rewrite some variables if necessary
4256     if (!empty($user->description)) {
4257         $user->description = true;   // No need to cart all of it around
4258     }
4259     if (isguestuser($user)) {
4260         $user->lang       = $CFG->lang;               // Guest language always same as site
4261         $user->firstname  = get_string('guestuser');  // Name always in current language
4262         $user->lastname   = ' ';
4263     }
4265     return $user;
4268 /**
4269  * Validate a password against the configured password policy
4270  *
4271  * @global object
4272  * @param string $password the password to be checked against the password policy
4273  * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4274  * @return bool true if the password is valid according to the policy. false otherwise.
4275  */
4276 function check_password_policy($password, &$errmsg) {
4277     global $CFG;
4279     if (empty($CFG->passwordpolicy)) {
4280         return true;
4281     }
4283     $textlib = textlib_get_instance();
4284     $errmsg = '';
4285     if ($textlib->strlen($password) < $CFG->minpasswordlength) {
4286         $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4288     }
4289     if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4290         $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4292     }
4293     if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4294         $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4296     }
4297     if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4298         $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4300     }
4301     if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4302         $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4303     }
4304     if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4305         $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4306     }
4308     if ($errmsg == '') {
4309         return true;
4310     } else {
4311         return false;
4312     }
4316 /**
4317  * When logging in, this function is run to set certain preferences
4318  * for the current SESSION
4319  *
4320  * @global object
4321  * @global object
4322  */
4323 function set_login_session_preferences() {
4324     global $SESSION, $CFG;
4326     $SESSION->justloggedin = true;
4328     unset($SESSION->lang);
4332 /**
4333  * Delete a course, including all related data from the database,
4334  * and any associated files.
4335  *
4336  * @global object
4337  * @global object
4338  * @param mixed $courseorid The id of the course or course object to delete.
4339  * @param bool $showfeedback Whether to display notifications of each action the function performs.
4340  * @return bool true if all the removals succeeded. false if there were any failures. If this
4341  *             method returns false, some of the removals will probably have succeeded, and others
4342  *             failed, but you have no way of knowing which.
4343  */
4344 function delete_course($courseorid, $showfeedback = true) {
4345     global $DB;
4347     if (is_object($courseorid)) {
4348         $courseid = $courseorid->id;
4349         $course   = $courseorid;
4350     } else {
4351         $courseid = $courseorid;
4352         if (!$course = $DB->get_record('course', array('id'=>$courseid))) {
4353             return false;
4354         }
4355     }
4356     $context = get_context_instance(CONTEXT_COURSE, $courseid);
4358     // frontpage course can not be deleted!!
4359     if ($courseid == SITEID) {
4360         return false;
4361     }