1de567fa985a4d087cbaab6163be5a13fbb45c0e
[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  * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
137  * It does not work for languages that use , as a decimal separator.
138  * Instead, do something like
139  *     $rawvalue = required_param('name', PARAM_RAW);
140  *     // ... other code including require_login, which sets current lang ...
141  *     $realvalue = unformat_float($rawvalue);
142  *     // ... then use $realvalue
143  */
144 define('PARAM_FLOAT',  'float');
146 /**
147  * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
148  */
149 define('PARAM_HOST',     'host');
151 /**
152  * PARAM_INT - integers only, use when expecting only numbers.
153  */
154 define('PARAM_INT',      'int');
156 /**
157  * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
158  */
159 define('PARAM_LANG',  'lang');
161 /**
162  * 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!)
163  */
164 define('PARAM_LOCALURL', 'localurl');
166 /**
167  * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
168  */
169 define('PARAM_NOTAGS',   'notags');
171 /**
172  * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
173  * note: the leading slash is not removed, window drive letter is not allowed
174  */
175 define('PARAM_PATH',     'path');
177 /**
178  * PARAM_PEM - Privacy Enhanced Mail format
179  */
180 define('PARAM_PEM',      'pem');
182 /**
183  * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
184  */
185 define('PARAM_PERMISSION',   'permission');
187 /**
188  * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
189  */
190 define('PARAM_RAW', 'raw');
192 /**
193  * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
194  */
195 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
197 /**
198  * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
199  */
200 define('PARAM_SAFEDIR',  'safedir');
202 /**
203  * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
204  */
205 define('PARAM_SAFEPATH',  'safepath');
207 /**
208  * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9.  Numbers and comma only.
209  */
210 define('PARAM_SEQUENCE',  'sequence');
212 /**
213  * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
214  */
215 define('PARAM_TAG',   'tag');
217 /**
218  * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
219  */
220 define('PARAM_TAGLIST',   'taglist');
222 /**
223  * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
224  */
225 define('PARAM_TEXT',  'text');
227 /**
228  * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
229  */
230 define('PARAM_THEME',  'theme');
232 /**
233  * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
234  */
235 define('PARAM_URL',      'url');
237 /**
238  * 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!!
239  */
240 define('PARAM_USERNAME',    'username');
242 /**
243  * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
244  */
245 define('PARAM_STRINGID',    'stringid');
247 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE  /////
248 /**
249  * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
250  * It was one of the first types, that is why it is abused so much ;-)
251  * @deprecated since 2.0
252  */
253 define('PARAM_CLEAN',    'clean');
255 /**
256  * PARAM_INTEGER - deprecated alias for PARAM_INT
257  */
258 define('PARAM_INTEGER',  'int');
260 /**
261  * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
262  */
263 define('PARAM_NUMBER',  'float');
265 /**
266  * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
267  * NOTE: originally alias for PARAM_APLHA
268  */
269 define('PARAM_ACTION',   'alphanumext');
271 /**
272  * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
273  * NOTE: originally alias for PARAM_APLHA
274  */
275 define('PARAM_FORMAT',   'alphanumext');
277 /**
278  * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
279  */
280 define('PARAM_MULTILANG',  'text');
282 /**
283  * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
284  * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
285  * America/Port-au-Prince)
286  */
287 define('PARAM_TIMEZONE', 'timezone');
289 /**
290  * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
291  */
292 define('PARAM_CLEANFILE', 'file');
294 /**
295  * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
296  * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
297  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
298  * NOTE: numbers and underscores are strongly discouraged in plugin names!
299  */
300 define('PARAM_COMPONENT', 'component');
302 /**
303  * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
304  * It is usually used together with context id and component.
305  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
306  */
307 define('PARAM_AREA', 'area');
309 /**
310  * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
311  * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
312  * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
313  */
314 define('PARAM_PLUGIN', 'plugin');
317 /// Web Services ///
319 /**
320  * VALUE_REQUIRED - if the parameter is not supplied, there is an error
321  */
322 define('VALUE_REQUIRED', 1);
324 /**
325  * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
326  */
327 define('VALUE_OPTIONAL', 2);
329 /**
330  * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
331  */
332 define('VALUE_DEFAULT', 0);
334 /**
335  * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
336  */
337 define('NULL_NOT_ALLOWED', false);
339 /**
340  * NULL_ALLOWED - the parameter can be set to null in the database
341  */
342 define('NULL_ALLOWED', true);
344 /// Page types ///
345 /**
346  * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
347  */
348 define('PAGE_COURSE_VIEW', 'course-view');
350 /** Get remote addr constant */
351 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
352 /** Get remote addr constant */
353 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
355 /// Blog access level constant declaration ///
356 define ('BLOG_USER_LEVEL', 1);
357 define ('BLOG_GROUP_LEVEL', 2);
358 define ('BLOG_COURSE_LEVEL', 3);
359 define ('BLOG_SITE_LEVEL', 4);
360 define ('BLOG_GLOBAL_LEVEL', 5);
363 ///Tag constants///
364 /**
365  * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
366  * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
367  * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
368  *
369  * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
370  */
371 define('TAG_MAX_LENGTH', 50);
373 /// Password policy constants ///
374 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
375 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
376 define ('PASSWORD_DIGITS', '0123456789');
377 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
379 /// Feature constants ///
380 // Used for plugin_supports() to report features that are, or are not, supported by a module.
382 /** True if module can provide a grade */
383 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
384 /** True if module supports outcomes */
385 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
386 /** True if module supports advanced grading methods */
387 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
388 /** True if module controls the grade visibility over the gradebook */
389 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
391 /** True if module has code to track whether somebody viewed it */
392 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
393 /** True if module has custom completion rules */
394 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
396 /** True if module has no 'view' page (like label) */
397 define('FEATURE_NO_VIEW_LINK', 'viewlink');
398 /** True if module supports outcomes */
399 define('FEATURE_IDNUMBER', 'idnumber');
400 /** True if module supports groups */
401 define('FEATURE_GROUPS', 'groups');
402 /** True if module supports groupings */
403 define('FEATURE_GROUPINGS', 'groupings');
404 /** True if module supports groupmembersonly */
405 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
407 /** Type of module */
408 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
409 /** True if module supports intro editor */
410 define('FEATURE_MOD_INTRO', 'mod_intro');
411 /** True if module has default completion */
412 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
414 define('FEATURE_COMMENT', 'comment');
416 define('FEATURE_RATE', 'rate');
417 /** True if module supports backup/restore of moodle2 format */
418 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
420 /** True if module can show description on course main page */
421 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
423 /** Unspecified module archetype */
424 define('MOD_ARCHETYPE_OTHER', 0);
425 /** Resource-like type module */
426 define('MOD_ARCHETYPE_RESOURCE', 1);
427 /** Assignment module archetype */
428 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
429 /** System (not user-addable) module archetype */
430 define('MOD_ARCHETYPE_SYSTEM', 3);
432 /**
433  * Security token used for allowing access
434  * from external application such as web services.
435  * Scripts do not use any session, performance is relatively
436  * low because we need to load access info in each request.
437  * Scripts are executed in parallel.
438  */
439 define('EXTERNAL_TOKEN_PERMANENT', 0);
441 /**
442  * Security token used for allowing access
443  * of embedded applications, the code is executed in the
444  * active user session. Token is invalidated after user logs out.
445  * Scripts are executed serially - normal session locking is used.
446  */
447 define('EXTERNAL_TOKEN_EMBEDDED', 1);
449 /**
450  * The home page should be the site home
451  */
452 define('HOMEPAGE_SITE', 0);
453 /**
454  * The home page should be the users my page
455  */
456 define('HOMEPAGE_MY', 1);
457 /**
458  * The home page can be chosen by the user
459  */
460 define('HOMEPAGE_USER', 2);
462 /**
463  * Hub directory url (should be moodle.org)
464  */
465 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
468 /**
469  * Moodle.org url (should be moodle.org)
470  */
471 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
473 /**
474  * Moodle mobile app service name
475  */
476 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
478 /**
479  * Indicates the user has the capabilities required to ignore activity and course file size restrictions
480  */
481 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
483 /**
484  * Course display settings
485  */
486 define('COURSE_DISPLAY_SINGLEPAGE', 0); // display all sections on one page
487 define('COURSE_DISPLAY_MULTIPAGE', 1); // split pages into a page per section
489 /// PARAMETER HANDLING ////////////////////////////////////////////////////
491 /**
492  * Returns a particular value for the named variable, taken from
493  * POST or GET.  If the parameter doesn't exist then an error is
494  * thrown because we require this variable.
495  *
496  * This function should be used to initialise all required values
497  * in a script that are based on parameters.  Usually it will be
498  * used like this:
499  *    $id = required_param('id', PARAM_INT);
500  *
501  * Please note the $type parameter is now required and the value can not be array.
502  *
503  * @param string $parname the name of the page parameter we want
504  * @param string $type expected type of parameter
505  * @return mixed
506  */
507 function required_param($parname, $type) {
508     if (func_num_args() != 2 or empty($parname) or empty($type)) {
509         throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
510     }
511     if (isset($_POST[$parname])) {       // POST has precedence
512         $param = $_POST[$parname];
513     } else if (isset($_GET[$parname])) {
514         $param = $_GET[$parname];
515     } else {
516         print_error('missingparam', '', '', $parname);
517     }
519     if (is_array($param)) {
520         debugging('Invalid array parameter detected in required_param(): '.$parname);
521         // TODO: switch to fatal error in Moodle 2.3
522         //print_error('missingparam', '', '', $parname);
523         return required_param_array($parname, $type);
524     }
526     return clean_param($param, $type);
529 /**
530  * Returns a particular array value for the named variable, taken from
531  * POST or GET.  If the parameter doesn't exist then an error is
532  * thrown because we require this variable.
533  *
534  * This function should be used to initialise all required values
535  * in a script that are based on parameters.  Usually it will be
536  * used like this:
537  *    $ids = required_param_array('ids', PARAM_INT);
538  *
539  *  Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
540  *
541  * @param string $parname the name of the page parameter we want
542  * @param string $type expected type of parameter
543  * @return array
544  */
545 function required_param_array($parname, $type) {
546     if (func_num_args() != 2 or empty($parname) or empty($type)) {
547         throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
548     }
549     if (isset($_POST[$parname])) {       // POST has precedence
550         $param = $_POST[$parname];
551     } else if (isset($_GET[$parname])) {
552         $param = $_GET[$parname];
553     } else {
554         print_error('missingparam', '', '', $parname);
555     }
556     if (!is_array($param)) {
557         print_error('missingparam', '', '', $parname);
558     }
560     $result = array();
561     foreach($param as $key=>$value) {
562         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
563             debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
564             continue;
565         }
566         $result[$key] = clean_param($value, $type);
567     }
569     return $result;
572 /**
573  * Returns a particular value for the named variable, taken from
574  * POST or GET, otherwise returning a given default.
575  *
576  * This function should be used to initialise all optional values
577  * in a script that are based on parameters.  Usually it will be
578  * used like this:
579  *    $name = optional_param('name', 'Fred', PARAM_TEXT);
580  *
581  * Please note the $type parameter is now required and the value can not be array.
582  *
583  * @param string $parname the name of the page parameter we want
584  * @param mixed  $default the default value to return if nothing is found
585  * @param string $type expected type of parameter
586  * @return mixed
587  */
588 function optional_param($parname, $default, $type) {
589     if (func_num_args() != 3 or empty($parname) or empty($type)) {
590         throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
591     }
592     if (!isset($default)) {
593         $default = null;
594     }
596     if (isset($_POST[$parname])) {       // POST has precedence
597         $param = $_POST[$parname];
598     } else if (isset($_GET[$parname])) {
599         $param = $_GET[$parname];
600     } else {
601         return $default;
602     }
604     if (is_array($param)) {
605         debugging('Invalid array parameter detected in required_param(): '.$parname);
606         // TODO: switch to $default in Moodle 2.3
607         //return $default;
608         return optional_param_array($parname, $default, $type);
609     }
611     return clean_param($param, $type);
614 /**
615  * Returns a particular array value for the named variable, taken from
616  * POST or GET, otherwise returning a given default.
617  *
618  * This function should be used to initialise all optional values
619  * in a script that are based on parameters.  Usually it will be
620  * used like this:
621  *    $ids = optional_param('id', array(), PARAM_INT);
622  *
623  *  Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
624  *
625  * @param string $parname the name of the page parameter we want
626  * @param mixed  $default the default value to return if nothing is found
627  * @param string $type expected type of parameter
628  * @return array
629  */
630 function optional_param_array($parname, $default, $type) {
631     if (func_num_args() != 3 or empty($parname) or empty($type)) {
632         throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
633     }
635     if (isset($_POST[$parname])) {       // POST has precedence
636         $param = $_POST[$parname];
637     } else if (isset($_GET[$parname])) {
638         $param = $_GET[$parname];
639     } else {
640         return $default;
641     }
642     if (!is_array($param)) {
643         debugging('optional_param_array() expects array parameters only: '.$parname);
644         return $default;
645     }
647     $result = array();
648     foreach($param as $key=>$value) {
649         if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
650             debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
651             continue;
652         }
653         $result[$key] = clean_param($value, $type);
654     }
656     return $result;
659 /**
660  * Strict validation of parameter values, the values are only converted
661  * to requested PHP type. Internally it is using clean_param, the values
662  * before and after cleaning must be equal - otherwise
663  * an invalid_parameter_exception is thrown.
664  * Objects and classes are not accepted.
665  *
666  * @param mixed $param
667  * @param string $type PARAM_ constant
668  * @param bool $allownull are nulls valid value?
669  * @param string $debuginfo optional debug information
670  * @return mixed the $param value converted to PHP type
671  * @throws invalid_parameter_exception if $param is not of given type
672  */
673 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
674     if (is_null($param)) {
675         if ($allownull == NULL_ALLOWED) {
676             return null;
677         } else {
678             throw new invalid_parameter_exception($debuginfo);
679         }
680     }
681     if (is_array($param) or is_object($param)) {
682         throw new invalid_parameter_exception($debuginfo);
683     }
685     $cleaned = clean_param($param, $type);
687     if ($type == PARAM_FLOAT) {
688         // Do not detect precision loss here.
689         if (is_float($param) or is_int($param)) {
690             // These always fit.
691         } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
692             throw new invalid_parameter_exception($debuginfo);
693         }
694     } else if ((string)$param !== (string)$cleaned) {
695         // conversion to string is usually lossless
696         throw new invalid_parameter_exception($debuginfo);
697     }
699     return $cleaned;
702 /**
703  * Makes sure array contains only the allowed types,
704  * this function does not validate array key names!
705  * <code>
706  * $options = clean_param($options, PARAM_INT);
707  * </code>
708  *
709  * @param array $param the variable array we are cleaning
710  * @param string $type expected format of param after cleaning.
711  * @param bool $recursive clean recursive arrays
712  * @return array
713  */
714 function clean_param_array(array $param = null, $type, $recursive = false) {
715     $param = (array)$param; // convert null to empty array
716     foreach ($param as $key => $value) {
717         if (is_array($value)) {
718             if ($recursive) {
719                 $param[$key] = clean_param_array($value, $type, true);
720             } else {
721                 throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
722             }
723         } else {
724             $param[$key] = clean_param($value, $type);
725         }
726     }
727     return $param;
730 /**
731  * Used by {@link optional_param()} and {@link required_param()} to
732  * clean the variables and/or cast to specific types, based on
733  * an options field.
734  * <code>
735  * $course->format = clean_param($course->format, PARAM_ALPHA);
736  * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
737  * </code>
738  *
739  * @param mixed $param the variable we are cleaning
740  * @param string $type expected format of param after cleaning.
741  * @return mixed
742  */
743 function clean_param($param, $type) {
745     global $CFG;
747     if (is_array($param)) {
748         throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
749     } else if (is_object($param)) {
750         if (method_exists($param, '__toString')) {
751             $param = $param->__toString();
752         } else {
753             throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
754         }
755     }
757     switch ($type) {
758         case PARAM_RAW:          // no cleaning at all
759             $param = fix_utf8($param);
760             return $param;
762         case PARAM_RAW_TRIMMED:         // no cleaning, but strip leading and trailing whitespace.
763             $param = fix_utf8($param);
764             return trim($param);
766         case PARAM_CLEAN:        // General HTML cleaning, try to use more specific type if possible
767             // this is deprecated!, please use more specific type instead
768             if (is_numeric($param)) {
769                 return $param;
770             }
771             $param = fix_utf8($param);
772             return clean_text($param);     // Sweep for scripts, etc
774         case PARAM_CLEANHTML:    // clean html fragment
775             $param = fix_utf8($param);
776             $param = clean_text($param, FORMAT_HTML);     // Sweep for scripts, etc
777             return trim($param);
779         case PARAM_INT:
780             return (int)$param;  // Convert to integer
782         case PARAM_FLOAT:
783         case PARAM_NUMBER:
784             return (float)$param;  // Convert to float
786         case PARAM_ALPHA:        // Remove everything not a-z
787             return preg_replace('/[^a-zA-Z]/i', '', $param);
789         case PARAM_ALPHAEXT:     // Remove everything not a-zA-Z_- (originally allowed "/" too)
790             return preg_replace('/[^a-zA-Z_-]/i', '', $param);
792         case PARAM_ALPHANUM:     // Remove everything not a-zA-Z0-9
793             return preg_replace('/[^A-Za-z0-9]/i', '', $param);
795         case PARAM_ALPHANUMEXT:     // Remove everything not a-zA-Z0-9_-
796             return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
798         case PARAM_SEQUENCE:     // Remove everything not 0-9,
799             return preg_replace('/[^0-9,]/i', '', $param);
801         case PARAM_BOOL:         // Convert to 1 or 0
802             $tempstr = strtolower($param);
803             if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
804                 $param = 1;
805             } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
806                 $param = 0;
807             } else {
808                 $param = empty($param) ? 0 : 1;
809             }
810             return $param;
812         case PARAM_NOTAGS:       // Strip all tags
813             $param = fix_utf8($param);
814             return strip_tags($param);
816         case PARAM_TEXT:    // leave only tags needed for multilang
817             $param = fix_utf8($param);
818             // if the multilang syntax is not correct we strip all tags
819             // because it would break xhtml strict which is required for accessibility standards
820             // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
821             do {
822                 if (strpos($param, '</lang>') !== false) {
823                     // old and future mutilang syntax
824                     $param = strip_tags($param, '<lang>');
825                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
826                         break;
827                     }
828                     $open = false;
829                     foreach ($matches[0] as $match) {
830                         if ($match === '</lang>') {
831                             if ($open) {
832                                 $open = false;
833                                 continue;
834                             } else {
835                                 break 2;
836                             }
837                         }
838                         if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
839                             break 2;
840                         } else {
841                             $open = true;
842                         }
843                     }
844                     if ($open) {
845                         break;
846                     }
847                     return $param;
849                 } else if (strpos($param, '</span>') !== false) {
850                     // current problematic multilang syntax
851                     $param = strip_tags($param, '<span>');
852                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
853                         break;
854                     }
855                     $open = false;
856                     foreach ($matches[0] as $match) {
857                         if ($match === '</span>') {
858                             if ($open) {
859                                 $open = false;
860                                 continue;
861                             } else {
862                                 break 2;
863                             }
864                         }
865                         if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
866                             break 2;
867                         } else {
868                             $open = true;
869                         }
870                     }
871                     if ($open) {
872                         break;
873                     }
874                     return $param;
875                 }
876             } while (false);
877             // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
878             return strip_tags($param);
880         case PARAM_COMPONENT:
881             // we do not want any guessing here, either the name is correct or not
882             // please note only normalised component names are accepted
883             if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
884                 return '';
885             }
886             if (strpos($param, '__') !== false) {
887                 return '';
888             }
889             if (strpos($param, 'mod_') === 0) {
890                 // module names must not contain underscores because we need to differentiate them from invalid plugin types
891                 if (substr_count($param, '_') != 1) {
892                     return '';
893                 }
894             }
895             return $param;
897         case PARAM_PLUGIN:
898         case PARAM_AREA:
899             // we do not want any guessing here, either the name is correct or not
900             if (!preg_match('/^[a-z][a-z0-9_]*[a-z0-9]$/', $param)) {
901                 return '';
902             }
903             if (strpos($param, '__') !== false) {
904                 return '';
905             }
906             return $param;
908         case PARAM_SAFEDIR:      // Remove everything not a-zA-Z0-9_-
909             return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
911         case PARAM_SAFEPATH:     // Remove everything not a-zA-Z0-9/_-
912             return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
914         case PARAM_FILE:         // Strip all suspicious characters from filename
915             $param = fix_utf8($param);
916             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
917             $param = preg_replace('~\.\.+~', '', $param);
918             if ($param === '.') {
919                 $param = '';
920             }
921             return $param;
923         case PARAM_PATH:         // Strip all suspicious characters from file path
924             $param = fix_utf8($param);
925             $param = str_replace('\\', '/', $param);
926             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
927             $param = preg_replace('~\.\.+~', '', $param);
928             $param = preg_replace('~//+~', '/', $param);
929             return preg_replace('~/(\./)+~', '/', $param);
931         case PARAM_HOST:         // allow FQDN or IPv4 dotted quad
932             $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
933             // match ipv4 dotted quad
934             if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
935                 // confirm values are ok
936                 if ( $match[0] > 255
937                      || $match[1] > 255
938                      || $match[3] > 255
939                      || $match[4] > 255 ) {
940                     // hmmm, what kind of dotted quad is this?
941                     $param = '';
942                 }
943             } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
944                        && !preg_match('/^[\.-]/',  $param) // no leading dots/hyphens
945                        && !preg_match('/[\.-]$/',  $param) // no trailing dots/hyphens
946                        ) {
947                 // all is ok - $param is respected
948             } else {
949                 // all is not ok...
950                 $param='';
951             }
952             return $param;
954         case PARAM_URL:          // allow safe ftp, http, mailto urls
955             $param = fix_utf8($param);
956             include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
957             if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
958                 // all is ok, param is respected
959             } else {
960                 $param =''; // not really ok
961             }
962             return $param;
964         case PARAM_LOCALURL:     // allow http absolute, root relative and relative URLs within wwwroot
965             $param = clean_param($param, PARAM_URL);
966             if (!empty($param)) {
967                 if (preg_match(':^/:', $param)) {
968                     // root-relative, ok!
969                 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
970                     // absolute, and matches our wwwroot
971                 } else {
972                     // relative - let's make sure there are no tricks
973                     if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
974                         // looks ok.
975                     } else {
976                         $param = '';
977                     }
978                 }
979             }
980             return $param;
982         case PARAM_PEM:
983             $param = trim($param);
984             // PEM formatted strings may contain letters/numbers and the symbols
985             // forward slash: /
986             // plus sign:     +
987             // equal sign:    =
988             // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
989             if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
990                 list($wholething, $body) = $matches;
991                 unset($wholething, $matches);
992                 $b64 = clean_param($body, PARAM_BASE64);
993                 if (!empty($b64)) {
994                     return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
995                 } else {
996                     return '';
997                 }
998             }
999             return '';
1001         case PARAM_BASE64:
1002             if (!empty($param)) {
1003                 // PEM formatted strings may contain letters/numbers and the symbols
1004                 // forward slash: /
1005                 // plus sign:     +
1006                 // equal sign:    =
1007                 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1008                     return '';
1009                 }
1010                 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1011                 // Each line of base64 encoded data must be 64 characters in
1012                 // length, except for the last line which may be less than (or
1013                 // equal to) 64 characters long.
1014                 for ($i=0, $j=count($lines); $i < $j; $i++) {
1015                     if ($i + 1 == $j) {
1016                         if (64 < strlen($lines[$i])) {
1017                             return '';
1018                         }
1019                         continue;
1020                     }
1022                     if (64 != strlen($lines[$i])) {
1023                         return '';
1024                     }
1025                 }
1026                 return implode("\n",$lines);
1027             } else {
1028                 return '';
1029             }
1031         case PARAM_TAG:
1032             $param = fix_utf8($param);
1033             // Please note it is not safe to use the tag name directly anywhere,
1034             // it must be processed with s(), urlencode() before embedding anywhere.
1035             // remove some nasties
1036             $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1037             //convert many whitespace chars into one
1038             $param = preg_replace('/\s+/', ' ', $param);
1039             $param = textlib::substr(trim($param), 0, TAG_MAX_LENGTH);
1040             return $param;
1042         case PARAM_TAGLIST:
1043             $param = fix_utf8($param);
1044             $tags = explode(',', $param);
1045             $result = array();
1046             foreach ($tags as $tag) {
1047                 $res = clean_param($tag, PARAM_TAG);
1048                 if ($res !== '') {
1049                     $result[] = $res;
1050                 }
1051             }
1052             if ($result) {
1053                 return implode(',', $result);
1054             } else {
1055                 return '';
1056             }
1058         case PARAM_CAPABILITY:
1059             if (get_capability_info($param)) {
1060                 return $param;
1061             } else {
1062                 return '';
1063             }
1065         case PARAM_PERMISSION:
1066             $param = (int)$param;
1067             if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1068                 return $param;
1069             } else {
1070                 return CAP_INHERIT;
1071             }
1073         case PARAM_AUTH:
1074             $param = clean_param($param, PARAM_PLUGIN);
1075             if (empty($param)) {
1076                 return '';
1077             } else if (exists_auth_plugin($param)) {
1078                 return $param;
1079             } else {
1080                 return '';
1081             }
1083         case PARAM_LANG:
1084             $param = clean_param($param, PARAM_SAFEDIR);
1085             if (get_string_manager()->translation_exists($param)) {
1086                 return $param;
1087             } else {
1088                 return ''; // Specified language is not installed or param malformed
1089             }
1091         case PARAM_THEME:
1092             $param = clean_param($param, PARAM_PLUGIN);
1093             if (empty($param)) {
1094                 return '';
1095             } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1096                 return $param;
1097             } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1098                 return $param;
1099             } else {
1100                 return '';  // Specified theme is not installed
1101             }
1103         case PARAM_USERNAME:
1104             $param = fix_utf8($param);
1105             $param = str_replace(" " , "", $param);
1106             $param = textlib::strtolower($param);  // Convert uppercase to lowercase MDL-16919
1107             if (empty($CFG->extendedusernamechars)) {
1108                 // regular expression, eliminate all chars EXCEPT:
1109                 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1110                 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1111             }
1112             return $param;
1114         case PARAM_EMAIL:
1115             $param = fix_utf8($param);
1116             if (validate_email($param)) {
1117                 return $param;
1118             } else {
1119                 return '';
1120             }
1122         case PARAM_STRINGID:
1123             if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1124                 return $param;
1125             } else {
1126                 return '';
1127             }
1129         case PARAM_TIMEZONE:    //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1130             $param = fix_utf8($param);
1131             $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1132             if (preg_match($timezonepattern, $param)) {
1133                 return $param;
1134             } else {
1135                 return '';
1136             }
1138         default:                 // throw error, switched parameters in optional_param or another serious problem
1139             print_error("unknownparamtype", '', '', $type);
1140     }
1143 /**
1144  * Makes sure the data is using valid utf8, invalid characters are discarded.
1145  *
1146  * Note: this function is not intended for full objects with methods and private properties.
1147  *
1148  * @param mixed $value
1149  * @return mixed with proper utf-8 encoding
1150  */
1151 function fix_utf8($value) {
1152     if (is_null($value) or $value === '') {
1153         return $value;
1155     } else if (is_string($value)) {
1156         if ((string)(int)$value === $value) {
1157             // shortcut
1158             return $value;
1159         }
1161         // Lower error reporting because glibc throws bogus notices.
1162         $olderror = error_reporting();
1163         if ($olderror & E_NOTICE) {
1164             error_reporting($olderror ^ E_NOTICE);
1165         }
1167         // Note: this duplicates min_fix_utf8() intentionally.
1168         static $buggyiconv = null;
1169         if ($buggyiconv === null) {
1170             $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1171         }
1173         if ($buggyiconv) {
1174             if (function_exists('mb_convert_encoding')) {
1175                 $subst = mb_substitute_character();
1176                 mb_substitute_character('');
1177                 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1178                 mb_substitute_character($subst);
1180             } else {
1181                 // Warn admins on admin/index.php page.
1182                 $result = $value;
1183             }
1185         } else {
1186             $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1187         }
1189         if ($olderror & E_NOTICE) {
1190             error_reporting($olderror);
1191         }
1193         return $result;
1195     } else if (is_array($value)) {
1196         foreach ($value as $k=>$v) {
1197             $value[$k] = fix_utf8($v);
1198         }
1199         return $value;
1201     } else if (is_object($value)) {
1202         $value = clone($value); // do not modify original
1203         foreach ($value as $k=>$v) {
1204             $value->$k = fix_utf8($v);
1205         }
1206         return $value;
1208     } else {
1209         // this is some other type, no utf-8 here
1210         return $value;
1211     }
1214 /**
1215  * Return true if given value is integer or string with integer value
1216  *
1217  * @param mixed $value String or Int
1218  * @return bool true if number, false if not
1219  */
1220 function is_number($value) {
1221     if (is_int($value)) {
1222         return true;
1223     } else if (is_string($value)) {
1224         return ((string)(int)$value) === $value;
1225     } else {
1226         return false;
1227     }
1230 /**
1231  * Returns host part from url
1232  * @param string $url full url
1233  * @return string host, null if not found
1234  */
1235 function get_host_from_url($url) {
1236     preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1237     if ($matches) {
1238         return $matches[1];
1239     }
1240     return null;
1243 /**
1244  * Tests whether anything was returned by text editor
1245  *
1246  * This function is useful for testing whether something you got back from
1247  * the HTML editor actually contains anything. Sometimes the HTML editor
1248  * appear to be empty, but actually you get back a <br> tag or something.
1249  *
1250  * @param string $string a string containing HTML.
1251  * @return boolean does the string contain any actual content - that is text,
1252  * images, objects, etc.
1253  */
1254 function html_is_blank($string) {
1255     return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1258 /**
1259  * Set a key in global configuration
1260  *
1261  * Set a key/value pair in both this session's {@link $CFG} global variable
1262  * and in the 'config' database table for future sessions.
1263  *
1264  * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1265  * In that case it doesn't affect $CFG.
1266  *
1267  * A NULL value will delete the entry.
1268  *
1269  * @global object
1270  * @global object
1271  * @param string $name the key to set
1272  * @param string $value the value to set (without magic quotes)
1273  * @param string $plugin (optional) the plugin scope, default NULL
1274  * @return bool true or exception
1275  */
1276 function set_config($name, $value, $plugin=NULL) {
1277     global $CFG, $DB;
1279     if (empty($plugin)) {
1280         if (!array_key_exists($name, $CFG->config_php_settings)) {
1281             // So it's defined for this invocation at least
1282             if (is_null($value)) {
1283                 unset($CFG->$name);
1284             } else {
1285                 $CFG->$name = (string)$value; // settings from db are always strings
1286             }
1287         }
1289         if ($DB->get_field('config', 'name', array('name'=>$name))) {
1290             if ($value === null) {
1291                 $DB->delete_records('config', array('name'=>$name));
1292             } else {
1293                 $DB->set_field('config', 'value', $value, array('name'=>$name));
1294             }
1295         } else {
1296             if ($value !== null) {
1297                 $config = new stdClass();
1298                 $config->name  = $name;
1299                 $config->value = $value;
1300                 $DB->insert_record('config', $config, false);
1301             }
1302         }
1304     } else { // plugin scope
1305         if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1306             if ($value===null) {
1307                 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1308             } else {
1309                 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1310             }
1311         } else {
1312             if ($value !== null) {
1313                 $config = new stdClass();
1314                 $config->plugin = $plugin;
1315                 $config->name   = $name;
1316                 $config->value  = $value;
1317                 $DB->insert_record('config_plugins', $config, false);
1318             }
1319         }
1320     }
1322     return true;
1325 /**
1326  * Get configuration values from the global config table
1327  * or the config_plugins table.
1328  *
1329  * If called with one parameter, it will load all the config
1330  * variables for one plugin, and return them as an object.
1331  *
1332  * If called with 2 parameters it will return a string single
1333  * value or false if the value is not found.
1334  *
1335  * @param string $plugin full component name
1336  * @param string $name default NULL
1337  * @return mixed hash-like object or single value, return false no config found
1338  */
1339 function get_config($plugin, $name = NULL) {
1340     global $CFG, $DB;
1342     // normalise component name
1343     if ($plugin === 'moodle' or $plugin === 'core') {
1344         $plugin = NULL;
1345     }
1347     if (!empty($name)) { // the user is asking for a specific value
1348         if (!empty($plugin)) {
1349             if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1350                 // setting forced in config file
1351                 return $CFG->forced_plugin_settings[$plugin][$name];
1352             } else {
1353                 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1354             }
1355         } else {
1356             if (array_key_exists($name, $CFG->config_php_settings)) {
1357                 // setting force in config file
1358                 return $CFG->config_php_settings[$name];
1359             } else {
1360                 return $DB->get_field('config', 'value', array('name'=>$name));
1361             }
1362         }
1363     }
1365     // the user is after a recordset
1366     if ($plugin) {
1367         $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1368         if (isset($CFG->forced_plugin_settings[$plugin])) {
1369             foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1370                 if (is_null($v) or is_array($v) or is_object($v)) {
1371                     // we do not want any extra mess here, just real settings that could be saved in db
1372                     unset($localcfg[$n]);
1373                 } else {
1374                     //convert to string as if it went through the DB
1375                     $localcfg[$n] = (string)$v;
1376                 }
1377             }
1378         }
1379         if ($localcfg) {
1380             return (object)$localcfg;
1381         } else {
1382             return new stdClass();
1383         }
1385     } else {
1386         // this part is not really used any more, but anyway...
1387         $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1388         foreach($CFG->config_php_settings as $n=>$v) {
1389             if (is_null($v) or is_array($v) or is_object($v)) {
1390                 // we do not want any extra mess here, just real settings that could be saved in db
1391                 unset($localcfg[$n]);
1392             } else {
1393                 //convert to string as if it went through the DB
1394                 $localcfg[$n] = (string)$v;
1395             }
1396         }
1397         return (object)$localcfg;
1398     }
1401 /**
1402  * Removes a key from global configuration
1403  *
1404  * @param string $name the key to set
1405  * @param string $plugin (optional) the plugin scope
1406  * @global object
1407  * @return boolean whether the operation succeeded.
1408  */
1409 function unset_config($name, $plugin=NULL) {
1410     global $CFG, $DB;
1412     if (empty($plugin)) {
1413         unset($CFG->$name);
1414         $DB->delete_records('config', array('name'=>$name));
1415     } else {
1416         $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1417     }
1419     return true;
1422 /**
1423  * Remove all the config variables for a given plugin.
1424  *
1425  * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1426  * @return boolean whether the operation succeeded.
1427  */
1428 function unset_all_config_for_plugin($plugin) {
1429     global $DB;
1430     $DB->delete_records('config_plugins', array('plugin' => $plugin));
1431     $like = $DB->sql_like('name', '?', true, true, false, '|');
1432     $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1433     $DB->delete_records_select('config', $like, $params);
1434     return true;
1437 /**
1438  * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1439  *
1440  * All users are verified if they still have the necessary capability.
1441  *
1442  * @param string $value the value of the config setting.
1443  * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1444  * @param bool $include admins, include administrators
1445  * @return array of user objects.
1446  */
1447 function get_users_from_config($value, $capability, $includeadmins = true) {
1448     global $CFG, $DB;
1450     if (empty($value) or $value === '$@NONE@$') {
1451         return array();
1452     }
1454     // we have to make sure that users still have the necessary capability,
1455     // it should be faster to fetch them all first and then test if they are present
1456     // instead of validating them one-by-one
1457     $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1458     if ($includeadmins) {
1459         $admins = get_admins();
1460         foreach ($admins as $admin) {
1461             $users[$admin->id] = $admin;
1462         }
1463     }
1465     if ($value === '$@ALL@$') {
1466         return $users;
1467     }
1469     $result = array(); // result in correct order
1470     $allowed = explode(',', $value);
1471     foreach ($allowed as $uid) {
1472         if (isset($users[$uid])) {
1473             $user = $users[$uid];
1474             $result[$user->id] = $user;
1475         }
1476     }
1478     return $result;
1482 /**
1483  * Invalidates browser caches and cached data in temp
1484  * @return void
1485  */
1486 function purge_all_caches() {
1487     global $CFG;
1489     reset_text_filters_cache();
1490     js_reset_all_caches();
1491     theme_reset_all_caches();
1492     get_string_manager()->reset_caches();
1493     textlib::reset_caches();
1495     // purge all other caches: rss, simplepie, etc.
1496     remove_dir($CFG->cachedir.'', true);
1498     // make sure cache dir is writable, throws exception if not
1499     make_cache_directory('');
1501     // hack: this script may get called after the purifier was initialised,
1502     // but we do not want to verify repeatedly this exists in each call
1503     make_cache_directory('htmlpurifier');
1506 /**
1507  * Get volatile flags
1508  *
1509  * @param string $type
1510  * @param int    $changedsince default null
1511  * @return records array
1512  */
1513 function get_cache_flags($type, $changedsince=NULL) {
1514     global $DB;
1516     $params = array('type'=>$type, 'expiry'=>time());
1517     $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1518     if ($changedsince !== NULL) {
1519         $params['changedsince'] = $changedsince;
1520         $sqlwhere .= " AND timemodified > :changedsince";
1521     }
1522     $cf = array();
1524     if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1525         foreach ($flags as $flag) {
1526             $cf[$flag->name] = $flag->value;
1527         }
1528     }
1529     return $cf;
1532 /**
1533  * Get volatile flags
1534  *
1535  * @param string $type
1536  * @param string $name
1537  * @param int    $changedsince default null
1538  * @return records array
1539  */
1540 function get_cache_flag($type, $name, $changedsince=NULL) {
1541     global $DB;
1543     $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1545     $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1546     if ($changedsince !== NULL) {
1547         $params['changedsince'] = $changedsince;
1548         $sqlwhere .= " AND timemodified > :changedsince";
1549     }
1551     return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1554 /**
1555  * Set a volatile flag
1556  *
1557  * @param string $type the "type" namespace for the key
1558  * @param string $name the key to set
1559  * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1560  * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1561  * @return bool Always returns true
1562  */
1563 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1564     global $DB;
1566     $timemodified = time();
1567     if ($expiry===NULL || $expiry < $timemodified) {
1568         $expiry = $timemodified + 24 * 60 * 60;
1569     } else {
1570         $expiry = (int)$expiry;
1571     }
1573     if ($value === NULL) {
1574         unset_cache_flag($type,$name);
1575         return true;
1576     }
1578     if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1579         if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1580             return true; //no need to update; helps rcache too
1581         }
1582         $f->value        = $value;
1583         $f->expiry       = $expiry;
1584         $f->timemodified = $timemodified;
1585         $DB->update_record('cache_flags', $f);
1586     } else {
1587         $f = new stdClass();
1588         $f->flagtype     = $type;
1589         $f->name         = $name;
1590         $f->value        = $value;
1591         $f->expiry       = $expiry;
1592         $f->timemodified = $timemodified;
1593         $DB->insert_record('cache_flags', $f);
1594     }
1595     return true;
1598 /**
1599  * Removes a single volatile flag
1600  *
1601  * @global object
1602  * @param string $type the "type" namespace for the key
1603  * @param string $name the key to set
1604  * @return bool
1605  */
1606 function unset_cache_flag($type, $name) {
1607     global $DB;
1608     $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1609     return true;
1612 /**
1613  * Garbage-collect volatile flags
1614  *
1615  * @return bool Always returns true
1616  */
1617 function gc_cache_flags() {
1618     global $DB;
1619     $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1620     return true;
1623 // USER PREFERENCE API
1625 /**
1626  * Refresh user preference cache. This is used most often for $USER
1627  * object that is stored in session, but it also helps with performance in cron script.
1628  *
1629  * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1630  *
1631  * @package  core
1632  * @category preference
1633  * @access   public
1634  * @param    stdClass         $user          User object. Preferences are preloaded into 'preference' property
1635  * @param    int              $cachelifetime Cache life time on the current page (in seconds)
1636  * @throws   coding_exception
1637  * @return   null
1638  */
1639 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1640     global $DB;
1641     static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1643     if (!isset($user->id)) {
1644         throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1645     }
1647     if (empty($user->id) or isguestuser($user->id)) {
1648         // No permanent storage for not-logged-in users and guest
1649         if (!isset($user->preference)) {
1650             $user->preference = array();
1651         }
1652         return;
1653     }
1655     $timenow = time();
1657     if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1658         // Already loaded at least once on this page. Are we up to date?
1659         if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1660             // no need to reload - we are on the same page and we loaded prefs just a moment ago
1661             return;
1663         } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1664             // no change since the lastcheck on this page
1665             $user->preference['_lastloaded'] = $timenow;
1666             return;
1667         }
1668     }
1670     // OK, so we have to reload all preferences
1671     $loadedusers[$user->id] = true;
1672     $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1673     $user->preference['_lastloaded'] = $timenow;
1676 /**
1677  * Called from set/unset_user_preferences, so that the prefs can
1678  * be correctly reloaded in different sessions.
1679  *
1680  * NOTE: internal function, do not call from other code.
1681  *
1682  * @package core
1683  * @access  private
1684  * @param   integer         $userid the user whose prefs were changed.
1685  */
1686 function mark_user_preferences_changed($userid) {
1687     global $CFG;
1689     if (empty($userid) or isguestuser($userid)) {
1690         // no cache flags for guest and not-logged-in users
1691         return;
1692     }
1694     set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1697 /**
1698  * Sets a preference for the specified user.
1699  *
1700  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1701  *
1702  * @package  core
1703  * @category preference
1704  * @access   public
1705  * @param    string            $name  The key to set as preference for the specified user
1706  * @param    string            $value The value to set for the $name key in the specified user's
1707  *                                    record, null means delete current value.
1708  * @param    stdClass|int|null $user  A moodle user object or id, null means current user
1709  * @throws   coding_exception
1710  * @return   bool                     Always true or exception
1711  */
1712 function set_user_preference($name, $value, $user = null) {
1713     global $USER, $DB;
1715     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1716         throw new coding_exception('Invalid preference name in set_user_preference() call');
1717     }
1719     if (is_null($value)) {
1720         // null means delete current
1721         return unset_user_preference($name, $user);
1722     } else if (is_object($value)) {
1723         throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1724     } else if (is_array($value)) {
1725         throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1726     }
1727     $value = (string)$value;
1728     if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1729         throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1730     }
1732     if (is_null($user)) {
1733         $user = $USER;
1734     } else if (isset($user->id)) {
1735         // $user is valid object
1736     } else if (is_numeric($user)) {
1737         $user = (object)array('id'=>(int)$user);
1738     } else {
1739         throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1740     }
1742     check_user_preferences_loaded($user);
1744     if (empty($user->id) or isguestuser($user->id)) {
1745         // no permanent storage for not-logged-in users and guest
1746         $user->preference[$name] = $value;
1747         return true;
1748     }
1750     if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1751         if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1752             // preference already set to this value
1753             return true;
1754         }
1755         $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1757     } else {
1758         $preference = new stdClass();
1759         $preference->userid = $user->id;
1760         $preference->name   = $name;
1761         $preference->value  = $value;
1762         $DB->insert_record('user_preferences', $preference);
1763     }
1765     // update value in cache
1766     $user->preference[$name] = $value;
1768     // set reload flag for other sessions
1769     mark_user_preferences_changed($user->id);
1771     return true;
1774 /**
1775  * Sets a whole array of preferences for the current user
1776  *
1777  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1778  *
1779  * @package  core
1780  * @category preference
1781  * @access   public
1782  * @param    array             $prefarray An array of key/value pairs to be set
1783  * @param    stdClass|int|null $user      A moodle user object or id, null means current user
1784  * @return   bool                         Always true or exception
1785  */
1786 function set_user_preferences(array $prefarray, $user = null) {
1787     foreach ($prefarray as $name => $value) {
1788         set_user_preference($name, $value, $user);
1789     }
1790     return true;
1793 /**
1794  * Unsets a preference completely by deleting it from the database
1795  *
1796  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1797  *
1798  * @package  core
1799  * @category preference
1800  * @access   public
1801  * @param    string            $name The key to unset as preference for the specified user
1802  * @param    stdClass|int|null $user A moodle user object or id, null means current user
1803  * @throws   coding_exception
1804  * @return   bool                    Always true or exception
1805  */
1806 function unset_user_preference($name, $user = null) {
1807     global $USER, $DB;
1809     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1810         throw new coding_exception('Invalid preference name in unset_user_preference() call');
1811     }
1813     if (is_null($user)) {
1814         $user = $USER;
1815     } else if (isset($user->id)) {
1816         // $user is valid object
1817     } else if (is_numeric($user)) {
1818         $user = (object)array('id'=>(int)$user);
1819     } else {
1820         throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1821     }
1823     check_user_preferences_loaded($user);
1825     if (empty($user->id) or isguestuser($user->id)) {
1826         // no permanent storage for not-logged-in user and guest
1827         unset($user->preference[$name]);
1828         return true;
1829     }
1831     // delete from DB
1832     $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1834     // delete the preference from cache
1835     unset($user->preference[$name]);
1837     // set reload flag for other sessions
1838     mark_user_preferences_changed($user->id);
1840     return true;
1843 /**
1844  * Used to fetch user preference(s)
1845  *
1846  * If no arguments are supplied this function will return
1847  * all of the current user preferences as an array.
1848  *
1849  * If a name is specified then this function
1850  * attempts to return that particular preference value.  If
1851  * none is found, then the optional value $default is returned,
1852  * otherwise NULL.
1853  *
1854  * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1855  *
1856  * @package  core
1857  * @category preference
1858  * @access   public
1859  * @param    string            $name    Name of the key to use in finding a preference value
1860  * @param    mixed|null        $default Value to be returned if the $name key is not set in the user preferences
1861  * @param    stdClass|int|null $user    A moodle user object or id, null means current user
1862  * @throws   coding_exception
1863  * @return   string|mixed|null          A string containing the value of a single preference. An
1864  *                                      array with all of the preferences or null
1865  */
1866 function get_user_preferences($name = null, $default = null, $user = null) {
1867     global $USER;
1869     if (is_null($name)) {
1870         // all prefs
1871     } else if (is_numeric($name) or $name === '_lastloaded') {
1872         throw new coding_exception('Invalid preference name in get_user_preferences() call');
1873     }
1875     if (is_null($user)) {
1876         $user = $USER;
1877     } else if (isset($user->id)) {
1878         // $user is valid object
1879     } else if (is_numeric($user)) {
1880         $user = (object)array('id'=>(int)$user);
1881     } else {
1882         throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1883     }
1885     check_user_preferences_loaded($user);
1887     if (empty($name)) {
1888         return $user->preference; // All values
1889     } else if (isset($user->preference[$name])) {
1890         return $user->preference[$name]; // The single string value
1891     } else {
1892         return $default; // Default value (null if not specified)
1893     }
1896 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1898 /**
1899  * Given date parts in user time produce a GMT timestamp.
1900  *
1901  * @package core
1902  * @category time
1903  * @param int $year The year part to create timestamp of
1904  * @param int $month The month part to create timestamp of
1905  * @param int $day The day part to create timestamp of
1906  * @param int $hour The hour part to create timestamp of
1907  * @param int $minute The minute part to create timestamp of
1908  * @param int $second The second part to create timestamp of
1909  * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1910  *             if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
1911  * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1912  *             applied only if timezone is 99 or string.
1913  * @return int GMT timestamp
1914  */
1915 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1917     //save input timezone, required for dst offset check.
1918     $passedtimezone = $timezone;
1920     $timezone = get_user_timezone_offset($timezone);
1922     if (abs($timezone) > 13) {  //server time
1923         $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1924     } else {
1925         $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1926         $time = usertime($time, $timezone);
1928         //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1929         if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1930             $time -= dst_offset_on($time, $passedtimezone);
1931         }
1932     }
1934     return $time;
1938 /**
1939  * Format a date/time (seconds) as weeks, days, hours etc as needed
1940  *
1941  * Given an amount of time in seconds, returns string
1942  * formatted nicely as weeks, days, hours etc as needed
1943  *
1944  * @package core
1945  * @category time
1946  * @uses MINSECS
1947  * @uses HOURSECS
1948  * @uses DAYSECS
1949  * @uses YEARSECS
1950  * @param int $totalsecs Time in seconds
1951  * @param object $str Should be a time object
1952  * @return string A nicely formatted date/time string
1953  */
1954  function format_time($totalsecs, $str=NULL) {
1956     $totalsecs = abs($totalsecs);
1958     if (!$str) {  // Create the str structure the slow way
1959         $str = new stdClass();
1960         $str->day   = get_string('day');
1961         $str->days  = get_string('days');
1962         $str->hour  = get_string('hour');
1963         $str->hours = get_string('hours');
1964         $str->min   = get_string('min');
1965         $str->mins  = get_string('mins');
1966         $str->sec   = get_string('sec');
1967         $str->secs  = get_string('secs');
1968         $str->year  = get_string('year');
1969         $str->years = get_string('years');
1970     }
1973     $years     = floor($totalsecs/YEARSECS);
1974     $remainder = $totalsecs - ($years*YEARSECS);
1975     $days      = floor($remainder/DAYSECS);
1976     $remainder = $totalsecs - ($days*DAYSECS);
1977     $hours     = floor($remainder/HOURSECS);
1978     $remainder = $remainder - ($hours*HOURSECS);
1979     $mins      = floor($remainder/MINSECS);
1980     $secs      = $remainder - ($mins*MINSECS);
1982     $ss = ($secs == 1)  ? $str->sec  : $str->secs;
1983     $sm = ($mins == 1)  ? $str->min  : $str->mins;
1984     $sh = ($hours == 1) ? $str->hour : $str->hours;
1985     $sd = ($days == 1)  ? $str->day  : $str->days;
1986     $sy = ($years == 1)  ? $str->year  : $str->years;
1988     $oyears = '';
1989     $odays = '';
1990     $ohours = '';
1991     $omins = '';
1992     $osecs = '';
1994     if ($years)  $oyears  = $years .' '. $sy;
1995     if ($days)  $odays  = $days .' '. $sd;
1996     if ($hours) $ohours = $hours .' '. $sh;
1997     if ($mins)  $omins  = $mins .' '. $sm;
1998     if ($secs)  $osecs  = $secs .' '. $ss;
2000     if ($years) return trim($oyears .' '. $odays);
2001     if ($days)  return trim($odays .' '. $ohours);
2002     if ($hours) return trim($ohours .' '. $omins);
2003     if ($mins)  return trim($omins .' '. $osecs);
2004     if ($secs)  return $osecs;
2005     return get_string('now');
2008 /**
2009  * Returns a formatted string that represents a date in user time
2010  *
2011  * Returns a formatted string that represents a date in user time
2012  * <b>WARNING: note that the format is for strftime(), not date().</b>
2013  * Because of a bug in most Windows time libraries, we can't use
2014  * the nicer %e, so we have to use %d which has leading zeroes.
2015  * A lot of the fuss in the function is just getting rid of these leading
2016  * zeroes as efficiently as possible.
2017  *
2018  * If parameter fixday = true (default), then take off leading
2019  * zero from %d, else maintain it.
2020  *
2021  * @package core
2022  * @category time
2023  * @param int $date the timestamp in UTC, as obtained from the database.
2024  * @param string $format strftime format. You should probably get this using
2025  *        get_string('strftime...', 'langconfig');
2026  * @param int|float|string  $timezone by default, uses the user's time zone. if numeric and
2027  *        not 99 then daylight saving will not be added.
2028  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2029  * @param bool $fixday If true (default) then the leading zero from %d is removed.
2030  *        If false then the leading zero is maintained.
2031  * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2032  * @return string the formatted date/time.
2033  */
2034 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2036     global $CFG;
2038     if (empty($format)) {
2039         $format = get_string('strftimedaydatetime', 'langconfig');
2040     }
2042     if (!empty($CFG->nofixday)) {  // Config.php can force %d not to be fixed.
2043         $fixday = false;
2044     } else if ($fixday) {
2045         $formatnoday = str_replace('%d', 'DD', $format);
2046         $fixday = ($formatnoday != $format);
2047         $format = $formatnoday;
2048     }
2050     // Note: This logic about fixing 12-hour time to remove unnecessary leading
2051     // zero is required because on Windows, PHP strftime function does not
2052     // support the correct 'hour without leading zero' parameter (%l).
2053     if (!empty($CFG->nofixhour)) {
2054         // Config.php can force %I not to be fixed.
2055         $fixhour = false;
2056     } else if ($fixhour) {
2057         $formatnohour = str_replace('%I', 'HH', $format);
2058         $fixhour = ($formatnohour != $format);
2059         $format = $formatnohour;
2060     }
2062     //add daylight saving offset for string timezones only, as we can't get dst for
2063     //float values. if timezone is 99 (user default timezone), then try update dst.
2064     if ((99 == $timezone) || !is_numeric($timezone)) {
2065         $date += dst_offset_on($date, $timezone);
2066     }
2068     $timezone = get_user_timezone_offset($timezone);
2070     // If we are running under Windows convert to windows encoding and then back to UTF-8
2071     // (because it's impossible to specify UTF-8 to fetch locale info in Win32)
2073     if (abs($timezone) > 13) {   /// Server time
2074         $datestring = date_format_string($date, $format, $timezone);
2075         if ($fixday) {
2076             $daystring  = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
2077             $datestring = str_replace('DD', $daystring, $datestring);
2078         }
2079         if ($fixhour) {
2080             $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2081             $datestring = str_replace('HH', $hourstring, $datestring);
2082         }
2084     } else {
2085         $date += (int)($timezone * 3600);
2086         $datestring = date_format_string($date, $format, $timezone);
2087         if ($fixday) {
2088             $daystring  = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
2089             $datestring = str_replace('DD', $daystring, $datestring);
2090         }
2091         if ($fixhour) {
2092             $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2093             $datestring = str_replace('HH', $hourstring, $datestring);
2094         }
2095     }
2097     return $datestring;
2100 /**
2101  * Returns a formatted date ensuring it is UTF-8.
2102  *
2103  * If we are running under Windows convert to Windows encoding and then back to UTF-8
2104  * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2105  *
2106  * This function does not do any calculation regarding the user preferences and should
2107  * therefore receive the final date timestamp, format and timezone. Timezone being only used
2108  * to differenciate the use of server time or not (strftime() against gmstrftime()).
2109  *
2110  * @param int $date the timestamp.
2111  * @param string $format strftime format.
2112  * @param int|float $timezone the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2113  * @return string the formatted date/time.
2114  * @since 2.3.3
2115  */
2116 function date_format_string($date, $format, $tz = 99) {
2117     global $CFG;
2118     if (abs($tz) > 13) {
2119         if ($CFG->ostype == 'WINDOWS') {
2120             $localewincharset = get_string('localewincharset', 'langconfig');
2121             $format = textlib::convert($format, 'utf-8', $localewincharset);
2122             $datestring = strftime($format, $date);
2123             $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2124         } else {
2125             $datestring = strftime($format, $date);
2126         }
2127     } else {
2128         if ($CFG->ostype == 'WINDOWS') {
2129             $localewincharset = get_string('localewincharset', 'langconfig');
2130             $format = textlib::convert($format, 'utf-8', $localewincharset);
2131             $datestring = gmstrftime($format, $date);
2132             $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2133         } else {
2134             $datestring = gmstrftime($format, $date);
2135         }
2136     }
2137     return $datestring;
2140 /**
2141  * Given a $time timestamp in GMT (seconds since epoch),
2142  * returns an array that represents the date in user time
2143  *
2144  * @package core
2145  * @category time
2146  * @uses HOURSECS
2147  * @param int $time Timestamp in GMT
2148  * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2149  *        dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
2150  * @return array An array that represents the date in user time
2151  */
2152 function usergetdate($time, $timezone=99) {
2154     //save input timezone, required for dst offset check.
2155     $passedtimezone = $timezone;
2157     $timezone = get_user_timezone_offset($timezone);
2159     if (abs($timezone) > 13) {    // Server time
2160         return getdate($time);
2161     }
2163     //add daylight saving offset for string timezones only, as we can't get dst for
2164     //float values. if timezone is 99 (user default timezone), then try update dst.
2165     if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2166         $time += dst_offset_on($time, $passedtimezone);
2167     }
2169     $time += intval((float)$timezone * HOURSECS);
2171     $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2173     //be careful to ensure the returned array matches that produced by getdate() above
2174     list(
2175         $getdate['month'],
2176         $getdate['weekday'],
2177         $getdate['yday'],
2178         $getdate['year'],
2179         $getdate['mon'],
2180         $getdate['wday'],
2181         $getdate['mday'],
2182         $getdate['hours'],
2183         $getdate['minutes'],
2184         $getdate['seconds']
2185     ) = explode('_', $datestring);
2187     // set correct datatype to match with getdate()
2188     $getdate['seconds'] = (int)$getdate['seconds'];
2189     $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
2190     $getdate['year'] = (int)$getdate['year'];
2191     $getdate['mon'] = (int)$getdate['mon'];
2192     $getdate['wday'] = (int)$getdate['wday'];
2193     $getdate['mday'] = (int)$getdate['mday'];
2194     $getdate['hours'] = (int)$getdate['hours'];
2195     $getdate['minutes']  = (int)$getdate['minutes'];
2196     return $getdate;
2199 /**
2200  * Given a GMT timestamp (seconds since epoch), offsets it by
2201  * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2202  *
2203  * @package core
2204  * @category time
2205  * @uses HOURSECS
2206  * @param int $date Timestamp in GMT
2207  * @param float|int|string $timezone timezone to calculate GMT time offset before
2208  *        calculating user time, 99 is default user timezone
2209  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2210  * @return int
2211  */
2212 function usertime($date, $timezone=99) {
2214     $timezone = get_user_timezone_offset($timezone);
2216     if (abs($timezone) > 13) {
2217         return $date;
2218     }
2219     return $date - (int)($timezone * HOURSECS);
2222 /**
2223  * Given a time, return the GMT timestamp of the most recent midnight
2224  * for the current user.
2225  *
2226  * @package core
2227  * @category time
2228  * @param int $date Timestamp in GMT
2229  * @param float|int|string $timezone timezone to calculate GMT time offset before
2230  *        calculating user midnight time, 99 is default user timezone
2231  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2232  * @return int Returns a GMT timestamp
2233  */
2234 function usergetmidnight($date, $timezone=99) {
2236     $userdate = usergetdate($date, $timezone);
2238     // Time of midnight of this user's day, in GMT
2239     return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2243 /**
2244  * Returns a string that prints the user's timezone
2245  *
2246  * @package core
2247  * @category time
2248  * @param float|int|string $timezone timezone to calculate GMT time offset before
2249  *        calculating user timezone, 99 is default user timezone
2250  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2251  * @return string
2252  */
2253 function usertimezone($timezone=99) {
2255     $tz = get_user_timezone($timezone);
2257     if (!is_float($tz)) {
2258         return $tz;
2259     }
2261     if(abs($tz) > 13) { // Server time
2262         return get_string('serverlocaltime');
2263     }
2265     if($tz == intval($tz)) {
2266         // Don't show .0 for whole hours
2267         $tz = intval($tz);
2268     }
2270     if($tz == 0) {
2271         return 'UTC';
2272     }
2273     else if($tz > 0) {
2274         return 'UTC+'.$tz;
2275     }
2276     else {
2277         return 'UTC'.$tz;
2278     }
2282 /**
2283  * Returns a float which represents the user's timezone difference from GMT in hours
2284  * Checks various settings and picks the most dominant of those which have a value
2285  *
2286  * @package core
2287  * @category time
2288  * @param float|int|string $tz timezone to calculate GMT time offset for user,
2289  *        99 is default user timezone
2290  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2291  * @return float
2292  */
2293 function get_user_timezone_offset($tz = 99) {
2295     global $USER, $CFG;
2297     $tz = get_user_timezone($tz);
2299     if (is_float($tz)) {
2300         return $tz;
2301     } else {
2302         $tzrecord = get_timezone_record($tz);
2303         if (empty($tzrecord)) {
2304             return 99.0;
2305         }
2306         return (float)$tzrecord->gmtoff / HOURMINS;
2307     }
2310 /**
2311  * Returns an int which represents the systems's timezone difference from GMT in seconds
2312  *
2313  * @package core
2314  * @category time
2315  * @param float|int|string $tz timezone for which offset is required.
2316  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2317  * @return int|bool if found, false is timezone 99 or error
2318  */
2319 function get_timezone_offset($tz) {
2320     global $CFG;
2322     if ($tz == 99) {
2323         return false;
2324     }
2326     if (is_numeric($tz)) {
2327         return intval($tz * 60*60);
2328     }
2330     if (!$tzrecord = get_timezone_record($tz)) {
2331         return false;
2332     }
2333     return intval($tzrecord->gmtoff * 60);
2336 /**
2337  * Returns a float or a string which denotes the user's timezone
2338  * 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)
2339  * means that for this timezone there are also DST rules to be taken into account
2340  * Checks various settings and picks the most dominant of those which have a value
2341  *
2342  * @package core
2343  * @category time
2344  * @param float|int|string $tz timezone to calculate GMT time offset before
2345  *        calculating user timezone, 99 is default user timezone
2346  *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2347  * @return float|string
2348  */
2349 function get_user_timezone($tz = 99) {
2350     global $USER, $CFG;
2352     $timezones = array(
2353         $tz,
2354         isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2355         isset($USER->timezone) ? $USER->timezone : 99,
2356         isset($CFG->timezone) ? $CFG->timezone : 99,
2357         );
2359     $tz = 99;
2361     // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array
2362     while(((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2363         $tz = $next['value'];
2364     }
2365     return is_numeric($tz) ? (float) $tz : $tz;
2368 /**
2369  * Returns cached timezone record for given $timezonename
2370  *
2371  * @package core
2372  * @param string $timezonename name of the timezone
2373  * @return stdClass|bool timezonerecord or false
2374  */
2375 function get_timezone_record($timezonename) {
2376     global $CFG, $DB;
2377     static $cache = NULL;
2379     if ($cache === NULL) {
2380         $cache = array();
2381     }
2383     if (isset($cache[$timezonename])) {
2384         return $cache[$timezonename];
2385     }
2387     return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2388                                                         WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2391 /**
2392  * Build and store the users Daylight Saving Time (DST) table
2393  *
2394  * @package core
2395  * @param int $from_year Start year for the table, defaults to 1971
2396  * @param int $to_year End year for the table, defaults to 2035
2397  * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
2398  * @return bool
2399  */
2400 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2401     global $CFG, $SESSION, $DB;
2403     $usertz = get_user_timezone($strtimezone);
2405     if (is_float($usertz)) {
2406         // Trivial timezone, no DST
2407         return false;
2408     }
2410     if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2411         // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2412         unset($SESSION->dst_offsets);
2413         unset($SESSION->dst_range);
2414     }
2416     if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2417         // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2418         // This will be the return path most of the time, pretty light computationally
2419         return true;
2420     }
2422     // Reaching here means we either need to extend our table or create it from scratch
2424     // Remember which TZ we calculated these changes for
2425     $SESSION->dst_offsettz = $usertz;
2427     if(empty($SESSION->dst_offsets)) {
2428         // If we 're creating from scratch, put the two guard elements in there
2429         $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2430     }
2431     if(empty($SESSION->dst_range)) {
2432         // If creating from scratch
2433         $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2434         $to   = min((empty($to_year)   ? intval(date('Y')) + 3 : $to_year),   2035);
2436         // Fill in the array with the extra years we need to process
2437         $yearstoprocess = array();
2438         for($i = $from; $i <= $to; ++$i) {
2439             $yearstoprocess[] = $i;
2440         }
2442         // Take note of which years we have processed for future calls
2443         $SESSION->dst_range = array($from, $to);
2444     }
2445     else {
2446         // If needing to extend the table, do the same
2447         $yearstoprocess = array();
2449         $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2450         $to   = min((empty($to_year)   ? $SESSION->dst_range[1] : $to_year),   2035);
2452         if($from < $SESSION->dst_range[0]) {
2453             // Take note of which years we need to process and then note that we have processed them for future calls
2454             for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2455                 $yearstoprocess[] = $i;
2456             }
2457             $SESSION->dst_range[0] = $from;
2458         }
2459         if($to > $SESSION->dst_range[1]) {
2460             // Take note of which years we need to process and then note that we have processed them for future calls
2461             for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2462                 $yearstoprocess[] = $i;
2463             }
2464             $SESSION->dst_range[1] = $to;
2465         }
2466     }
2468     if(empty($yearstoprocess)) {
2469         // This means that there was a call requesting a SMALLER range than we have already calculated
2470         return true;
2471     }
2473     // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2474     // Also, the array is sorted in descending timestamp order!
2476     // Get DB data
2478     static $presets_cache = array();
2479     if (!isset($presets_cache[$usertz])) {
2480         $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');
2481     }
2482     if(empty($presets_cache[$usertz])) {
2483         return false;
2484     }
2486     // Remove ending guard (first element of the array)
2487     reset($SESSION->dst_offsets);
2488     unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2490     // Add all required change timestamps
2491     foreach($yearstoprocess as $y) {
2492         // Find the record which is in effect for the year $y
2493         foreach($presets_cache[$usertz] as $year => $preset) {
2494             if($year <= $y) {
2495                 break;
2496             }
2497         }
2499         $changes = dst_changes_for_year($y, $preset);
2501         if($changes === NULL) {
2502             continue;
2503         }
2504         if($changes['dst'] != 0) {
2505             $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2506         }
2507         if($changes['std'] != 0) {
2508             $SESSION->dst_offsets[$changes['std']] = 0;
2509         }
2510     }
2512     // Put in a guard element at the top
2513     $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2514     $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2516     // Sort again
2517     krsort($SESSION->dst_offsets);
2519     return true;
2522 /**
2523  * Calculates the required DST change and returns a Timestamp Array
2524  *
2525  * @package core
2526  * @category time
2527  * @uses HOURSECS
2528  * @uses MINSECS
2529  * @param int|string $year Int or String Year to focus on
2530  * @param object $timezone Instatiated Timezone object
2531  * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
2532  */
2533 function dst_changes_for_year($year, $timezone) {
2535     if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2536         return NULL;
2537     }
2539     $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2540     $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2542     list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2543     list($std_hour, $std_min) = explode(':', $timezone->std_time);
2545     $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2546     $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2548     // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2549     // This has the advantage of being able to have negative values for hour, i.e. for timezones
2550     // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2552     $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2553     $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2555     return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2558 /**
2559  * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2560  * - Note: Daylight saving only works for string timezones and not for float.
2561  *
2562  * @package core
2563  * @category time
2564  * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2565  * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2566  *        then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2567  * @return int
2568  */
2569 function dst_offset_on($time, $strtimezone = NULL) {
2570     global $SESSION;
2572     if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2573         return 0;
2574     }
2576     reset($SESSION->dst_offsets);
2577     while(list($from, $offset) = each($SESSION->dst_offsets)) {
2578         if($from <= $time) {
2579             break;
2580         }
2581     }
2583     // This is the normal return path
2584     if($offset !== NULL) {
2585         return $offset;
2586     }
2588     // Reaching this point means we haven't calculated far enough, do it now:
2589     // Calculate extra DST changes if needed and recurse. The recursion always
2590     // moves toward the stopping condition, so will always end.
2592     if($from == 0) {
2593         // We need a year smaller than $SESSION->dst_range[0]
2594         if($SESSION->dst_range[0] == 1971) {
2595             return 0;
2596         }
2597         calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2598         return dst_offset_on($time, $strtimezone);
2599     }
2600     else {
2601         // We need a year larger than $SESSION->dst_range[1]
2602         if($SESSION->dst_range[1] == 2035) {
2603             return 0;
2604         }
2605         calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2606         return dst_offset_on($time, $strtimezone);
2607     }
2610 /**
2611  * Calculates when the day appears in specific month
2612  *
2613  * @package core
2614  * @category time
2615  * @param int $startday starting day of the month
2616  * @param int $weekday The day when week starts (normally taken from user preferences)
2617  * @param int $month The month whose day is sought
2618  * @param int $year The year of the month whose day is sought
2619  * @return int
2620  */
2621 function find_day_in_month($startday, $weekday, $month, $year) {
2623     $daysinmonth = days_in_month($month, $year);
2625     if($weekday == -1) {
2626         // Don't care about weekday, so return:
2627         //    abs($startday) if $startday != -1
2628         //    $daysinmonth otherwise
2629         return ($startday == -1) ? $daysinmonth : abs($startday);
2630     }
2632     // From now on we 're looking for a specific weekday
2634     // Give "end of month" its actual value, since we know it
2635     if($startday == -1) {
2636         $startday = -1 * $daysinmonth;
2637     }
2639     // Starting from day $startday, the sign is the direction
2641     if($startday < 1) {
2643         $startday = abs($startday);
2644         $lastmonthweekday  = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2646         // This is the last such weekday of the month
2647         $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2648         if($lastinmonth > $daysinmonth) {
2649             $lastinmonth -= 7;
2650         }
2652         // Find the first such weekday <= $startday
2653         while($lastinmonth > $startday) {
2654             $lastinmonth -= 7;
2655         }
2657         return $lastinmonth;
2659     }
2660     else {
2662         $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2664         $diff = $weekday - $indexweekday;
2665         if($diff < 0) {
2666             $diff += 7;
2667         }
2669         // This is the first such weekday of the month equal to or after $startday
2670         $firstfromindex = $startday + $diff;
2672         return $firstfromindex;
2674     }
2677 /**
2678  * Calculate the number of days in a given month
2679  *
2680  * @package core
2681  * @category time
2682  * @param int $month The month whose day count is sought
2683  * @param int $year The year of the month whose day count is sought
2684  * @return int
2685  */
2686 function days_in_month($month, $year) {
2687    return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2690 /**
2691  * Calculate the position in the week of a specific calendar day
2692  *
2693  * @package core
2694  * @category time
2695  * @param int $day The day of the date whose position in the week is sought
2696  * @param int $month The month of the date whose position in the week is sought
2697  * @param int $year The year of the date whose position in the week is sought
2698  * @return int
2699  */
2700 function dayofweek($day, $month, $year) {
2701     // I wonder if this is any different from
2702     // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2703     return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2706 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2708 /**
2709  * Returns full login url.
2710  *
2711  * @return string login url
2712  */
2713 function get_login_url() {
2714     global $CFG;
2716     $url = "$CFG->wwwroot/login/index.php";
2718     if (!empty($CFG->loginhttps)) {
2719         $url = str_replace('http:', 'https:', $url);
2720     }
2722     return $url;
2725 /**
2726  * This function checks that the current user is logged in and has the
2727  * required privileges
2728  *
2729  * This function checks that the current user is logged in, and optionally
2730  * whether they are allowed to be in a particular course and view a particular
2731  * course module.
2732  * If they are not logged in, then it redirects them to the site login unless
2733  * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2734  * case they are automatically logged in as guests.
2735  * If $courseid is given and the user is not enrolled in that course then the
2736  * user is redirected to the course enrolment page.
2737  * If $cm is given and the course module is hidden and the user is not a teacher
2738  * in the course then the user is redirected to the course home page.
2739  *
2740  * When $cm parameter specified, this function sets page layout to 'module'.
2741  * You need to change it manually later if some other layout needed.
2742  *
2743  * @package    core_access
2744  * @category   access
2745  *
2746  * @param mixed $courseorid id of the course or course object
2747  * @param bool $autologinguest default true
2748  * @param object $cm course module object
2749  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2750  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2751  *             in order to keep redirects working properly. MDL-14495
2752  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2753  * @return mixed Void, exit, and die depending on path
2754  */
2755 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2756     global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2758     // setup global $COURSE, themes, language and locale
2759     if (!empty($courseorid)) {
2760         if (is_object($courseorid)) {
2761             $course = $courseorid;
2762         } else if ($courseorid == SITEID) {
2763             $course = clone($SITE);
2764         } else {
2765             $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2766         }
2767         if ($cm) {
2768             if ($cm->course != $course->id) {
2769                 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2770             }
2771             // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2772             if (!($cm instanceof cm_info)) {
2773                 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2774                 // db queries so this is not really a performance concern, however it is obviously
2775                 // better if you use get_fast_modinfo to get the cm before calling this.
2776                 $modinfo = get_fast_modinfo($course);
2777                 $cm = $modinfo->get_cm($cm->id);
2778             }
2779             $PAGE->set_cm($cm, $course); // set's up global $COURSE
2780             $PAGE->set_pagelayout('incourse');
2781         } else {
2782             $PAGE->set_course($course); // set's up global $COURSE
2783         }
2784     } else {
2785         // do not touch global $COURSE via $PAGE->set_course(),
2786         // the reasons is we need to be able to call require_login() at any time!!
2787         $course = $SITE;
2788         if ($cm) {
2789             throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2790         }
2791     }
2793     // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2794     // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2795     // risk leading the user back to the AJAX request URL.
2796     if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2797         $setwantsurltome = false;
2798     }
2800     // If the user is not even logged in yet then make sure they are
2801     if (!isloggedin()) {
2802         if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2803             if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2804                 // misconfigured site guest, just redirect to login page
2805                 redirect(get_login_url());
2806                 exit; // never reached
2807             }
2808             $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2809             complete_user_login($guest);
2810             $USER->autologinguest = true;
2811             $SESSION->lang = $lang;
2812         } else {
2813             //NOTE: $USER->site check was obsoleted by session test cookie,
2814             //      $USER->confirmed test is in login/index.php
2815             if ($preventredirect) {
2816                 throw new require_login_exception('You are not logged in');
2817             }
2819             if ($setwantsurltome) {
2820                 $SESSION->wantsurl = qualified_me();
2821             }
2822             if (!empty($_SERVER['HTTP_REFERER'])) {
2823                 $SESSION->fromurl  = $_SERVER['HTTP_REFERER'];
2824             }
2825             redirect(get_login_url());
2826             exit; // never reached
2827         }
2828     }
2830     // loginas as redirection if needed
2831     if ($course->id != SITEID and session_is_loggedinas()) {
2832         if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2833             if ($USER->loginascontext->instanceid != $course->id) {
2834                 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2835             }
2836         }
2837     }
2839     // check whether the user should be changing password (but only if it is REALLY them)
2840     if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2841         $userauth = get_auth_plugin($USER->auth);
2842         if ($userauth->can_change_password() and !$preventredirect) {
2843             if ($setwantsurltome) {
2844                 $SESSION->wantsurl = qualified_me();
2845             }
2846             if ($changeurl = $userauth->change_password_url()) {
2847                 //use plugin custom url
2848                 redirect($changeurl);
2849             } else {
2850                 //use moodle internal method
2851                 if (empty($CFG->loginhttps)) {
2852                     redirect($CFG->wwwroot .'/login/change_password.php');
2853                 } else {
2854                     $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2855                     redirect($wwwroot .'/login/change_password.php');
2856                 }
2857             }
2858         } else {
2859             print_error('nopasswordchangeforced', 'auth');
2860         }
2861     }
2863     // Check that the user account is properly set up
2864     if (user_not_fully_set_up($USER)) {
2865         if ($preventredirect) {
2866             throw new require_login_exception('User not fully set-up');
2867         }
2868         if ($setwantsurltome) {
2869             $SESSION->wantsurl = qualified_me();
2870         }
2871         redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2872     }
2874     // Make sure the USER has a sesskey set up. Used for CSRF protection.
2875     sesskey();
2877     // Do not bother admins with any formalities
2878     if (is_siteadmin()) {
2879         //set accesstime or the user will appear offline which messes up messaging
2880         user_accesstime_log($course->id);
2881         return;
2882     }
2884     // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2885     if (!$USER->policyagreed and !is_siteadmin()) {
2886         if (!empty($CFG->sitepolicy) and !isguestuser()) {
2887             if ($preventredirect) {
2888                 throw new require_login_exception('Policy not agreed');
2889             }
2890             if ($setwantsurltome) {
2891                 $SESSION->wantsurl = qualified_me();
2892             }
2893             redirect($CFG->wwwroot .'/user/policy.php');
2894         } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2895             if ($preventredirect) {
2896                 throw new require_login_exception('Policy not agreed');
2897             }
2898             if ($setwantsurltome) {
2899                 $SESSION->wantsurl = qualified_me();
2900             }
2901             redirect($CFG->wwwroot .'/user/policy.php');
2902         }
2903     }
2905     // Fetch the system context, the course context, and prefetch its child contexts
2906     $sysctx = get_context_instance(CONTEXT_SYSTEM);
2907     $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2908     if ($cm) {
2909         $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2910     } else {
2911         $cmcontext = null;
2912     }
2914     // If the site is currently under maintenance, then print a message
2915     if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2916         if ($preventredirect) {
2917             throw new require_login_exception('Maintenance in progress');
2918         }
2920         print_maintenance_message();
2921     }
2923     // make sure the course itself is not hidden
2924     if ($course->id == SITEID) {
2925         // frontpage can not be hidden
2926     } else {
2927         if (is_role_switched($course->id)) {
2928             // when switching roles ignore the hidden flag - user had to be in course to do the switch
2929         } else {
2930             if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2931                 // originally there was also test of parent category visibility,
2932                 // BUT is was very slow in complex queries involving "my courses"
2933                 // now it is also possible to simply hide all courses user is not enrolled in :-)
2934                 if ($preventredirect) {
2935                     throw new require_login_exception('Course is hidden');
2936                 }
2937                 // We need to override the navigation URL as the course won't have
2938                 // been added to the navigation and thus the navigation will mess up
2939                 // when trying to find it.
2940                 navigation_node::override_active_url(new moodle_url('/'));
2941                 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2942             }
2943         }
2944     }
2946     // is the user enrolled?
2947     if ($course->id == SITEID) {
2948         // everybody is enrolled on the frontpage
2950     } else {
2951         if (session_is_loggedinas()) {
2952             // Make sure the REAL person can access this course first
2953             $realuser = session_get_realuser();
2954             if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2955                 if ($preventredirect) {
2956                     throw new require_login_exception('Invalid course login-as access');
2957                 }
2958                 echo $OUTPUT->header();
2959                 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2960             }
2961         }
2963         $access = false;
2965         if (is_role_switched($course->id)) {
2966             // ok, user had to be inside this course before the switch
2967             $access = true;
2969         } else if (is_viewing($coursecontext, $USER)) {
2970             // ok, no need to mess with enrol
2971             $access = true;
2973         } else {
2974             if (isset($USER->enrol['enrolled'][$course->id])) {
2975                 if ($USER->enrol['enrolled'][$course->id] > time()) {
2976                     $access = true;
2977                     if (isset($USER->enrol['tempguest'][$course->id])) {
2978                         unset($USER->enrol['tempguest'][$course->id]);
2979                         remove_temp_course_roles($coursecontext);
2980                     }
2981                 } else {
2982                     //expired
2983                     unset($USER->enrol['enrolled'][$course->id]);
2984                 }
2985             }
2986             if (isset($USER->enrol['tempguest'][$course->id])) {
2987                 if ($USER->enrol['tempguest'][$course->id] == 0) {
2988                     $access = true;
2989                 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2990                     $access = true;
2991                 } else {
2992                     //expired
2993                     unset($USER->enrol['tempguest'][$course->id]);
2994                     remove_temp_course_roles($coursecontext);
2995                 }
2996             }
2998             if ($access) {
2999                 // cache ok
3000             } else {
3001                 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3002                 if ($until !== false) {
3003                     // active participants may always access, a timestamp in the future, 0 (always) or false.
3004                     if ($until == 0) {
3005                         $until = ENROL_MAX_TIMESTAMP;
3006                     }
3007                     $USER->enrol['enrolled'][$course->id] = $until;
3008                     $access = true;
3010                 } else {
3011                     $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
3012                     $enrols = enrol_get_plugins(true);
3013                     // first ask all enabled enrol instances in course if they want to auto enrol user
3014                     foreach($instances as $instance) {
3015                         if (!isset($enrols[$instance->enrol])) {
3016                             continue;
3017                         }
3018                         // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3019                         $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3020                         if ($until !== false) {
3021                             if ($until == 0) {
3022                                 $until = ENROL_MAX_TIMESTAMP;
3023                             }
3024                             $USER->enrol['enrolled'][$course->id] = $until;
3025                             $access = true;
3026                             break;
3027                         }
3028                     }
3029                     // if not enrolled yet try to gain temporary guest access
3030                     if (!$access) {
3031                         foreach($instances as $instance) {
3032                             if (!isset($enrols[$instance->enrol])) {
3033                                 continue;
3034                             }
3035                             // Get a duration for the guest access, a timestamp in the future or false.
3036                             $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3037                             if ($until !== false and $until > time()) {
3038                                 $USER->enrol['tempguest'][$course->id] = $until;
3039                                 $access = true;
3040                                 break;
3041                             }
3042                         }
3043                     }
3044                 }
3045             }
3046         }
3048         if (!$access) {
3049             if ($preventredirect) {
3050                 throw new require_login_exception('Not enrolled');
3051             }
3052             if ($setwantsurltome) {
3053                 $SESSION->wantsurl = qualified_me();
3054             }
3055             redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3056         }
3057     }
3059     // Check visibility of activity to current user; includes visible flag, groupmembersonly,
3060     // conditional availability, etc
3061     if ($cm && !$cm->uservisible) {
3062         if ($preventredirect) {
3063             throw new require_login_exception('Activity is hidden');
3064         }
3065         redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
3066     }
3068     // Finally access granted, update lastaccess times
3069     user_accesstime_log($course->id);
3073 /**
3074  * This function just makes sure a user is logged out.
3075  *
3076  * @package    core_access
3077  */
3078 function require_logout() {
3079     global $USER;
3081     $params = $USER;
3083     if (isloggedin()) {
3084         add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
3086         $authsequence = get_enabled_auth_plugins(); // auths, in sequence
3087         foreach($authsequence as $authname) {
3088             $authplugin = get_auth_plugin($authname);
3089             $authplugin->prelogout_hook();
3090         }
3091     }
3093     events_trigger('user_logout', $params);
3094     session_get_instance()->terminate_current();
3095     unset($params);
3098 /**
3099  * Weaker version of require_login()
3100  *
3101  * This is a weaker version of {@link require_login()} which only requires login
3102  * when called from within a course rather than the site page, unless
3103  * the forcelogin option is turned on.
3104  * @see require_login()
3105  *
3106  * @package    core_access
3107  * @category   access
3108  *
3109  * @param mixed $courseorid The course object or id in question
3110  * @param bool $autologinguest Allow autologin guests if that is wanted
3111  * @param object $cm Course activity module if known
3112  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3113  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3114  *             in order to keep redirects working properly. MDL-14495
3115  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3116  * @return void
3117  */
3118 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
3119     global $CFG, $PAGE, $SITE;
3120     $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3121           or (!is_object($courseorid) and $courseorid == SITEID);
3122     if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3123         // note: nearly all pages call get_fast_modinfo anyway and it does not make any
3124         // db queries so this is not really a performance concern, however it is obviously
3125         // better if you use get_fast_modinfo to get the cm before calling this.
3126         if (is_object($courseorid)) {
3127             $course = $courseorid;
3128         } else {
3129             $course = clone($SITE);
3130         }
3131         $modinfo = get_fast_modinfo($course);
3132         $cm = $modinfo->get_cm($cm->id);
3133     }
3134     if (!empty($CFG->forcelogin)) {
3135         // login required for both SITE and courses
3136         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3138     } else if ($issite && !empty($cm) and !$cm->uservisible) {
3139         // always login for hidden activities
3140         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3142     } else if ($issite) {
3143               //login for SITE not required
3144         if ($cm and empty($cm->visible)) {
3145             // hidden activities are not accessible without login
3146             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3147         } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3148             // not-logged-in users do not have any group membership
3149             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3150         } else {
3151             // We still need to instatiate PAGE vars properly so that things
3152             // that rely on it like navigation function correctly.
3153             if (!empty($courseorid)) {
3154                 if (is_object($courseorid)) {
3155                     $course = $courseorid;
3156                 } else {
3157                     $course = clone($SITE);
3158                 }
3159                 if ($cm) {
3160                     if ($cm->course != $course->id) {
3161                         throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3162                     }
3163                     $PAGE->set_cm($cm, $course);
3164                     $PAGE->set_pagelayout('incourse');
3165                 } else {
3166                     $PAGE->set_course($course);
3167                 }
3168             } else {
3169                 // If $PAGE->course, and hence $PAGE->context, have not already been set
3170                 // up properly, set them up now.
3171                 $PAGE->set_course($PAGE->course);
3172             }
3173             //TODO: verify conditional activities here
3174             user_accesstime_log(SITEID);
3175             return;
3176         }
3178     } else {
3179         // course login always required
3180         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3181     }
3184 /**
3185  * Require key login. Function terminates with error if key not found or incorrect.
3186  *
3187  * @global object
3188  * @global object
3189  * @global object
3190  * @global object
3191  * @uses NO_MOODLE_COOKIES
3192  * @uses PARAM_ALPHANUM
3193  * @param string $script unique script identifier
3194  * @param int $instance optional instance id
3195  * @return int Instance ID
3196  */
3197 function require_user_key_login($script, $instance=null) {
3198     global $USER, $SESSION, $CFG, $DB;
3200     if (!NO_MOODLE_COOKIES) {
3201         print_error('sessioncookiesdisable');
3202     }
3204 /// extra safety
3205     @session_write_close();
3207     $keyvalue = required_param('key', PARAM_ALPHANUM);
3209     if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3210         print_error('invalidkey');
3211     }
3213     if (!empty($key->validuntil) and $key->validuntil < time()) {
3214         print_error('expiredkey');
3215     }
3217     if ($key->iprestriction) {
3218         $remoteaddr = getremoteaddr(null);
3219         if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3220             print_error('ipmismatch');
3221         }
3222     }
3224     if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
3225         print_error('invaliduserid');
3226     }
3228 /// emulate normal session
3229     enrol_check_plugins($user);
3230     session_set_user($user);
3232 /// note we are not using normal login
3233     if (!defined('USER_KEY_LOGIN')) {
3234         define('USER_KEY_LOGIN', true);
3235     }
3237 /// return instance id - it might be empty
3238     return $key->instance;
3241 /**
3242  * Creates a new private user access key.
3243  *
3244  * @global object
3245  * @param string $script unique target identifier
3246  * @param int $userid
3247  * @param int $instance optional instance id
3248  * @param string $iprestriction optional ip restricted access
3249  * @param timestamp $validuntil key valid only until given data
3250  * @return string access key value
3251  */
3252 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3253     global $DB;
3255     $key = new stdClass();
3256     $key->script        = $script;
3257     $key->userid        = $userid;
3258     $key->instance      = $instance;
3259     $key->iprestriction = $iprestriction;
3260     $key->validuntil    = $validuntil;
3261     $key->timecreated   = time();
3263     $key->value         = md5($userid.'_'.time().random_string(40)); // something long and unique
3264     while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3265         // must be unique
3266         $key->value     = md5($userid.'_'.time().random_string(40));
3267     }
3268     $DB->insert_record('user_private_key', $key);
3269     return $key->value;
3272 /**
3273  * Delete the user's new private user access keys for a particular script.
3274  *
3275  * @global object
3276  * @param string $script unique target identifier
3277  * @param int $userid
3278  * @return void
3279  */
3280 function delete_user_key($script,$userid) {
3281     global $DB;
3282     $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3285 /**
3286  * Gets a private user access key (and creates one if one doesn't exist).
3287  *
3288  * @global object
3289  * @param string $script unique target identifier
3290  * @param int $userid
3291  * @param int $instance optional instance id
3292  * @param string $iprestriction optional ip restricted access
3293  * @param timestamp $validuntil key valid only until given data
3294  * @return string access key value
3295  */
3296 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3297     global $DB;
3299     if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3300                                                          'instance'=>$instance, 'iprestriction'=>$iprestriction,
3301                                                          'validuntil'=>$validuntil))) {
3302         return $key->value;
3303     } else {
3304         return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3305     }
3309 /**
3310  * Modify the user table by setting the currently logged in user's
3311  * last login to now.
3312  *
3313  * @global object
3314  * @global object
3315  * @return bool Always returns true
3316  */
3317 function update_user_login_times() {
3318     global $USER, $DB;
3320     if (isguestuser()) {
3321         // Do not update guest access times/ips for performance.
3322         return true;
3323     }
3325     $now = time();
3327     $user = new stdClass();
3328     $user->id = $USER->id;
3330     // Make sure all users that logged in have some firstaccess.
3331     if ($USER->firstaccess == 0) {
3332         $USER->firstaccess = $user->firstaccess = $now;
3333     }
3335     // Store the previous current as lastlogin.
3336     $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3338     $USER->currentlogin = $user->currentlogin = $now;
3340     // Function user_accesstime_log() may not update immediately, better do it here.
3341     $USER->lastaccess = $user->lastaccess = $now;
3342     $USER->lastip = $user->lastip = getremoteaddr();
3344     $DB->update_record('user', $user);
3345     return true;
3348 /**
3349  * Determines if a user has completed setting up their account.
3350  *
3351  * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3352  * @return bool
3353  */
3354 function user_not_fully_set_up($user) {
3355     if (isguestuser($user)) {
3356         return false;
3357     }
3358     return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3361 /**
3362  * Check whether the user has exceeded the bounce threshold
3363  *
3364  * @global object
3365  * @global object
3366  * @param user $user A {@link $USER} object
3367  * @return bool true=>User has exceeded bounce threshold
3368  */
3369 function over_bounce_threshold($user) {
3370     global $CFG, $DB;
3372     if (empty($CFG->handlebounces)) {
3373         return false;
3374     }
3376     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3377         return false;
3378     }
3380     // set sensible defaults
3381     if (empty($CFG->minbounces)) {
3382         $CFG->minbounces = 10;
3383     }
3384     if (empty($CFG->bounceratio)) {
3385         $CFG->bounceratio = .20;
3386     }
3387     $bouncecount = 0;
3388     $sendcount = 0;
3389     if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3390         $bouncecount = $bounce->value;
3391     }
3392     if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3393         $sendcount = $send->value;
3394     }
3395     return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3398 /**
3399  * Used to increment or reset email sent count
3400  *
3401  * @global object
3402  * @param user $user object containing an id
3403  * @param bool $reset will reset the count to 0
3404  * @return void
3405  */
3406 function set_send_count($user,$reset=false) {
3407     global $DB;
3409     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3410         return;
3411     }
3413     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3414         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3415         $DB->update_record('user_preferences', $pref);
3416     }
3417     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3418         // make a new one
3419         $pref = new stdClass();
3420         $pref->name   = 'email_send_count';
3421         $pref->value  = 1;
3422         $pref->userid = $user->id;
3423         $DB->insert_record('user_preferences', $pref, false);
3424     }
3427 /**
3428  * Increment or reset user's email bounce count
3429  *
3430  * @global object
3431  * @param user $user object containing an id
3432  * @param bool $reset will reset the count to 0
3433  */
3434 function set_bounce_count($user,$reset=false) {
3435     global $DB;
3437     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3438         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3439         $DB->update_record('user_preferences', $pref);
3440     }
3441     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3442         // make a new one
3443         $pref = new stdClass();
3444         $pref->name   = 'email_bounce_count';
3445         $pref->value  = 1;
3446         $pref->userid = $user->id;
3447         $DB->insert_record('user_preferences', $pref, false);
3448     }
3451 /**
3452  * Keeps track of login attempts
3453  *
3454  * @global object
3455  */
3456 function update_login_count() {
3457     global $SESSION;
3459     $max_logins = 10;
3461     if (empty($SESSION->logincount)) {
3462         $SESSION->logincount = 1;
3463     } else {
3464         $SESSION->logincount++;
3465     }
3467     if ($SESSION->logincount > $max_logins) {
3468         unset($SESSION->wantsurl);
3469         print_error('errortoomanylogins');
3470     }
3473 /**
3474  * Resets login attempts
3475  *
3476  * @global object
3477  */
3478 function reset_login_count() {
3479     global $SESSION;
3481     $SESSION->logincount = 0;
3484 /**
3485  * Determines if the currently logged in user is in editing mode.
3486  * Note: originally this function had $userid parameter - it was not usable anyway
3487  *
3488  * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3489  * @todo Deprecated function remove when ready
3490  *
3491  * @global object
3492  * @uses DEBUG_DEVELOPER
3493  * @return bool
3494  */
3495 function isediting() {
3496     global $PAGE;
3497     debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3498     return $PAGE->user_is_editing();
3501 /**
3502  * Determines if the logged in user is currently moving an activity
3503  *
3504  * @global object
3505  * @param int $courseid The id of the course being tested
3506  * @return bool
3507  */
3508 function ismoving($courseid) {
3509     global $USER;
3511     if (!empty($USER->activitycopy)) {
3512         return ($USER->activitycopycourse == $courseid);
3513     }
3514     return false;
3517 /**
3518  * Returns a persons full name
3519  *
3520  * Given an object containing firstname and lastname
3521  * values, this function returns a string with the
3522  * full name of the person.
3523  * The result may depend on system settings
3524  * or language.  'override' will force both names
3525  * to be used even if system settings specify one.
3526  *
3527  * @global object
3528  * @global object
3529  * @param object $user A {@link $USER} object to get full name of
3530  * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3531  * @return string
3532  */
3533 function fullname($user, $override=false) {
3534     global $CFG, $SESSION;
3536     if (!isset($user->firstname) and !isset($user->lastname)) {
3537         return '';
3538     }
3540     if (!$override) {
3541         if (!empty($CFG->forcefirstname)) {
3542             $user->firstname = $CFG->forcefirstname;
3543         }
3544         if (!empty($CFG->forcelastname)) {
3545             $user->lastname = $CFG->forcelastname;
3546         }
3547     }
3549     if (!empty($SESSION->fullnamedisplay)) {
3550         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3551     }
3553     if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3554         return $user->firstname .' '. $user->lastname;
3556     } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3557         return $user->lastname .' '. $user->firstname;
3559     } else if ($CFG->fullnamedisplay == 'firstname') {
3560         if ($override) {
3561             return get_string('fullnamedisplay', '', $user);
3562         } else {
3563             return $user->firstname;
3564         }
3565     }
3567     return get_string('fullnamedisplay', '', $user);
3570 /**
3571  * Checks if current user is shown any extra fields when listing users.
3572  * @param object $context Context
3573  * @param array $already Array of fields that we're going to show anyway
3574  *   so don't bother listing them
3575  * @return array Array of field names from user table, not including anything
3576  *   listed in $already
3577  */
3578 function get_extra_user_fields($context, $already = array()) {
3579     global $CFG;
3581     // Only users with permission get the extra fields
3582     if (!has_capability('moodle/site:viewuseridentity', $context)) {
3583         return array();
3584     }
3586     // Split showuseridentity on comma
3587     if (empty($CFG->showuseridentity)) {
3588         // Explode gives wrong result with empty string
3589         $extra = array();
3590     } else {
3591         $extra =  explode(',', $CFG->showuseridentity);
3592     }
3593     $renumber = false;
3594     foreach ($extra as $key => $field) {
3595         if (in_array($field, $already)) {
3596             unset($extra[$key]);
3597             $renumber = true;
3598         }
3599     }
3600     if ($renumber) {
3601         // For consistency, if entries are removed from array, renumber it
3602         // so they are numbered as you would expect
3603         $extra = array_merge($extra);
3604     }
3605     return $extra;
3608 /**
3609  * If the current user is to be shown extra user fields when listing or
3610  * selecting users, returns a string suitable for including in an SQL select
3611  * clause to retrieve those fields.
3612  * @param object $context Context
3613  * @param string $alias Alias of user table, e.g. 'u' (default none)
3614  * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3615  * @param array $already Array of fields that we're going to include anyway
3616  *   so don't list them (default none)
3617  * @return string Partial SQL select clause, beginning with comma, for example
3618  *   ',u.idnumber,u.department' unless it is blank
3619  */
3620 function get_extra_user_fields_sql($context, $alias='', $prefix='',
3621         $already = array()) {
3622     $fields = get_extra_user_fields($context, $already);
3623     $result = '';
3624     // Add punctuation for alias
3625     if ($alias !== '') {
3626         $alias .= '.';
3627     }
3628     foreach ($fields as $field) {
3629         $result .= ', ' . $alias . $field;
3630         if ($prefix) {
3631             $result .= ' AS ' . $prefix . $field;
3632         }
3633     }
3634     return $result;
3637 /**
3638  * Returns the display name of a field in the user table. Works for most fields
3639  * that are commonly displayed to users.
3640  * @param string $field Field name, e.g. 'phone1'
3641  * @return string Text description taken from language file, e.g. 'Phone number'
3642  */
3643 function get_user_field_name($field) {
3644     // Some fields have language strings which are not the same as field name
3645     switch ($field) {
3646         case 'phone1' : return get_string('phone');
3647     }
3648     // Otherwise just use the same lang string
3649     return get_string($field);
3652 /**
3653  * Returns whether a given authentication plugin exists.
3654  *
3655  * @global object
3656  * @param string $auth Form of authentication to check for. Defaults to the
3657  *        global setting in {@link $CFG}.
3658  * @return boolean Whether the plugin is available.
3659  */
3660 function exists_auth_plugin($auth) {
3661     global $CFG;
3663     if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3664         return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3665     }
3666     return false;