65428bdaafafca05c97c051533f94e88a6b5823d
[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             $param = textlib::substr(trim($param), 0, TAG_MAX_LENGTH);
1010             return $param;
1012         case PARAM_TAGLIST:
1013             $param = fix_utf8($param);
1014             $tags = explode(',', $param);
1015             $result = array();
1016             foreach ($tags as $tag) {
1017                 $res = clean_param($tag, PARAM_TAG);
1018                 if ($res !== '') {
1019                     $result[] = $res;
1020                 }
1021             }
1022             if ($result) {
1023                 return implode(',', $result);
1024             } else {
1025                 return '';
1026             }
1028         case PARAM_CAPABILITY:
1029             if (get_capability_info($param)) {
1030                 return $param;
1031             } else {
1032                 return '';
1033             }
1035         case PARAM_PERMISSION:
1036             $param = (int)$param;
1037             if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1038                 return $param;
1039             } else {
1040                 return CAP_INHERIT;
1041             }
1043         case PARAM_AUTH:
1044             $param = clean_param($param, PARAM_PLUGIN);
1045             if (empty($param)) {
1046                 return '';
1047             } else if (exists_auth_plugin($param)) {
1048                 return $param;
1049             } else {
1050                 return '';
1051             }
1053         case PARAM_LANG:
1054             $param = clean_param($param, PARAM_SAFEDIR);
1055             if (get_string_manager()->translation_exists($param)) {
1056                 return $param;
1057             } else {
1058                 return ''; // Specified language is not installed or param malformed
1059             }
1061         case PARAM_THEME:
1062             $param = clean_param($param, PARAM_PLUGIN);
1063             if (empty($param)) {
1064                 return '';
1065             } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1066                 return $param;
1067             } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1068                 return $param;
1069             } else {
1070                 return '';  // Specified theme is not installed
1071             }
1073         case PARAM_USERNAME:
1074             $param = fix_utf8($param);
1075             $param = str_replace(" " , "", $param);
1076             $param = textlib::strtolower($param);  // Convert uppercase to lowercase MDL-16919
1077             if (empty($CFG->extendedusernamechars)) {
1078                 // regular expression, eliminate all chars EXCEPT:
1079                 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1080                 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1081             }
1082             return $param;
1084         case PARAM_EMAIL:
1085             $param = fix_utf8($param);
1086             if (validate_email($param)) {
1087                 return $param;
1088             } else {
1089                 return '';
1090             }
1092         case PARAM_STRINGID:
1093             if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1094                 return $param;
1095             } else {
1096                 return '';
1097             }
1099         case PARAM_TIMEZONE:    //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1100             $param = fix_utf8($param);
1101             $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1102             if (preg_match($timezonepattern, $param)) {
1103                 return $param;
1104             } else {
1105                 return '';
1106             }
1108         default:                 // throw error, switched parameters in optional_param or another serious problem
1109             print_error("unknownparamtype", '', '', $type);
1110     }
1113 /**
1114  * Makes sure the data is using valid utf8, invalid characters are discarded.
1115  *
1116  * Note: this function is not intended for full objects with methods and private properties.
1117  *
1118  * @param mixed $value
1119  * @return mixed with proper utf-8 encoding
1120  */
1121 function fix_utf8($value) {
1122     if (is_null($value) or $value === '') {
1123         return $value;
1125     } else if (is_string($value)) {
1126         if ((string)(int)$value === $value) {
1127             // shortcut
1128             return $value;
1129         }
1130         // lower error reporting because glibc throws bogus notices
1131         $olderror = error_reporting();
1132         if ($olderror & E_NOTICE) {
1133             error_reporting($olderror ^ E_NOTICE);
1134         }
1135         $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1136         if ($olderror & E_NOTICE) {
1137             error_reporting($olderror);
1138         }
1139         return $result;
1141     } else if (is_array($value)) {
1142         foreach ($value as $k=>$v) {
1143             $value[$k] = fix_utf8($v);
1144         }
1145         return $value;
1147     } else if (is_object($value)) {
1148         $value = clone($value); // do not modify original
1149         foreach ($value as $k=>$v) {
1150             $value->$k = fix_utf8($v);
1151         }
1152         return $value;
1154     } else {
1155         // this is some other type, no utf-8 here
1156         return $value;
1157     }
1160 /**
1161  * Return true if given value is integer or string with integer value
1162  *
1163  * @param mixed $value String or Int
1164  * @return bool true if number, false if not
1165  */
1166 function is_number($value) {
1167     if (is_int($value)) {
1168         return true;
1169     } else if (is_string($value)) {
1170         return ((string)(int)$value) === $value;
1171     } else {
1172         return false;
1173     }
1176 /**
1177  * Returns host part from url
1178  * @param string $url full url
1179  * @return string host, null if not found
1180  */
1181 function get_host_from_url($url) {
1182     preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1183     if ($matches) {
1184         return $matches[1];
1185     }
1186     return null;
1189 /**
1190  * Tests whether anything was returned by text editor
1191  *
1192  * This function is useful for testing whether something you got back from
1193  * the HTML editor actually contains anything. Sometimes the HTML editor
1194  * appear to be empty, but actually you get back a <br> tag or something.
1195  *
1196  * @param string $string a string containing HTML.
1197  * @return boolean does the string contain any actual content - that is text,
1198  * images, objects, etc.
1199  */
1200 function html_is_blank($string) {
1201     return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1204 /**
1205  * Set a key in global configuration
1206  *
1207  * Set a key/value pair in both this session's {@link $CFG} global variable
1208  * and in the 'config' database table for future sessions.
1209  *
1210  * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1211  * In that case it doesn't affect $CFG.
1212  *
1213  * A NULL value will delete the entry.
1214  *
1215  * @global object
1216  * @global object
1217  * @param string $name the key to set
1218  * @param string $value the value to set (without magic quotes)
1219  * @param string $plugin (optional) the plugin scope, default NULL
1220  * @return bool true or exception
1221  */
1222 function set_config($name, $value, $plugin=NULL) {
1223     global $CFG, $DB;
1225     if (empty($plugin)) {
1226         if (!array_key_exists($name, $CFG->config_php_settings)) {
1227             // So it's defined for this invocation at least
1228             if (is_null($value)) {
1229                 unset($CFG->$name);
1230             } else {
1231                 $CFG->$name = (string)$value; // settings from db are always strings
1232             }
1233         }
1235         if ($DB->get_field('config', 'name', array('name'=>$name))) {
1236             if ($value === null) {
1237                 $DB->delete_records('config', array('name'=>$name));
1238             } else {
1239                 $DB->set_field('config', 'value', $value, array('name'=>$name));
1240             }
1241         } else {
1242             if ($value !== null) {
1243                 $config = new stdClass();
1244                 $config->name  = $name;
1245                 $config->value = $value;
1246                 $DB->insert_record('config', $config, false);
1247             }
1248         }
1250     } else { // plugin scope
1251         if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1252             if ($value===null) {
1253                 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1254             } else {
1255                 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1256             }
1257         } else {
1258             if ($value !== null) {
1259                 $config = new stdClass();
1260                 $config->plugin = $plugin;
1261                 $config->name   = $name;
1262                 $config->value  = $value;
1263                 $DB->insert_record('config_plugins', $config, false);
1264             }
1265         }
1266     }
1268     return true;
1271 /**
1272  * Get configuration values from the global config table
1273  * or the config_plugins table.
1274  *
1275  * If called with one parameter, it will load all the config
1276  * variables for one plugin, and return them as an object.
1277  *
1278  * If called with 2 parameters it will return a string single
1279  * value or false if the value is not found.
1280  *
1281  * @param string $plugin full component name
1282  * @param string $name default NULL
1283  * @return mixed hash-like object or single value, return false no config found
1284  */
1285 function get_config($plugin, $name = NULL) {
1286     global $CFG, $DB;
1288     // normalise component name
1289     if ($plugin === 'moodle' or $plugin === 'core') {
1290         $plugin = NULL;
1291     }
1293     if (!empty($name)) { // the user is asking for a specific value
1294         if (!empty($plugin)) {
1295             if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1296                 // setting forced in config file
1297                 return $CFG->forced_plugin_settings[$plugin][$name];
1298             } else {
1299                 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1300             }
1301         } else {
1302             if (array_key_exists($name, $CFG->config_php_settings)) {
1303                 // setting force in config file
1304                 return $CFG->config_php_settings[$name];
1305             } else {
1306                 return $DB->get_field('config', 'value', array('name'=>$name));
1307             }
1308         }
1309     }
1311     // the user is after a recordset
1312     if ($plugin) {
1313         $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1314         if (isset($CFG->forced_plugin_settings[$plugin])) {
1315             foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1316                 if (is_null($v) or is_array($v) or is_object($v)) {
1317                     // we do not want any extra mess here, just real settings that could be saved in db
1318                     unset($localcfg[$n]);
1319                 } else {
1320                     //convert to string as if it went through the DB
1321                     $localcfg[$n] = (string)$v;
1322                 }
1323             }
1324         }
1325         if ($localcfg) {
1326             return (object)$localcfg;
1327         } else {
1328             return new stdClass();
1329         }
1331     } else {
1332         // this part is not really used any more, but anyway...
1333         $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1334         foreach($CFG->config_php_settings as $n=>$v) {
1335             if (is_null($v) or is_array($v) or is_object($v)) {
1336                 // we do not want any extra mess here, just real settings that could be saved in db
1337                 unset($localcfg[$n]);
1338             } else {
1339                 //convert to string as if it went through the DB
1340                 $localcfg[$n] = (string)$v;
1341             }
1342         }
1343         return (object)$localcfg;
1344     }
1347 /**
1348  * Removes a key from global configuration
1349  *
1350  * @param string $name the key to set
1351  * @param string $plugin (optional) the plugin scope
1352  * @global object
1353  * @return boolean whether the operation succeeded.
1354  */
1355 function unset_config($name, $plugin=NULL) {
1356     global $CFG, $DB;
1358     if (empty($plugin)) {
1359         unset($CFG->$name);
1360         $DB->delete_records('config', array('name'=>$name));
1361     } else {
1362         $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1363     }
1365     return true;
1368 /**
1369  * Remove all the config variables for a given plugin.
1370  *
1371  * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1372  * @return boolean whether the operation succeeded.
1373  */
1374 function unset_all_config_for_plugin($plugin) {
1375     global $DB;
1376     $DB->delete_records('config_plugins', array('plugin' => $plugin));
1377     $like = $DB->sql_like('name', '?', true, true, false, '|');
1378     $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1379     $DB->delete_records_select('config', $like, $params);
1380     return true;
1383 /**
1384  * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1385  *
1386  * All users are verified if they still have the necessary capability.
1387  *
1388  * @param string $value the value of the config setting.
1389  * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1390  * @param bool $include admins, include administrators
1391  * @return array of user objects.
1392  */
1393 function get_users_from_config($value, $capability, $includeadmins = true) {
1394     global $CFG, $DB;
1396     if (empty($value) or $value === '$@NONE@$') {
1397         return array();
1398     }
1400     // we have to make sure that users still have the necessary capability,
1401     // it should be faster to fetch them all first and then test if they are present
1402     // instead of validating them one-by-one
1403     $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1404     if ($includeadmins) {
1405         $admins = get_admins();
1406         foreach ($admins as $admin) {
1407             $users[$admin->id] = $admin;
1408         }
1409     }
1411     if ($value === '$@ALL@$') {
1412         return $users;
1413     }
1415     $result = array(); // result in correct order
1416     $allowed = explode(',', $value);
1417     foreach ($allowed as $uid) {
1418         if (isset($users[$uid])) {
1419             $user = $users[$uid];
1420             $result[$user->id] = $user;
1421         }
1422     }
1424     return $result;
1428 /**
1429  * Invalidates browser caches and cached data in temp
1430  * @return void
1431  */
1432 function purge_all_caches() {
1433     global $CFG;
1435     reset_text_filters_cache();
1436     js_reset_all_caches();
1437     theme_reset_all_caches();
1438     get_string_manager()->reset_caches();
1439     textlib::reset_caches();
1441     // purge all other caches: rss, simplepie, etc.
1442     remove_dir($CFG->cachedir.'', true);
1444     // make sure cache dir is writable, throws exception if not
1445     make_cache_directory('');
1447     // hack: this script may get called after the purifier was initialised,
1448     // but we do not want to verify repeatedly this exists in each call
1449     make_cache_directory('htmlpurifier');
1452 /**
1453  * Get volatile flags
1454  *
1455  * @param string $type
1456  * @param int    $changedsince default null
1457  * @return records array
1458  */
1459 function get_cache_flags($type, $changedsince=NULL) {
1460     global $DB;
1462     $params = array('type'=>$type, 'expiry'=>time());
1463     $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1464     if ($changedsince !== NULL) {
1465         $params['changedsince'] = $changedsince;
1466         $sqlwhere .= " AND timemodified > :changedsince";
1467     }
1468     $cf = array();
1470     if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1471         foreach ($flags as $flag) {
1472             $cf[$flag->name] = $flag->value;
1473         }
1474     }
1475     return $cf;
1478 /**
1479  * Get volatile flags
1480  *
1481  * @param string $type
1482  * @param string $name
1483  * @param int    $changedsince default null
1484  * @return records array
1485  */
1486 function get_cache_flag($type, $name, $changedsince=NULL) {
1487     global $DB;
1489     $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1491     $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1492     if ($changedsince !== NULL) {
1493         $params['changedsince'] = $changedsince;
1494         $sqlwhere .= " AND timemodified > :changedsince";
1495     }
1497     return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1500 /**
1501  * Set a volatile flag
1502  *
1503  * @param string $type the "type" namespace for the key
1504  * @param string $name the key to set
1505  * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1506  * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1507  * @return bool Always returns true
1508  */
1509 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1510     global $DB;
1512     $timemodified = time();
1513     if ($expiry===NULL || $expiry < $timemodified) {
1514         $expiry = $timemodified + 24 * 60 * 60;
1515     } else {
1516         $expiry = (int)$expiry;
1517     }
1519     if ($value === NULL) {
1520         unset_cache_flag($type,$name);
1521         return true;
1522     }
1524     if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1525         if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1526             return true; //no need to update; helps rcache too
1527         }
1528         $f->value        = $value;
1529         $f->expiry       = $expiry;
1530         $f->timemodified = $timemodified;
1531         $DB->update_record('cache_flags', $f);
1532     } else {
1533         $f = new stdClass();
1534         $f->flagtype     = $type;
1535         $f->name         = $name;
1536         $f->value        = $value;
1537         $f->expiry       = $expiry;
1538         $f->timemodified = $timemodified;
1539         $DB->insert_record('cache_flags', $f);
1540     }
1541     return true;
1544 /**
1545  * Removes a single volatile flag
1546  *
1547  * @global object
1548  * @param string $type the "type" namespace for the key
1549  * @param string $name the key to set
1550  * @return bool
1551  */
1552 function unset_cache_flag($type, $name) {
1553     global $DB;
1554     $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1555     return true;
1558 /**
1559  * Garbage-collect volatile flags
1560  *
1561  * @return bool Always returns true
1562  */
1563 function gc_cache_flags() {
1564     global $DB;
1565     $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1566     return true;
1569 // USER PREFERENCE API
1571 /**
1572  * Refresh user preference cache. This is used most often for $USER
1573  * object that is stored in session, but it also helps with performance in cron script.
1574  *
1575  * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1576  *
1577  * @package  core
1578  * @category preference
1579  * @access   public
1580  * @param    stdClass         $user          User object. Preferences are preloaded into 'preference' property
1581  * @param    int              $cachelifetime Cache life time on the current page (in seconds)
1582  * @throws   coding_exception
1583  * @return   null
1584  */
1585 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1586     global $DB;
1587     static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1589     if (!isset($user->id)) {
1590         throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1591     }
1593     if (empty($user->id) or isguestuser($user->id)) {
1594         // No permanent storage for not-logged-in users and guest
1595         if (!isset($user->preference)) {
1596             $user->preference = array();
1597         }
1598         return;
1599     }
1601     $timenow = time();
1603     if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1604         // Already loaded at least once on this page. Are we up to date?
1605         if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1606             // no need to reload - we are on the same page and we loaded prefs just a moment ago
1607             return;
1609         } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1610             // no change since the lastcheck on this page
1611             $user->preference['_lastloaded'] = $timenow;
1612             return;
1613         }
1614     }
1616     // OK, so we have to reload all preferences
1617     $loadedusers[$user->id] = true;
1618     $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1619     $user->preference['_lastloaded'] = $timenow;
1622 /**
1623  * Called from set/unset_user_preferences, so that the prefs can
1624  * be correctly reloaded in different sessions.
1625  *
1626  * NOTE: internal function, do not call from other code.
1627  *
1628  * @package core
1629  * @access  private
1630  * @param   integer         $userid the user whose prefs were changed.
1631  */
1632 function mark_user_preferences_changed($userid) {
1633     global $CFG;
1635     if (empty($userid) or isguestuser($userid)) {
1636         // no cache flags for guest and not-logged-in users
1637         return;
1638     }
1640     set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1643 /**
1644  * Sets a preference for the specified user.
1645  *
1646  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1647  *
1648  * @package  core
1649  * @category preference
1650  * @access   public
1651  * @param    string            $name  The key to set as preference for the specified user
1652  * @param    string            $value The value to set for the $name key in the specified user's
1653  *                                    record, null means delete current value.
1654  * @param    stdClass|int|null $user  A moodle user object or id, null means current user
1655  * @throws   coding_exception
1656  * @return   bool                     Always true or exception
1657  */
1658 function set_user_preference($name, $value, $user = null) {
1659     global $USER, $DB;
1661     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1662         throw new coding_exception('Invalid preference name in set_user_preference() call');
1663     }
1665     if (is_null($value)) {
1666         // null means delete current
1667         return unset_user_preference($name, $user);
1668     } else if (is_object($value)) {
1669         throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1670     } else if (is_array($value)) {
1671         throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1672     }
1673     $value = (string)$value;
1674     if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1675         throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1676     }
1678     if (is_null($user)) {
1679         $user = $USER;
1680     } else if (isset($user->id)) {
1681         // $user is valid object
1682     } else if (is_numeric($user)) {
1683         $user = (object)array('id'=>(int)$user);
1684     } else {
1685         throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1686     }
1688     check_user_preferences_loaded($user);
1690     if (empty($user->id) or isguestuser($user->id)) {
1691         // no permanent storage for not-logged-in users and guest
1692         $user->preference[$name] = $value;
1693         return true;
1694     }
1696     if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1697         if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1698             // preference already set to this value
1699             return true;
1700         }
1701         $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1703     } else {
1704         $preference = new stdClass();
1705         $preference->userid = $user->id;
1706         $preference->name   = $name;
1707         $preference->value  = $value;
1708         $DB->insert_record('user_preferences', $preference);
1709     }
1711     // update value in cache
1712     $user->preference[$name] = $value;
1714     // set reload flag for other sessions
1715     mark_user_preferences_changed($user->id);
1717     return true;
1720 /**
1721  * Sets a whole array of preferences for the current user
1722  *
1723  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1724  *
1725  * @package  core
1726  * @category preference
1727  * @access   public
1728  * @param    array             $prefarray An array of key/value pairs to be set
1729  * @param    stdClass|int|null $user      A moodle user object or id, null means current user
1730  * @return   bool                         Always true or exception
1731  */
1732 function set_user_preferences(array $prefarray, $user = null) {
1733     foreach ($prefarray as $name => $value) {
1734         set_user_preference($name, $value, $user);
1735     }
1736     return true;
1739 /**
1740  * Unsets a preference completely by deleting it from the database
1741  *
1742  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1743  *
1744  * @package  core
1745  * @category preference
1746  * @access   public
1747  * @param    string            $name The key to unset as preference for the specified user
1748  * @param    stdClass|int|null $user A moodle user object or id, null means current user
1749  * @throws   coding_exception
1750  * @return   bool                    Always true or exception
1751  */
1752 function unset_user_preference($name, $user = null) {
1753     global $USER, $DB;
1755     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1756         throw new coding_exception('Invalid preference name in unset_user_preference() call');
1757     }
1759     if (is_null($user)) {
1760         $user = $USER;
1761     } else if (isset($user->id)) {
1762         // $user is valid object
1763     } else if (is_numeric($user)) {
1764         $user = (object)array('id'=>(int)$user);
1765     } else {
1766         throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1767     }
1769     check_user_preferences_loaded($user);
1771     if (empty($user->id) or isguestuser($user->id)) {
1772         // no permanent storage for not-logged-in user and guest
1773         unset($user->preference[$name]);
1774         return true;
1775     }
1777     // delete from DB
1778     $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1780     // delete the preference from cache
1781     unset($user->preference[$name]);
1783     // set reload flag for other sessions
1784     mark_user_preferences_changed($user->id);
1786     return true;
1789 /**
1790  * Used to fetch user preference(s)
1791  *
1792  * If no arguments are supplied this function will return
1793  * all of the current user preferences as an array.
1794  *
1795  * If a name is specified then this function
1796  * attempts to return that particular preference value.  If
1797  * none is found, then the optional value $default is returned,
1798  * otherwise NULL.
1799  *
1800  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1801  *
1802  * @package  core
1803  * @category preference
1804  * @access   public
1805  * @param    string            $name    Name of the key to use in finding a preference value
1806  * @param    mixed|null        $default Value to be returned if the $name key is not set in the user preferences
1807  * @param    stdClass|int|null $user    A moodle user object or id, null means current user
1808  * @throws   coding_exception
1809  * @return   string|mixed|null          A string containing the value of a single preference. An
1810  *                                      array with all of the preferences or null
1811  */
1812 function get_user_preferences($name = null, $default = null, $user = null) {
1813     global $USER;
1815     if (is_null($name)) {
1816         // all prefs
1817     } else if (is_numeric($name) or $name === '_lastloaded') {
1818         throw new coding_exception('Invalid preference name in get_user_preferences() call');
1819     }
1821     if (is_null($user)) {
1822         $user = $USER;
1823     } else if (isset($user->id)) {
1824         // $user is valid object
1825     } else if (is_numeric($user)) {
1826         $user = (object)array('id'=>(int)$user);
1827     } else {
1828         throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1829     }
1831     check_user_preferences_loaded($user);
1833     if (empty($name)) {
1834         return $user->preference; // All values
1835     } else if (isset($user->preference[$name])) {
1836         return $user->preference[$name]; // The single string value
1837     } else {
1838         return $default; // Default value (null if not specified)
1839     }
1842 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1844 /**
1845  * Given date parts in user time produce a GMT timestamp.
1846  *
1847  * @package core
1848  * @category time
1849  * @param int $year The year part to create timestamp of
1850  * @param int $month The month part to create timestamp of
1851  * @param int $day The day part to create timestamp of
1852  * @param int $hour The hour part to create timestamp of
1853  * @param int $minute The minute part to create timestamp of
1854  * @param int $second The second part to create timestamp of
1855  * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1856  *             if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
1857  * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1858  *             applied only if timezone is 99 or string.
1859  * @return int GMT timestamp
1860  */
1861 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1863     //save input timezone, required for dst offset check.
1864     $passedtimezone = $timezone;
1866     $timezone = get_user_timezone_offset($timezone);
1868     if (abs($timezone) > 13) {  //server time
1869         $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1870     } else {
1871         $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1872         $time = usertime($time, $timezone);
1874         //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1875         if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1876             $time -= dst_offset_on($time, $passedtimezone);
1877         }
1878     }
1880     return $time;
1884 /**
1885  * Format a date/time (seconds) as weeks, days, hours etc as needed
1886  *
1887  * Given an amount of time in seconds, returns string
1888  * formatted nicely as weeks, days, hours etc as needed
1889  *
1890  * @package core
1891  * @category time
1892  * @uses MINSECS
1893  * @uses HOURSECS
1894  * @uses DAYSECS
1895  * @uses YEARSECS
1896  * @param int $totalsecs Time in seconds
1897  * @param object $str Should be a time object
1898  * @return string A nicely formatted date/time string
1899  */
1900  function format_time($totalsecs, $str=NULL) {
1902     $totalsecs = abs($totalsecs);
1904     if (!$str) {  // Create the str structure the slow way
1905         $str = new stdClass();
1906         $str->day   = get_string('day');
1907         $str->days  = get_string('days');
1908         $str->hour  = get_string('hour');
1909         $str->hours = get_string('hours');
1910         $str->min   = get_string('min');
1911         $str->mins  = get_string('mins');
1912         $str->sec   = get_string('sec');
1913         $str->secs  = get_string('secs');
1914         $str->year  = get_string('year');
1915         $str->years = get_string('years');
1916     }
1919     $years     = floor($totalsecs/YEARSECS);
1920     $remainder = $totalsecs - ($years*YEARSECS);
1921     $days      = floor($remainder/DAYSECS);
1922     $remainder = $totalsecs - ($days*DAYSECS);
1923     $hours     = floor($remainder/HOURSECS);
1924     $remainder = $remainder - ($hours*HOURSECS);
1925     $mins      = floor($remainder/MINSECS);
1926     $secs      = $remainder - ($mins*MINSECS);
1928     $ss = ($secs == 1)  ? $str->sec  : $str->secs;
1929     $sm = ($mins == 1)  ? $str->min  : $str->mins;
1930     $sh = ($hours == 1) ? $str->hour : $str->hours;
1931     $sd = ($days == 1)  ? $str->day  : $str->days;
1932     $sy = ($years == 1)  ? $str->year  : $str->years;
1934     $oyears = '';
1935     $odays = '';
1936     $ohours = '';
1937     $omins = '';
1938     $osecs = '';
1940     if ($years)  $oyears  = $years .' '. $sy;
1941     if ($days)  $odays  = $days .' '. $sd;
1942     if ($hours) $ohours = $hours .' '. $sh;
1943     if ($mins)  $omins  = $mins .' '. $sm;
1944     if ($secs)  $osecs  = $secs .' '. $ss;
1946     if ($years) return trim($oyears .' '. $odays);
1947     if ($days)  return trim($odays .' '. $ohours);
1948     if ($hours) return trim($ohours .' '. $omins);
1949     if ($mins)  return trim($omins .' '. $osecs);
1950     if ($secs)  return $osecs;
1951     return get_string('now');
1954 /**
1955  * Returns a formatted string that represents a date in user time
1956  *
1957  * Returns a formatted string that represents a date in user time
1958  * <b>WARNING: note that the format is for strftime(), not date().</b>
1959  * Because of a bug in most Windows time libraries, we can't use
1960  * the nicer %e, so we have to use %d which has leading zeroes.
1961  * A lot of the fuss in the function is just getting rid of these leading
1962  * zeroes as efficiently as possible.
1963  *
1964  * If parameter fixday = true (default), then take off leading
1965  * zero from %d, else maintain it.
1966  *
1967  * @package core
1968  * @category time
1969  * @param int $date the timestamp in UTC, as obtained from the database.
1970  * @param string $format strftime format. You should probably get this using
1971  *        get_string('strftime...', 'langconfig');
1972  * @param int|float|string  $timezone by default, uses the user's time zone. if numeric and
1973  *        not 99 then daylight saving will not be added.
1974  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
1975  * @param bool $fixday If true (default) then the leading zero from %d is removed.
1976  *        If false then the leading zero is maintained.
1977  * @param bool $fixhour If true (default) then the leading zero from %I is removed.
1978  * @return string the formatted date/time.
1979  */
1980 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
1982     global $CFG;
1984     if (empty($format)) {
1985         $format = get_string('strftimedaydatetime', 'langconfig');
1986     }
1988     if (!empty($CFG->nofixday)) {  // Config.php can force %d not to be fixed.
1989         $fixday = false;
1990     } else if ($fixday) {
1991         $formatnoday = str_replace('%d', 'DD', $format);
1992         $fixday = ($formatnoday != $format);
1993         $format = $formatnoday;
1994     }
1996     // Note: This logic about fixing 12-hour time to remove unnecessary leading
1997     // zero is required because on Windows, PHP strftime function does not
1998     // support the correct 'hour without leading zero' parameter (%l).
1999     if (!empty($CFG->nofixhour)) {
2000         // Config.php can force %I not to be fixed.
2001         $fixhour = false;
2002     } else if ($fixhour) {
2003         $formatnohour = str_replace('%I', 'HH', $format);
2004         $fixhour = ($formatnohour != $format);
2005         $format = $formatnohour;
2006     }
2008     //add daylight saving offset for string timezones only, as we can't get dst for
2009     //float values. if timezone is 99 (user default timezone), then try update dst.
2010     if ((99 == $timezone) || !is_numeric($timezone)) {
2011         $date += dst_offset_on($date, $timezone);
2012     }
2014     $timezone = get_user_timezone_offset($timezone);
2016     // If we are running under Windows convert to windows encoding and then back to UTF-8
2017     // (because it's impossible to specify UTF-8 to fetch locale info in Win32)
2019     if (abs($timezone) > 13) {   /// Server time
2020         if ($CFG->ostype == 'WINDOWS' and ($localewincharset = get_string('localewincharset', 'langconfig'))) {
2021             $format = textlib::convert($format, 'utf-8', $localewincharset);
2022             $datestring = strftime($format, $date);
2023             $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2024         } else {
2025             $datestring = strftime($format, $date);
2026         }
2027         if ($fixday) {
2028             $daystring  = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
2029             $datestring = str_replace('DD', $daystring, $datestring);
2030         }
2031         if ($fixhour) {
2032             $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2033             $datestring = str_replace('HH', $hourstring, $datestring);
2034         }
2036     } else {
2037         $date += (int)($timezone * 3600);
2038         if ($CFG->ostype == 'WINDOWS' and ($localewincharset = get_string('localewincharset', 'langconfig'))) {
2039             $format = textlib::convert($format, 'utf-8', $localewincharset);
2040             $datestring = gmstrftime($format, $date);
2041             $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2042         } else {
2043             $datestring = gmstrftime($format, $date);
2044         }
2045         if ($fixday) {
2046             $daystring  = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
2047             $datestring = str_replace('DD', $daystring, $datestring);
2048         }
2049         if ($fixhour) {
2050             $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2051             $datestring = str_replace('HH', $hourstring, $datestring);
2052         }
2053     }
2055     return $datestring;
2058 /**
2059  * Given a $time timestamp in GMT (seconds since epoch),
2060  * returns an array that represents the date in user time
2061  *
2062  * @package core
2063  * @category time
2064  * @uses HOURSECS
2065  * @param int $time Timestamp in GMT
2066  * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2067  *        dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
2068  * @return array An array that represents the date in user time
2069  */
2070 function usergetdate($time, $timezone=99) {
2072     //save input timezone, required for dst offset check.
2073     $passedtimezone = $timezone;
2075     $timezone = get_user_timezone_offset($timezone);
2077     if (abs($timezone) > 13) {    // Server time
2078         return getdate($time);
2079     }
2081     //add daylight saving offset for string timezones only, as we can't get dst for
2082     //float values. if timezone is 99 (user default timezone), then try update dst.
2083     if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2084         $time += dst_offset_on($time, $passedtimezone);
2085     }
2087     $time += intval((float)$timezone * HOURSECS);
2089     $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2091     //be careful to ensure the returned array matches that produced by getdate() above
2092     list(
2093         $getdate['month'],
2094         $getdate['weekday'],
2095         $getdate['yday'],
2096         $getdate['year'],
2097         $getdate['mon'],
2098         $getdate['wday'],
2099         $getdate['mday'],
2100         $getdate['hours'],
2101         $getdate['minutes'],
2102         $getdate['seconds']
2103     ) = explode('_', $datestring);
2105     // set correct datatype to match with getdate()
2106     $getdate['seconds'] = (int)$getdate['seconds'];
2107     $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
2108     $getdate['year'] = (int)$getdate['year'];
2109     $getdate['mon'] = (int)$getdate['mon'];
2110     $getdate['wday'] = (int)$getdate['wday'];
2111     $getdate['mday'] = (int)$getdate['mday'];
2112     $getdate['hours'] = (int)$getdate['hours'];
2113     $getdate['minutes']  = (int)$getdate['minutes'];
2114     return $getdate;
2117 /**
2118  * Given a GMT timestamp (seconds since epoch), offsets it by
2119  * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2120  *
2121  * @package core
2122  * @category time
2123  * @uses HOURSECS
2124  * @param int $date Timestamp in GMT
2125  * @param float|int|string $timezone timezone to calculate GMT time offset before
2126  *        calculating user time, 99 is default user timezone
2127  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2128  * @return int
2129  */
2130 function usertime($date, $timezone=99) {
2132     $timezone = get_user_timezone_offset($timezone);
2134     if (abs($timezone) > 13) {
2135         return $date;
2136     }
2137     return $date - (int)($timezone * HOURSECS);
2140 /**
2141  * Given a time, return the GMT timestamp of the most recent midnight
2142  * for the current user.
2143  *
2144  * @package core
2145  * @category time
2146  * @param int $date Timestamp in GMT
2147  * @param float|int|string $timezone timezone to calculate GMT time offset before
2148  *        calculating user midnight time, 99 is default user timezone
2149  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2150  * @return int Returns a GMT timestamp
2151  */
2152 function usergetmidnight($date, $timezone=99) {
2154     $userdate = usergetdate($date, $timezone);
2156     // Time of midnight of this user's day, in GMT
2157     return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2161 /**
2162  * Returns a string that prints the user's timezone
2163  *
2164  * @package core
2165  * @category time
2166  * @param float|int|string $timezone timezone to calculate GMT time offset before
2167  *        calculating user timezone, 99 is default user timezone
2168  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2169  * @return string
2170  */
2171 function usertimezone($timezone=99) {
2173     $tz = get_user_timezone($timezone);
2175     if (!is_float($tz)) {
2176         return $tz;
2177     }
2179     if(abs($tz) > 13) { // Server time
2180         return get_string('serverlocaltime');
2181     }
2183     if($tz == intval($tz)) {
2184         // Don't show .0 for whole hours
2185         $tz = intval($tz);
2186     }
2188     if($tz == 0) {
2189         return 'UTC';
2190     }
2191     else if($tz > 0) {
2192         return 'UTC+'.$tz;
2193     }
2194     else {
2195         return 'UTC'.$tz;
2196     }
2200 /**
2201  * Returns a float which represents the user's timezone difference from GMT in hours
2202  * Checks various settings and picks the most dominant of those which have a value
2203  *
2204  * @package core
2205  * @category time
2206  * @param float|int|string $tz timezone to calculate GMT time offset for user,
2207  *        99 is default user timezone
2208  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2209  * @return float
2210  */
2211 function get_user_timezone_offset($tz = 99) {
2213     global $USER, $CFG;
2215     $tz = get_user_timezone($tz);
2217     if (is_float($tz)) {
2218         return $tz;
2219     } else {
2220         $tzrecord = get_timezone_record($tz);
2221         if (empty($tzrecord)) {
2222             return 99.0;
2223         }
2224         return (float)$tzrecord->gmtoff / HOURMINS;
2225     }
2228 /**
2229  * Returns an int which represents the systems's timezone difference from GMT in seconds
2230  *
2231  * @package core
2232  * @category time
2233  * @param float|int|string $tz timezone for which offset is required.
2234  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2235  * @return int|bool if found, false is timezone 99 or error
2236  */
2237 function get_timezone_offset($tz) {
2238     global $CFG;
2240     if ($tz == 99) {
2241         return false;
2242     }
2244     if (is_numeric($tz)) {
2245         return intval($tz * 60*60);
2246     }
2248     if (!$tzrecord = get_timezone_record($tz)) {
2249         return false;
2250     }
2251     return intval($tzrecord->gmtoff * 60);
2254 /**
2255  * Returns a float or a string which denotes the user's timezone
2256  * 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)
2257  * means that for this timezone there are also DST rules to be taken into account
2258  * Checks various settings and picks the most dominant of those which have a value
2259  *
2260  * @package core
2261  * @category time
2262  * @param float|int|string $tz timezone to calculate GMT time offset before
2263  *        calculating user timezone, 99 is default user timezone
2264  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2265  * @return float|string
2266  */
2267 function get_user_timezone($tz = 99) {
2268     global $USER, $CFG;
2270     $timezones = array(
2271         $tz,
2272         isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2273         isset($USER->timezone) ? $USER->timezone : 99,
2274         isset($CFG->timezone) ? $CFG->timezone : 99,
2275         );
2277     $tz = 99;
2279     while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
2280         $tz = $next['value'];
2281     }
2283     return is_numeric($tz) ? (float) $tz : $tz;
2286 /**
2287  * Returns cached timezone record for given $timezonename
2288  *
2289  * @package core
2290  * @param string $timezonename name of the timezone
2291  * @return stdClass|bool timezonerecord or false
2292  */
2293 function get_timezone_record($timezonename) {
2294     global $CFG, $DB;
2295     static $cache = NULL;
2297     if ($cache === NULL) {
2298         $cache = array();
2299     }
2301     if (isset($cache[$timezonename])) {
2302         return $cache[$timezonename];
2303     }
2305     return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2306                                                         WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2309 /**
2310  * Build and store the users Daylight Saving Time (DST) table
2311  *
2312  * @package core
2313  * @param int $from_year Start year for the table, defaults to 1971
2314  * @param int $to_year End year for the table, defaults to 2035
2315  * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
2316  * @return bool
2317  */
2318 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2319     global $CFG, $SESSION, $DB;
2321     $usertz = get_user_timezone($strtimezone);
2323     if (is_float($usertz)) {
2324         // Trivial timezone, no DST
2325         return false;
2326     }
2328     if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2329         // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2330         unset($SESSION->dst_offsets);
2331         unset($SESSION->dst_range);
2332     }
2334     if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2335         // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2336         // This will be the return path most of the time, pretty light computationally
2337         return true;
2338     }
2340     // Reaching here means we either need to extend our table or create it from scratch
2342     // Remember which TZ we calculated these changes for
2343     $SESSION->dst_offsettz = $usertz;
2345     if(empty($SESSION->dst_offsets)) {
2346         // If we 're creating from scratch, put the two guard elements in there
2347         $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2348     }
2349     if(empty($SESSION->dst_range)) {
2350         // If creating from scratch
2351         $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2352         $to   = min((empty($to_year)   ? intval(date('Y')) + 3 : $to_year),   2035);
2354         // Fill in the array with the extra years we need to process
2355         $yearstoprocess = array();
2356         for($i = $from; $i <= $to; ++$i) {
2357             $yearstoprocess[] = $i;
2358         }
2360         // Take note of which years we have processed for future calls
2361         $SESSION->dst_range = array($from, $to);
2362     }
2363     else {
2364         // If needing to extend the table, do the same
2365         $yearstoprocess = array();
2367         $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2368         $to   = min((empty($to_year)   ? $SESSION->dst_range[1] : $to_year),   2035);
2370         if($from < $SESSION->dst_range[0]) {
2371             // Take note of which years we need to process and then note that we have processed them for future calls
2372             for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2373                 $yearstoprocess[] = $i;
2374             }
2375             $SESSION->dst_range[0] = $from;
2376         }
2377         if($to > $SESSION->dst_range[1]) {
2378             // Take note of which years we need to process and then note that we have processed them for future calls
2379             for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2380                 $yearstoprocess[] = $i;
2381             }
2382             $SESSION->dst_range[1] = $to;
2383         }
2384     }
2386     if(empty($yearstoprocess)) {
2387         // This means that there was a call requesting a SMALLER range than we have already calculated
2388         return true;
2389     }
2391     // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2392     // Also, the array is sorted in descending timestamp order!
2394     // Get DB data
2396     static $presets_cache = array();
2397     if (!isset($presets_cache[$usertz])) {
2398         $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');
2399     }
2400     if(empty($presets_cache[$usertz])) {
2401         return false;
2402     }
2404     // Remove ending guard (first element of the array)
2405     reset($SESSION->dst_offsets);
2406     unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2408     // Add all required change timestamps
2409     foreach($yearstoprocess as $y) {
2410         // Find the record which is in effect for the year $y
2411         foreach($presets_cache[$usertz] as $year => $preset) {
2412             if($year <= $y) {
2413                 break;
2414             }
2415         }
2417         $changes = dst_changes_for_year($y, $preset);
2419         if($changes === NULL) {
2420             continue;
2421         }
2422         if($changes['dst'] != 0) {
2423             $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2424         }
2425         if($changes['std'] != 0) {
2426             $SESSION->dst_offsets[$changes['std']] = 0;
2427         }
2428     }
2430     // Put in a guard element at the top
2431     $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2432     $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2434     // Sort again
2435     krsort($SESSION->dst_offsets);
2437     return true;
2440 /**
2441  * Calculates the required DST change and returns a Timestamp Array
2442  *
2443  * @package core
2444  * @category time
2445  * @uses HOURSECS
2446  * @uses MINSECS
2447  * @param int|string $year Int or String Year to focus on
2448  * @param object $timezone Instatiated Timezone object
2449  * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
2450  */
2451 function dst_changes_for_year($year, $timezone) {
2453     if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2454         return NULL;
2455     }
2457     $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2458     $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2460     list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2461     list($std_hour, $std_min) = explode(':', $timezone->std_time);
2463     $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2464     $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2466     // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2467     // This has the advantage of being able to have negative values for hour, i.e. for timezones
2468     // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2470     $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2471     $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2473     return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2476 /**
2477  * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2478  * - Note: Daylight saving only works for string timezones and not for float.
2479  *
2480  * @package core
2481  * @category time
2482  * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2483  * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2484  *        then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2485  * @return int
2486  */
2487 function dst_offset_on($time, $strtimezone = NULL) {
2488     global $SESSION;
2490     if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2491         return 0;
2492     }
2494     reset($SESSION->dst_offsets);
2495     while(list($from, $offset) = each($SESSION->dst_offsets)) {
2496         if($from <= $time) {
2497             break;
2498         }
2499     }
2501     // This is the normal return path
2502     if($offset !== NULL) {
2503         return $offset;
2504     }
2506     // Reaching this point means we haven't calculated far enough, do it now:
2507     // Calculate extra DST changes if needed and recurse. The recursion always
2508     // moves toward the stopping condition, so will always end.
2510     if($from == 0) {
2511         // We need a year smaller than $SESSION->dst_range[0]
2512         if($SESSION->dst_range[0] == 1971) {
2513             return 0;
2514         }
2515         calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2516         return dst_offset_on($time, $strtimezone);
2517     }
2518     else {
2519         // We need a year larger than $SESSION->dst_range[1]
2520         if($SESSION->dst_range[1] == 2035) {
2521             return 0;
2522         }
2523         calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2524         return dst_offset_on($time, $strtimezone);
2525     }
2528 /**
2529  * Calculates when the day appears in specific month
2530  *
2531  * @package core
2532  * @category time
2533  * @param int $startday starting day of the month
2534  * @param int $weekday The day when week starts (normally taken from user preferences)
2535  * @param int $month The month whose day is sought
2536  * @param int $year The year of the month whose day is sought
2537  * @return int
2538  */
2539 function find_day_in_month($startday, $weekday, $month, $year) {
2541     $daysinmonth = days_in_month($month, $year);
2543     if($weekday == -1) {
2544         // Don't care about weekday, so return:
2545         //    abs($startday) if $startday != -1
2546         //    $daysinmonth otherwise
2547         return ($startday == -1) ? $daysinmonth : abs($startday);
2548     }
2550     // From now on we 're looking for a specific weekday
2552     // Give "end of month" its actual value, since we know it
2553     if($startday == -1) {
2554         $startday = -1 * $daysinmonth;
2555     }
2557     // Starting from day $startday, the sign is the direction
2559     if($startday < 1) {
2561         $startday = abs($startday);
2562         $lastmonthweekday  = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2564         // This is the last such weekday of the month
2565         $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2566         if($lastinmonth > $daysinmonth) {
2567             $lastinmonth -= 7;
2568         }
2570         // Find the first such weekday <= $startday
2571         while($lastinmonth > $startday) {
2572             $lastinmonth -= 7;
2573         }
2575         return $lastinmonth;
2577     }
2578     else {
2580         $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2582         $diff = $weekday - $indexweekday;
2583         if($diff < 0) {
2584             $diff += 7;
2585         }
2587         // This is the first such weekday of the month equal to or after $startday
2588         $firstfromindex = $startday + $diff;
2590         return $firstfromindex;
2592     }
2595 /**
2596  * Calculate the number of days in a given month
2597  *
2598  * @package core
2599  * @category time
2600  * @param int $month The month whose day count is sought
2601  * @param int $year The year of the month whose day count is sought
2602  * @return int
2603  */
2604 function days_in_month($month, $year) {
2605    return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2608 /**
2609  * Calculate the position in the week of a specific calendar day
2610  *
2611  * @package core
2612  * @category time
2613  * @param int $day The day of the date whose position in the week is sought
2614  * @param int $month The month of the date whose position in the week is sought
2615  * @param int $year The year of the date whose position in the week is sought
2616  * @return int
2617  */
2618 function dayofweek($day, $month, $year) {
2619     // I wonder if this is any different from
2620     // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2621     return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2624 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2626 /**
2627  * Returns full login url.
2628  *
2629  * @return string login url
2630  */
2631 function get_login_url() {
2632     global $CFG;
2634     $url = "$CFG->wwwroot/login/index.php";
2636     if (!empty($CFG->loginhttps)) {
2637         $url = str_replace('http:', 'https:', $url);
2638     }
2640     return $url;
2643 /**
2644  * This function checks that the current user is logged in and has the
2645  * required privileges
2646  *
2647  * This function checks that the current user is logged in, and optionally
2648  * whether they are allowed to be in a particular course and view a particular
2649  * course module.
2650  * If they are not logged in, then it redirects them to the site login unless
2651  * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2652  * case they are automatically logged in as guests.
2653  * If $courseid is given and the user is not enrolled in that course then the
2654  * user is redirected to the course enrolment page.
2655  * If $cm is given and the course module is hidden and the user is not a teacher
2656  * in the course then the user is redirected to the course home page.
2657  *
2658  * When $cm parameter specified, this function sets page layout to 'module'.
2659  * You need to change it manually later if some other layout needed.
2660  *
2661  * @package    core_access
2662  * @category   access
2663  *
2664  * @param mixed $courseorid id of the course or course object
2665  * @param bool $autologinguest default true
2666  * @param object $cm course module object
2667  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2668  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2669  *             in order to keep redirects working properly. MDL-14495
2670  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2671  * @return mixed Void, exit, and die depending on path
2672  */
2673 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2674     global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2676     // setup global $COURSE, themes, language and locale
2677     if (!empty($courseorid)) {
2678         if (is_object($courseorid)) {
2679             $course = $courseorid;
2680         } else if ($courseorid == SITEID) {
2681             $course = clone($SITE);
2682         } else {
2683             $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2684         }
2685         if ($cm) {
2686             if ($cm->course != $course->id) {
2687                 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2688             }
2689             // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2690             if (!($cm instanceof cm_info)) {
2691                 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2692                 // db queries so this is not really a performance concern, however it is obviously
2693                 // better if you use get_fast_modinfo to get the cm before calling this.
2694                 $modinfo = get_fast_modinfo($course);
2695                 $cm = $modinfo->get_cm($cm->id);
2696             }
2697             $PAGE->set_cm($cm, $course); // set's up global $COURSE
2698             $PAGE->set_pagelayout('incourse');
2699         } else {
2700             $PAGE->set_course($course); // set's up global $COURSE
2701         }
2702     } else {
2703         // do not touch global $COURSE via $PAGE->set_course(),
2704         // the reasons is we need to be able to call require_login() at any time!!
2705         $course = $SITE;
2706         if ($cm) {
2707             throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2708         }
2709     }
2711     // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2712     // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2713     // risk leading the user back to the AJAX request URL.
2714     if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2715         $setwantsurltome = false;
2716     }
2718     // If the user is not even logged in yet then make sure they are
2719     if (!isloggedin()) {
2720         if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2721             if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2722                 // misconfigured site guest, just redirect to login page
2723                 redirect(get_login_url());
2724                 exit; // never reached
2725             }
2726             $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2727             complete_user_login($guest);
2728             $USER->autologinguest = true;
2729             $SESSION->lang = $lang;
2730         } else {
2731             //NOTE: $USER->site check was obsoleted by session test cookie,
2732             //      $USER->confirmed test is in login/index.php
2733             if ($preventredirect) {
2734                 throw new require_login_exception('You are not logged in');
2735             }
2737             if ($setwantsurltome) {
2738                 $SESSION->wantsurl = qualified_me();
2739             }
2740             if (!empty($_SERVER['HTTP_REFERER'])) {
2741                 $SESSION->fromurl  = $_SERVER['HTTP_REFERER'];
2742             }
2743             redirect(get_login_url());
2744             exit; // never reached
2745         }
2746     }
2748     // loginas as redirection if needed
2749     if ($course->id != SITEID and session_is_loggedinas()) {
2750         if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2751             if ($USER->loginascontext->instanceid != $course->id) {
2752                 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2753             }
2754         }
2755     }
2757     // check whether the user should be changing password (but only if it is REALLY them)
2758     if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2759         $userauth = get_auth_plugin($USER->auth);
2760         if ($userauth->can_change_password() and !$preventredirect) {
2761             if ($setwantsurltome) {
2762                 $SESSION->wantsurl = qualified_me();
2763             }
2764             if ($changeurl = $userauth->change_password_url()) {
2765                 //use plugin custom url
2766                 redirect($changeurl);
2767             } else {
2768                 //use moodle internal method
2769                 if (empty($CFG->loginhttps)) {
2770                     redirect($CFG->wwwroot .'/login/change_password.php');
2771                 } else {
2772                     $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2773                     redirect($wwwroot .'/login/change_password.php');
2774                 }
2775             }
2776         } else {
2777             print_error('nopasswordchangeforced', 'auth');
2778         }
2779     }
2781     // Check that the user account is properly set up
2782     if (user_not_fully_set_up($USER)) {
2783         if ($preventredirect) {
2784             throw new require_login_exception('User not fully set-up');
2785         }
2786         if ($setwantsurltome) {
2787             $SESSION->wantsurl = qualified_me();
2788         }
2789         redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2790     }
2792     // Make sure the USER has a sesskey set up. Used for CSRF protection.
2793     sesskey();
2795     // Do not bother admins with any formalities
2796     if (is_siteadmin()) {
2797         //set accesstime or the user will appear offline which messes up messaging
2798         user_accesstime_log($course->id);
2799         return;
2800     }
2802     // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2803     if (!$USER->policyagreed and !is_siteadmin()) {
2804         if (!empty($CFG->sitepolicy) and !isguestuser()) {
2805             if ($preventredirect) {
2806                 throw new require_login_exception('Policy not agreed');
2807             }
2808             if ($setwantsurltome) {
2809                 $SESSION->wantsurl = qualified_me();
2810             }
2811             redirect($CFG->wwwroot .'/user/policy.php');
2812         } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2813             if ($preventredirect) {
2814                 throw new require_login_exception('Policy not agreed');
2815             }
2816             if ($setwantsurltome) {
2817                 $SESSION->wantsurl = qualified_me();
2818             }
2819             redirect($CFG->wwwroot .'/user/policy.php');
2820         }
2821     }
2823     // Fetch the system context, the course context, and prefetch its child contexts
2824     $sysctx = get_context_instance(CONTEXT_SYSTEM);
2825     $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2826     if ($cm) {
2827         $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2828     } else {
2829         $cmcontext = null;
2830     }
2832     // If the site is currently under maintenance, then print a message
2833     if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2834         if ($preventredirect) {
2835             throw new require_login_exception('Maintenance in progress');
2836         }
2838         print_maintenance_message();
2839     }
2841     // make sure the course itself is not hidden
2842     if ($course->id == SITEID) {
2843         // frontpage can not be hidden
2844     } else {
2845         if (is_role_switched($course->id)) {
2846             // when switching roles ignore the hidden flag - user had to be in course to do the switch
2847         } else {
2848             if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2849                 // originally there was also test of parent category visibility,
2850                 // BUT is was very slow in complex queries involving "my courses"
2851                 // now it is also possible to simply hide all courses user is not enrolled in :-)
2852                 if ($preventredirect) {
2853                     throw new require_login_exception('Course is hidden');
2854                 }
2855                 // We need to override the navigation URL as the course won't have
2856                 // been added to the navigation and thus the navigation will mess up
2857                 // when trying to find it.
2858                 navigation_node::override_active_url(new moodle_url('/'));
2859                 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2860             }
2861         }
2862     }
2864     // is the user enrolled?
2865     if ($course->id == SITEID) {
2866         // everybody is enrolled on the frontpage
2868     } else {
2869         if (session_is_loggedinas()) {
2870             // Make sure the REAL person can access this course first
2871             $realuser = session_get_realuser();
2872             if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2873                 if ($preventredirect) {
2874                     throw new require_login_exception('Invalid course login-as access');
2875                 }
2876                 echo $OUTPUT->header();
2877                 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2878             }
2879         }
2881         $access = false;
2883         if (is_role_switched($course->id)) {
2884             // ok, user had to be inside this course before the switch
2885             $access = true;
2887         } else if (is_viewing($coursecontext, $USER)) {
2888             // ok, no need to mess with enrol
2889             $access = true;
2891         } else {
2892             if (isset($USER->enrol['enrolled'][$course->id])) {
2893                 if ($USER->enrol['enrolled'][$course->id] > time()) {
2894                     $access = true;
2895                     if (isset($USER->enrol['tempguest'][$course->id])) {
2896                         unset($USER->enrol['tempguest'][$course->id]);
2897                         remove_temp_course_roles($coursecontext);
2898                     }
2899                 } else {
2900                     //expired
2901                     unset($USER->enrol['enrolled'][$course->id]);
2902                 }
2903             }
2904             if (isset($USER->enrol['tempguest'][$course->id])) {
2905                 if ($USER->enrol['tempguest'][$course->id] == 0) {
2906                     $access = true;
2907                 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2908                     $access = true;
2909                 } else {
2910                     //expired
2911                     unset($USER->enrol['tempguest'][$course->id]);
2912                     remove_temp_course_roles($coursecontext);
2913                 }
2914             }
2916             if ($access) {
2917                 // cache ok
2918             } else {
2919                 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2920                 if ($until !== false) {
2921                     // active participants may always access, a timestamp in the future, 0 (always) or false.
2922                     if ($until == 0) {
2923                         $until = ENROL_MAX_TIMESTAMP;
2924                     }
2925                     $USER->enrol['enrolled'][$course->id] = $until;
2926                     $access = true;
2928                 } else {
2929                     $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2930                     $enrols = enrol_get_plugins(true);
2931                     // first ask all enabled enrol instances in course if they want to auto enrol user
2932                     foreach($instances as $instance) {
2933                         if (!isset($enrols[$instance->enrol])) {
2934                             continue;
2935                         }
2936                         // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2937                         $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2938                         if ($until !== false) {
2939                             if ($until == 0) {
2940                                 $until = ENROL_MAX_TIMESTAMP;
2941                             }
2942                             $USER->enrol['enrolled'][$course->id] = $until;
2943                             $access = true;
2944                             break;
2945                         }
2946                     }
2947                     // if not enrolled yet try to gain temporary guest access
2948                     if (!$access) {
2949                         foreach($instances as $instance) {
2950                             if (!isset($enrols[$instance->enrol])) {
2951                                 continue;
2952                             }
2953                             // Get a duration for the guest access, a timestamp in the future or false.
2954                             $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2955                             if ($until !== false and $until > time()) {
2956                                 $USER->enrol['tempguest'][$course->id] = $until;
2957                                 $access = true;
2958                                 break;
2959                             }
2960                         }
2961                     }
2962                 }
2963             }
2964         }
2966         if (!$access) {
2967             if ($preventredirect) {
2968                 throw new require_login_exception('Not enrolled');
2969             }
2970             if ($setwantsurltome) {
2971                 $SESSION->wantsurl = qualified_me();
2972             }
2973             redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2974         }
2975     }
2977     // Check visibility of activity to current user; includes visible flag, groupmembersonly,
2978     // conditional availability, etc
2979     if ($cm && !$cm->uservisible) {
2980         if ($preventredirect) {
2981             throw new require_login_exception('Activity is hidden');
2982         }
2983         redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2984     }
2986     // Finally access granted, update lastaccess times
2987     user_accesstime_log($course->id);
2991 /**
2992  * This function just makes sure a user is logged out.
2993  *
2994  * @package    core_access
2995  */
2996 function require_logout() {
2997     global $USER;
2999     $params = $USER;
3001     if (isloggedin()) {
3002         add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
3004         $authsequence = get_enabled_auth_plugins(); // auths, in sequence
3005         foreach($authsequence as $authname) {
3006             $authplugin = get_auth_plugin($authname);
3007             $authplugin->prelogout_hook();
3008         }
3009     }
3011     events_trigger('user_logout', $params);
3012     session_get_instance()->terminate_current();
3013     unset($params);
3016 /**
3017  * Weaker version of require_login()
3018  *
3019  * This is a weaker version of {@link require_login()} which only requires login
3020  * when called from within a course rather than the site page, unless
3021  * the forcelogin option is turned on.
3022  * @see require_login()
3023  *
3024  * @package    core_access
3025  * @category   access
3026  *
3027  * @param mixed $courseorid The course object or id in question
3028  * @param bool $autologinguest Allow autologin guests if that is wanted
3029  * @param object $cm Course activity module if known
3030  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3031  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3032  *             in order to keep redirects working properly. MDL-14495
3033  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3034  * @return void
3035  */
3036 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
3037     global $CFG, $PAGE, $SITE;
3038     $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3039           or (!is_object($courseorid) and $courseorid == SITEID);
3040     if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3041         // note: nearly all pages call get_fast_modinfo anyway and it does not make any
3042         // db queries so this is not really a performance concern, however it is obviously
3043         // better if you use get_fast_modinfo to get the cm before calling this.
3044         if (is_object($courseorid)) {
3045             $course = $courseorid;
3046         } else {
3047             $course = clone($SITE);
3048         }
3049         $modinfo = get_fast_modinfo($course);
3050         $cm = $modinfo->get_cm($cm->id);
3051     }
3052     if (!empty($CFG->forcelogin)) {
3053         // login required for both SITE and courses
3054         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3056     } else if ($issite && !empty($cm) and !$cm->uservisible) {
3057         // always login for hidden activities
3058         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3060     } else if ($issite) {
3061               //login for SITE not required
3062         if ($cm and empty($cm->visible)) {
3063             // hidden activities are not accessible without login
3064             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3065         } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3066             // not-logged-in users do not have any group membership
3067             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3068         } else {
3069             // We still need to instatiate PAGE vars properly so that things
3070             // that rely on it like navigation function correctly.
3071             if (!empty($courseorid)) {
3072                 if (is_object($courseorid)) {
3073                     $course = $courseorid;
3074                 } else {
3075                     $course = clone($SITE);
3076                 }
3077                 if ($cm) {
3078                     if ($cm->course != $course->id) {
3079                         throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3080                     }
3081                     $PAGE->set_cm($cm, $course);
3082                     $PAGE->set_pagelayout('incourse');
3083                 } else {
3084                     $PAGE->set_course($course);
3085                 }
3086             } else {
3087                 // If $PAGE->course, and hence $PAGE->context, have not already been set
3088                 // up properly, set them up now.
3089                 $PAGE->set_course($PAGE->course);
3090             }
3091             //TODO: verify conditional activities here
3092             user_accesstime_log(SITEID);
3093             return;
3094         }
3096     } else {
3097         // course login always required
3098         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3099     }
3102 /**
3103  * Require key login. Function terminates with error if key not found or incorrect.
3104  *
3105  * @global object
3106  * @global object
3107  * @global object
3108  * @global object
3109  * @uses NO_MOODLE_COOKIES
3110  * @uses PARAM_ALPHANUM
3111  * @param string $script unique script identifier
3112  * @param int $instance optional instance id
3113  * @return int Instance ID
3114  */
3115 function require_user_key_login($script, $instance=null) {
3116     global $USER, $SESSION, $CFG, $DB;
3118     if (!NO_MOODLE_COOKIES) {
3119         print_error('sessioncookiesdisable');
3120     }
3122 /// extra safety
3123     @session_write_close();
3125     $keyvalue = required_param('key', PARAM_ALPHANUM);
3127     if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3128         print_error('invalidkey');
3129     }
3131     if (!empty($key->validuntil) and $key->validuntil < time()) {
3132         print_error('expiredkey');
3133     }
3135     if ($key->iprestriction) {
3136         $remoteaddr = getremoteaddr(null);
3137         if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3138             print_error('ipmismatch');
3139         }
3140     }
3142     if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
3143         print_error('invaliduserid');
3144     }
3146 /// emulate normal session
3147     enrol_check_plugins($user);
3148     session_set_user($user);
3150 /// note we are not using normal login
3151     if (!defined('USER_KEY_LOGIN')) {
3152         define('USER_KEY_LOGIN', true);
3153     }
3155 /// return instance id - it might be empty
3156     return $key->instance;
3159 /**
3160  * Creates a new private user access key.
3161  *
3162  * @global object
3163  * @param string $script unique target identifier
3164  * @param int $userid
3165  * @param int $instance optional instance id
3166  * @param string $iprestriction optional ip restricted access
3167  * @param timestamp $validuntil key valid only until given data
3168  * @return string access key value
3169  */
3170 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3171     global $DB;
3173     $key = new stdClass();
3174     $key->script        = $script;
3175     $key->userid        = $userid;
3176     $key->instance      = $instance;
3177     $key->iprestriction = $iprestriction;
3178     $key->validuntil    = $validuntil;
3179     $key->timecreated   = time();
3181     $key->value         = md5($userid.'_'.time().random_string(40)); // something long and unique
3182     while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3183         // must be unique
3184         $key->value     = md5($userid.'_'.time().random_string(40));
3185     }
3186     $DB->insert_record('user_private_key', $key);
3187     return $key->value;
3190 /**
3191  * Delete the user's new private user access keys for a particular script.
3192  *
3193  * @global object
3194  * @param string $script unique target identifier
3195  * @param int $userid
3196  * @return void
3197  */
3198 function delete_user_key($script,$userid) {
3199     global $DB;
3200     $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3203 /**
3204  * Gets a private user access key (and creates one if one doesn't exist).
3205  *
3206  * @global object
3207  * @param string $script unique target identifier
3208  * @param int $userid
3209  * @param int $instance optional instance id
3210  * @param string $iprestriction optional ip restricted access
3211  * @param timestamp $validuntil key valid only until given data
3212  * @return string access key value
3213  */
3214 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3215     global $DB;
3217     if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3218                                                          'instance'=>$instance, 'iprestriction'=>$iprestriction,
3219                                                          'validuntil'=>$validuntil))) {
3220         return $key->value;
3221     } else {
3222         return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3223     }
3227 /**
3228  * Modify the user table by setting the currently logged in user's
3229  * last login to now.
3230  *
3231  * @global object
3232  * @global object
3233  * @return bool Always returns true
3234  */
3235 function update_user_login_times() {
3236     global $USER, $DB;
3238     $user = new stdClass();
3239     $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3240     $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
3242     $user->id = $USER->id;
3244     $DB->update_record('user', $user);
3245     return true;
3248 /**
3249  * Determines if a user has completed setting up their account.
3250  *
3251  * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3252  * @return bool
3253  */
3254 function user_not_fully_set_up($user) {
3255     if (isguestuser($user)) {
3256         return false;
3257     }
3258     return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3261 /**
3262  * Check whether the user has exceeded the bounce threshold
3263  *
3264  * @global object
3265  * @global object
3266  * @param user $user A {@link $USER} object
3267  * @return bool true=>User has exceeded bounce threshold
3268  */
3269 function over_bounce_threshold($user) {
3270     global $CFG, $DB;
3272     if (empty($CFG->handlebounces)) {
3273         return false;
3274     }
3276     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3277         return false;
3278     }
3280     // set sensible defaults
3281     if (empty($CFG->minbounces)) {
3282         $CFG->minbounces = 10;
3283     }
3284     if (empty($CFG->bounceratio)) {
3285         $CFG->bounceratio = .20;
3286     }
3287     $bouncecount = 0;
3288     $sendcount = 0;
3289     if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3290         $bouncecount = $bounce->value;
3291     }
3292     if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3293         $sendcount = $send->value;
3294     }
3295     return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3298 /**
3299  * Used to increment or reset email sent count
3300  *
3301  * @global object
3302  * @param user $user object containing an id
3303  * @param bool $reset will reset the count to 0
3304  * @return void
3305  */
3306 function set_send_count($user,$reset=false) {
3307     global $DB;
3309     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3310         return;
3311     }
3313     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3314         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3315         $DB->update_record('user_preferences', $pref);
3316     }
3317     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3318         // make a new one
3319         $pref = new stdClass();
3320         $pref->name   = 'email_send_count';
3321         $pref->value  = 1;
3322         $pref->userid = $user->id;
3323         $DB->insert_record('user_preferences', $pref, false);
3324     }
3327 /**
3328  * Increment or reset user's email bounce count
3329  *
3330  * @global object
3331  * @param user $user object containing an id
3332  * @param bool $reset will reset the count to 0
3333  */
3334 function set_bounce_count($user,$reset=false) {
3335     global $DB;
3337     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3338         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3339         $DB->update_record('user_preferences', $pref);
3340     }
3341     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3342         // make a new one
3343         $pref = new stdClass();
3344         $pref->name   = 'email_bounce_count';
3345         $pref->value  = 1;
3346         $pref->userid = $user->id;
3347         $DB->insert_record('user_preferences', $pref, false);
3348     }
3351 /**
3352  * Keeps track of login attempts
3353  *
3354  * @global object
3355  */
3356 function update_login_count() {
3357     global $SESSION;
3359     $max_logins = 10;
3361     if (empty($SESSION->logincount)) {
3362         $SESSION->logincount = 1;
3363     } else {
3364         $SESSION->logincount++;
3365     }
3367     if ($SESSION->logincount > $max_logins) {
3368         unset($SESSION->wantsurl);
3369         print_error('errortoomanylogins');
3370     }
3373 /**
3374  * Resets login attempts
3375  *
3376  * @global object
3377  */
3378 function reset_login_count() {
3379     global $SESSION;
3381     $SESSION->logincount = 0;
3384 /**
3385  * Determines if the currently logged in user is in editing mode.
3386  * Note: originally this function had $userid parameter - it was not usable anyway
3387  *
3388  * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3389  * @todo Deprecated function remove when ready
3390  *
3391  * @global object
3392  * @uses DEBUG_DEVELOPER
3393  * @return bool
3394  */
3395 function isediting() {
3396     global $PAGE;
3397     debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3398     return $PAGE->user_is_editing();
3401 /**
3402  * Determines if the logged in user is currently moving an activity
3403  *
3404  * @global object
3405  * @param int $courseid The id of the course being tested
3406  * @return bool
3407  */
3408 function ismoving($courseid) {
3409     global $USER;
3411     if (!empty($USER->activitycopy)) {
3412         return ($USER->activitycopycourse == $courseid);
3413     }
3414     return false;
3417 /**
3418  * Returns a persons full name
3419  *
3420  * Given an object containing firstname and lastname
3421  * values, this function returns a string with the
3422  * full name of the person.
3423  * The result may depend on system settings
3424  * or language.  'override' will force both names
3425  * to be used even if system settings specify one.
3426  *
3427  * @global object
3428  * @global object
3429  * @param object $user A {@link $USER} object to get full name of
3430  * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3431  * @return string
3432  */
3433 function fullname($user, $override=false) {
3434     global $CFG, $SESSION;
3436     if (!isset($user->firstname) and !isset($user->lastname)) {
3437         return '';
3438     }
3440     if (!$override) {
3441         if (!empty($CFG->forcefirstname)) {
3442             $user->firstname = $CFG->forcefirstname;
3443         }
3444         if (!empty($CFG->forcelastname)) {
3445             $user->lastname = $CFG->forcelastname;
3446         }
3447     }
3449     if (!empty($SESSION->fullnamedisplay)) {
3450         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3451     }
3453     if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3454         return $user->firstname .' '. $user->lastname;
3456     } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3457         return $user->lastname .' '. $user->firstname;
3459     } else if ($CFG->fullnamedisplay == 'firstname') {
3460         if ($override) {
3461             return get_string('fullnamedisplay', '', $user);
3462         } else {
3463             return $user->firstname;
3464         }
3465     }
3467     return get_string('fullnamedisplay', '', $user);
3470 /**
3471  * Checks if current user is shown any extra fields when listing users.
3472  * @param object $context Context
3473  * @param array $already Array of fields that we're going to show anyway
3474  *   so don't bother listing them
3475  * @return array Array of field names from user table, not including anything
3476  *   listed in $already
3477  */
3478 function get_extra_user_fields($context, $already = array()) {
3479     global $CFG;
3481     // Only users with permission get the extra fields
3482     if (!has_capability('moodle/site:viewuseridentity', $context)) {
3483         return array();
3484     }
3486     // Split showuseridentity on comma
3487     if (empty($CFG->showuseridentity)) {
3488         // Explode gives wrong result with empty string
3489         $extra = array();
3490     } else {
3491         $extra =  explode(',', $CFG->showuseridentity);
3492     }
3493     $renumber = false;
3494     foreach ($extra as $key => $field) {
3495         if (in_array($field, $already)) {
3496             unset($extra[$key]);
3497             $renumber = true;
3498         }
3499     }
3500     if ($renumber) {
3501         // For consistency, if entries are removed from array, renumber it
3502         // so they are numbered as you would expect
3503         $extra = array_merge($extra);
3504     }
3505     return $extra;
3508 /**
3509  * If the current user is to be shown extra user fields when listing or
3510  * selecting users, returns a string suitable for including in an SQL select
3511  * clause to retrieve those fields.
3512  * @param object $context Context
3513  * @param string $alias Alias of user table, e.g. 'u' (default none)
3514  * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3515  * @param array $already Array of fields that we're going to include anyway
3516  *   so don't list them (default none)
3517  * @return string Partial SQL select clause, beginning with comma, for example
3518  *   ',u.idnumber,u.department' unless it is blank
3519  */
3520 function get_extra_user_fields_sql($context, $alias='', $prefix='',
3521         $already = array()) {
3522     $fields = get_extra_user_fields($context, $already);
3523     $result = '';
3524     // Add punctuation for alias
3525     if ($alias !== '') {
3526         $alias .= '.';
3527     }
3528     foreach ($fields as $field) {
3529         $result .= ', ' . $alias . $field;
3530         if ($prefix) {
3531             $result .= ' AS ' . $prefix . $field;
3532         }
3533     }
3534     return $result;
3537 /**
3538  * Returns the display name of a field in the user table. Works for most fields
3539  * that are commonly displayed to users.
3540  * @param string $field Field name, e.g. 'phone1'
3541  * @return string Text description taken from language file, e.g. 'Phone number'
3542  */
3543 function get_user_field_name($field) {
3544     // Some fields have language strings which are not the same as field name
3545     switch ($field) {
3546         case 'phone1' : return get_string('phone');
3547     }
3548     // Otherwise just use the same lang string
3549     return get_string($field);
3552 /**
3553  * Returns whether a given authentication plugin exists.
3554  *
3555  * @global object
3556  * @param string $auth Form of authentication to check for. Defaults to the
3557  *        global setting in {@link $CFG}.
3558  * @return boolean Whether the plugin is available.
3559  */
3560 function exists_auth_plugin($auth) {
3561     global $CFG;
3563     if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3564         return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3565     }
3566     return false;
3569 /**
3570  * Checks if a given plugin is in the list of enabled authentication plugins.
3571  *
3572  * @param string $auth Authentication plugin.
3573  * @return boolean Whether the plugin is enabled.
3574  */
3575 function is_enabled_auth($auth) {
3576     if (empty($auth)) {
3577         return false;
3578     }
3580     $enabled = get_enabled_auth_plugins();
3582     return in_array($auth, $enabled);
3585 /**
3586  * Returns an authentication plugin instance.
3587  *
3588  * @global object
3589  * @param string $auth name of authentication plugin
3590  * @return auth_plugin_base An instance of the required authentication plugin.
3591  */
3592 function get_auth_plugin($auth) {
3593     global $CFG;
3595     // check the plugin exists first
3596     if (! exists_auth_plugin($auth)) {
3597         print_error('authpluginnotfound', 'debug', '', $auth);
3598     }
3600     // return auth plugin instance
3601     require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3602     $class = "auth_plugin_$auth";
3603     return new $class;
3606 /**
3607  * Returns array of active auth plugins.
3608  *
3609  * @param bool $fix fix $CFG->auth if needed
3610  * @return array
3611  */
3612 function get_enabled_auth_plugins($fix=false) {
3613     global $CFG;
3615     $default = array('manual', 'nologin');
3617     if (empty($CFG->auth)) {
3618         $auths = array();
3619     } else {
3620         $auths = explode(',', $CFG->auth);
3621     }
3623     if ($fix) {
3624         $auths = array_unique($auths);
3625         foreach($auths as $k=>$authname) {
3626             if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3627                 unset($auths[$k]);
3628             }
3629         }
3630         $newconfig = implode(',', $auths);
3631         if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3632             set_config('auth', $newconfig);
3633         }
3634     }
3636     return (array_merge($default, $auths));
3639 /**
3640  * Returns true if an internal authentication method is being used.
3641  * if method not specified then, global default is assumed
3642  *
3643  * @param string $auth Form of authentication required
3644  * @return bool
3645  */
3646 function is_internal_auth($auth) {
3647     $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3648     return $authplugin->is_internal();
3651 /**
3652  * Returns true if the user is a 'restored' one
3653  *
3654  * Used in the login process to inform the user
3655  * and allow him/her to reset the password
3656  *
3657  * @uses $CFG
3658  * @uses $DB
3659  * @param string $username username to be checked
3660  * @return bool
3661  */
3662 function is_restored_user($username) {
3663     global $CFG, $DB;
3665     return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3668 /**
3669  * Returns an array of user fields
3670  *
3671  * @return array User field/column names
3672  */
3673 function get_user_fieldnames() {
3674     global $DB;
3676     $fieldarray = $DB->get_columns('user');
3677     unset($fieldarray['id']);
3678     $fieldarray = array_keys($fieldarray);