MDL-17477 improve session purging when deleting users
[moodle.git] / lib / moodlelib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * moodlelib.php - Moodle main library
20  *
21  * Main library file of miscellaneous general-purpose Moodle functions.
22  * Other main libraries:
23  *  - weblib.php      - functions that produce web output
24  *  - datalib.php     - functions that access the database
25  *
26  * @package    core
27  * @subpackage lib
28  * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
29  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30  */
32 defined('MOODLE_INTERNAL') || die();
34 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
36 /// Date and time constants ///
37 /**
38  * Time constant - the number of seconds in a year
39  */
40 define('YEARSECS', 31536000);
42 /**
43  * Time constant - the number of seconds in a week
44  */
45 define('WEEKSECS', 604800);
47 /**
48  * Time constant - the number of seconds in a day
49  */
50 define('DAYSECS', 86400);
52 /**
53  * Time constant - the number of seconds in an hour
54  */
55 define('HOURSECS', 3600);
57 /**
58  * Time constant - the number of seconds in a minute
59  */
60 define('MINSECS', 60);
62 /**
63  * Time constant - the number of minutes in a day
64  */
65 define('DAYMINS', 1440);
67 /**
68  * Time constant - the number of minutes in an hour
69  */
70 define('HOURMINS', 60);
72 /// Parameter constants - every call to optional_param(), required_param()  ///
73 /// or clean_param() should have a specified type of parameter.  //////////////
77 /**
78  * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
79  */
80 define('PARAM_ALPHA',    'alpha');
82 /**
83  * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
84  * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
85  */
86 define('PARAM_ALPHAEXT', 'alphaext');
88 /**
89  * PARAM_ALPHANUM - expected numbers and letters only.
90  */
91 define('PARAM_ALPHANUM', 'alphanum');
93 /**
94  * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
95  */
96 define('PARAM_ALPHANUMEXT', 'alphanumext');
98 /**
99  * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
100  */
101 define('PARAM_AUTH',  'auth');
103 /**
104  * PARAM_BASE64 - Base 64 encoded format
105  */
106 define('PARAM_BASE64',   'base64');
108 /**
109  * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
110  */
111 define('PARAM_BOOL',     'bool');
113 /**
114  * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
115  * checked against the list of capabilities in the database.
116  */
117 define('PARAM_CAPABILITY',   'capability');
119 /**
120  * PARAM_CLEANHTML - cleans submitted HTML code. use only for text in HTML format. This cleaning may fix xhtml strictness too.
121  */
122 define('PARAM_CLEANHTML', 'cleanhtml');
124 /**
125  * PARAM_EMAIL - an email address following the RFC
126  */
127 define('PARAM_EMAIL',   'email');
129 /**
130  * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
131  */
132 define('PARAM_FILE',   'file');
134 /**
135  * PARAM_FLOAT - a real/floating point number.
136  */
137 define('PARAM_FLOAT',  'float');
139 /**
140  * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
141  */
142 define('PARAM_HOST',     'host');
144 /**
145  * PARAM_INT - integers only, use when expecting only numbers.
146  */
147 define('PARAM_INT',      'int');
149 /**
150  * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
151  */
152 define('PARAM_LANG',  'lang');
154 /**
155  * 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!)
156  */
157 define('PARAM_LOCALURL', 'localurl');
159 /**
160  * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
161  */
162 define('PARAM_NOTAGS',   'notags');
164 /**
165  * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
166  * note: the leading slash is not removed, window drive letter is not allowed
167  */
168 define('PARAM_PATH',     'path');
170 /**
171  * PARAM_PEM - Privacy Enhanced Mail format
172  */
173 define('PARAM_PEM',      'pem');
175 /**
176  * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
177  */
178 define('PARAM_PERMISSION',   'permission');
180 /**
181  * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
182  */
183 define('PARAM_RAW', 'raw');
185 /**
186  * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
187  */
188 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
190 /**
191  * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
192  */
193 define('PARAM_SAFEDIR',  'safedir');
195 /**
196  * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
197  */
198 define('PARAM_SAFEPATH',  'safepath');
200 /**
201  * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9.  Numbers and comma only.
202  */
203 define('PARAM_SEQUENCE',  'sequence');
205 /**
206  * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
207  */
208 define('PARAM_TAG',   'tag');
210 /**
211  * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
212  */
213 define('PARAM_TAGLIST',   'taglist');
215 /**
216  * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
217  */
218 define('PARAM_TEXT',  'text');
220 /**
221  * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
222  */
223 define('PARAM_THEME',  'theme');
225 /**
226  * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
227  */
228 define('PARAM_URL',      'url');
230 /**
231  * 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!!
232  */
233 define('PARAM_USERNAME',    'username');
235 /**
236  * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
237  */
238 define('PARAM_STRINGID',    'stringid');
240 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE  /////
241 /**
242  * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
243  * It was one of the first types, that is why it is abused so much ;-)
244  * @deprecated since 2.0
245  */
246 define('PARAM_CLEAN',    'clean');
248 /**
249  * PARAM_INTEGER - deprecated alias for PARAM_INT
250  */
251 define('PARAM_INTEGER',  'int');
253 /**
254  * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
255  */
256 define('PARAM_NUMBER',  'float');
258 /**
259  * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
260  * NOTE: originally alias for PARAM_APLHA
261  */
262 define('PARAM_ACTION',   'alphanumext');
264 /**
265  * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
266  * NOTE: originally alias for PARAM_APLHA
267  */
268 define('PARAM_FORMAT',   'alphanumext');
270 /**
271  * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
272  */
273 define('PARAM_MULTILANG',  'text');
275 /**
276  * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
277  * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
278  * America/Port-au-Prince)
279  */
280 define('PARAM_TIMEZONE', 'timezone');
282 /**
283  * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
284  */
285 define('PARAM_CLEANFILE', 'file');
287 /// Web Services ///
289 /**
290  * VALUE_REQUIRED - if the parameter is not supplied, there is an error
291  */
292 define('VALUE_REQUIRED', 1);
294 /**
295  * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
296  */
297 define('VALUE_OPTIONAL', 2);
299 /**
300  * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
301  */
302 define('VALUE_DEFAULT', 0);
304 /**
305  * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
306  */
307 define('NULL_NOT_ALLOWED', false);
309 /**
310  * NULL_ALLOWED - the parameter can be set to null in the database
311  */
312 define('NULL_ALLOWED', true);
314 /// Page types ///
315 /**
316  * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
317  */
318 define('PAGE_COURSE_VIEW', 'course-view');
320 /** Get remote addr constant */
321 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
322 /** Get remote addr constant */
323 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
325 /// Blog access level constant declaration ///
326 define ('BLOG_USER_LEVEL', 1);
327 define ('BLOG_GROUP_LEVEL', 2);
328 define ('BLOG_COURSE_LEVEL', 3);
329 define ('BLOG_SITE_LEVEL', 4);
330 define ('BLOG_GLOBAL_LEVEL', 5);
333 ///Tag constants///
334 /**
335  * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
336  * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
337  * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
338  *
339  * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
340  */
341 define('TAG_MAX_LENGTH', 50);
343 /// Password policy constants ///
344 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
345 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
346 define ('PASSWORD_DIGITS', '0123456789');
347 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
349 /// Feature constants ///
350 // Used for plugin_supports() to report features that are, or are not, supported by a module.
352 /** True if module can provide a grade */
353 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
354 /** True if module supports outcomes */
355 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
357 /** True if module has code to track whether somebody viewed it */
358 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
359 /** True if module has custom completion rules */
360 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
362 /** True if module has no 'view' page (like label) */
363 define('FEATURE_NO_VIEW_LINK', 'viewlink');
364 /** True if module supports outcomes */
365 define('FEATURE_IDNUMBER', 'idnumber');
366 /** True if module supports groups */
367 define('FEATURE_GROUPS', 'groups');
368 /** True if module supports groupings */
369 define('FEATURE_GROUPINGS', 'groupings');
370 /** True if module supports groupmembersonly */
371 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
373 /** Type of module */
374 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
375 /** True if module supports intro editor */
376 define('FEATURE_MOD_INTRO', 'mod_intro');
377 /** True if module has default completion */
378 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
380 define('FEATURE_COMMENT', 'comment');
382 define('FEATURE_RATE', 'rate');
383 /** True if module supports backup/restore of moodle2 format */
384 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
386 /** Unspecified module archetype */
387 define('MOD_ARCHETYPE_OTHER', 0);
388 /** Resource-like type module */
389 define('MOD_ARCHETYPE_RESOURCE', 1);
390 /** Assignment module archetype */
391 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
393 /**
394  * Security token used for allowing access
395  * from external application such as web services.
396  * Scripts do not use any session, performance is relatively
397  * low because we need to load access info in each request.
398  * Scripts are executed in parallel.
399  */
400 define('EXTERNAL_TOKEN_PERMANENT', 0);
402 /**
403  * Security token used for allowing access
404  * of embedded applications, the code is executed in the
405  * active user session. Token is invalidated after user logs out.
406  * Scripts are executed serially - normal session locking is used.
407  */
408 define('EXTERNAL_TOKEN_EMBEDDED', 1);
410 /**
411  * The home page should be the site home
412  */
413 define('HOMEPAGE_SITE', 0);
414 /**
415  * The home page should be the users my page
416  */
417 define('HOMEPAGE_MY', 1);
418 /**
419  * The home page can be chosen by the user
420  */
421 define('HOMEPAGE_USER', 2);
423 /**
424  * Hub directory url (should be moodle.org)
425  */
426 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
429 /**
430  * Moodle.org url (should be moodle.org)
431  */
432 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
434 /**
435  * Moodle mobile app service name
436  */
437 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
439 /// PARAMETER HANDLING ////////////////////////////////////////////////////
441 /**
442  * Returns a particular value for the named variable, taken from
443  * POST or GET.  If the parameter doesn't exist then an error is
444  * thrown because we require this variable.
445  *
446  * This function should be used to initialise all required values
447  * in a script that are based on parameters.  Usually it will be
448  * used like this:
449  *    $id = required_param('id', PARAM_INT);
450  *
451  * Please note the $type parameter is now required,
452  * for now PARAM_CLEAN is used for backwards compatibility only.
453  *
454  * @param string $parname the name of the page parameter we want
455  * @param string $type expected type of parameter
456  * @return mixed
457  */
458 function required_param($parname, $type) {
459     if (!isset($type)) {
460         debugging('required_param() requires $type to be specified.');
461         $type = PARAM_CLEAN; // for now let's use this deprecated type
462     }
463     if (isset($_POST[$parname])) {       // POST has precedence
464         $param = $_POST[$parname];
465     } else if (isset($_GET[$parname])) {
466         $param = $_GET[$parname];
467     } else {
468         print_error('missingparam', '', '', $parname);
469     }
471     return clean_param($param, $type);
474 /**
475  * Returns a particular value for the named variable, taken from
476  * POST or GET, otherwise returning a given default.
477  *
478  * This function should be used to initialise all optional values
479  * in a script that are based on parameters.  Usually it will be
480  * used like this:
481  *    $name = optional_param('name', 'Fred', PARAM_TEXT);
482  *
483  * Please note $default and $type parameters are now required,
484  * for now PARAM_CLEAN is used for backwards compatibility only.
485  *
486  * @param string $parname the name of the page parameter we want
487  * @param mixed  $default the default value to return if nothing is found
488  * @param string $type expected type of parameter
489  * @return mixed
490  */
491 function optional_param($parname, $default, $type) {
492     if (!isset($type)) {
493         debugging('optional_param() requires $default and $type to be specified.');
494         $type = PARAM_CLEAN; // for now let's use this deprecated type
495     }
496     if (!isset($default)) {
497         $default = null;
498     }
500     if (isset($_POST[$parname])) {       // POST has precedence
501         $param = $_POST[$parname];
502     } else if (isset($_GET[$parname])) {
503         $param = $_GET[$parname];
504     } else {
505         return $default;
506     }
508     return clean_param($param, $type);
511 /**
512  * Strict validation of parameter values, the values are only converted
513  * to requested PHP type. Internally it is using clean_param, the values
514  * before and after cleaning must be equal - otherwise
515  * an invalid_parameter_exception is thrown.
516  * Objects and classes are not accepted.
517  *
518  * @param mixed $param
519  * @param int $type PARAM_ constant
520  * @param bool $allownull are nulls valid value?
521  * @param string $debuginfo optional debug information
522  * @return mixed the $param value converted to PHP type or invalid_parameter_exception
523  */
524 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
525     if (is_null($param)) {
526         if ($allownull == NULL_ALLOWED) {
527             return null;
528         } else {
529             throw new invalid_parameter_exception($debuginfo);
530         }
531     }
532     if (is_array($param) or is_object($param)) {
533         throw new invalid_parameter_exception($debuginfo);
534     }
536     $cleaned = clean_param($param, $type);
537     if ((string)$param !== (string)$cleaned) {
538         // conversion to string is usually lossless
539         throw new invalid_parameter_exception($debuginfo);
540     }
542     return $cleaned;
545 /**
546  * Used by {@link optional_param()} and {@link required_param()} to
547  * clean the variables and/or cast to specific types, based on
548  * an options field.
549  * <code>
550  * $course->format = clean_param($course->format, PARAM_ALPHA);
551  * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
552  * </code>
553  *
554  * @param mixed $param the variable we are cleaning
555  * @param int $type expected format of param after cleaning.
556  * @return mixed
557  */
558 function clean_param($param, $type) {
560     global $CFG;
562     if (is_array($param)) {              // Let's loop
563         $newparam = array();
564         foreach ($param as $key => $value) {
565             $newparam[$key] = clean_param($value, $type);
566         }
567         return $newparam;
568     }
570     switch ($type) {
571         case PARAM_RAW:          // no cleaning at all
572             $param = fix_utf8($param);
573             return $param;
575         case PARAM_RAW_TRIMMED:         // no cleaning, but strip leading and trailing whitespace.
576             $param = fix_utf8($param);
577             return trim($param);
579         case PARAM_CLEAN:        // General HTML cleaning, try to use more specific type if possible
580             // this is deprecated!, please use more specific type instead
581             if (is_numeric($param)) {
582                 return $param;
583             }
584             $param = fix_utf8($param);
585             return clean_text($param);     // Sweep for scripts, etc
587         case PARAM_CLEANHTML:    // clean html fragment
588             $param = fix_utf8($param);
589             $param = clean_text($param, FORMAT_HTML);     // Sweep for scripts, etc
590             return trim($param);
592         case PARAM_INT:
593             return (int)$param;  // Convert to integer
595         case PARAM_FLOAT:
596         case PARAM_NUMBER:
597             return (float)$param;  // Convert to float
599         case PARAM_ALPHA:        // Remove everything not a-z
600             return preg_replace('/[^a-zA-Z]/i', '', $param);
602         case PARAM_ALPHAEXT:     // Remove everything not a-zA-Z_- (originally allowed "/" too)
603             return preg_replace('/[^a-zA-Z_-]/i', '', $param);
605         case PARAM_ALPHANUM:     // Remove everything not a-zA-Z0-9
606             return preg_replace('/[^A-Za-z0-9]/i', '', $param);
608         case PARAM_ALPHANUMEXT:     // Remove everything not a-zA-Z0-9_-
609             return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
611         case PARAM_SEQUENCE:     // Remove everything not 0-9,
612             return preg_replace('/[^0-9,]/i', '', $param);
614         case PARAM_BOOL:         // Convert to 1 or 0
615             $tempstr = strtolower($param);
616             if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
617                 $param = 1;
618             } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
619                 $param = 0;
620             } else {
621                 $param = empty($param) ? 0 : 1;
622             }
623             return $param;
625         case PARAM_NOTAGS:       // Strip all tags
626             $param = fix_utf8($param);
627             return strip_tags($param);
629         case PARAM_TEXT:    // leave only tags needed for multilang
630             $param = fix_utf8($param);
631             // if the multilang syntax is not correct we strip all tags
632             // because it would break xhtml strict which is required for accessibility standards
633             // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
634             do {
635                 if (strpos($param, '</lang>') !== false) {
636                     // old and future mutilang syntax
637                     $param = strip_tags($param, '<lang>');
638                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
639                         break;
640                     }
641                     $open = false;
642                     foreach ($matches[0] as $match) {
643                         if ($match === '</lang>') {
644                             if ($open) {
645                                 $open = false;
646                                 continue;
647                             } else {
648                                 break 2;
649                             }
650                         }
651                         if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
652                             break 2;
653                         } else {
654                             $open = true;
655                         }
656                     }
657                     if ($open) {
658                         break;
659                     }
660                     return $param;
662                 } else if (strpos($param, '</span>') !== false) {
663                     // current problematic multilang syntax
664                     $param = strip_tags($param, '<span>');
665                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
666                         break;
667                     }
668                     $open = false;
669                     foreach ($matches[0] as $match) {
670                         if ($match === '</span>') {
671                             if ($open) {
672                                 $open = false;
673                                 continue;
674                             } else {
675                                 break 2;
676                             }
677                         }
678                         if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
679                             break 2;
680                         } else {
681                             $open = true;
682                         }
683                     }
684                     if ($open) {
685                         break;
686                     }
687                     return $param;
688                 }
689             } while (false);
690             // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
691             return strip_tags($param);
693         case PARAM_SAFEDIR:      // Remove everything not a-zA-Z0-9_-
694             return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
696         case PARAM_SAFEPATH:     // Remove everything not a-zA-Z0-9/_-
697             return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
699         case PARAM_FILE:         // Strip all suspicious characters from filename
700             $param = fix_utf8($param);
701             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
702             $param = preg_replace('~\.\.+~', '', $param);
703             if ($param === '.') {
704                 $param = '';
705             }
706             return $param;
708         case PARAM_PATH:         // Strip all suspicious characters from file path
709             $param = fix_utf8($param);
710             $param = str_replace('\\', '/', $param);
711             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
712             $param = preg_replace('~\.\.+~', '', $param);
713             $param = preg_replace('~//+~', '/', $param);
714             return preg_replace('~/(\./)+~', '/', $param);
716         case PARAM_HOST:         // allow FQDN or IPv4 dotted quad
717             $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
718             // match ipv4 dotted quad
719             if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
720                 // confirm values are ok
721                 if ( $match[0] > 255
722                      || $match[1] > 255
723                      || $match[3] > 255
724                      || $match[4] > 255 ) {
725                     // hmmm, what kind of dotted quad is this?
726                     $param = '';
727                 }
728             } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
729                        && !preg_match('/^[\.-]/',  $param) // no leading dots/hyphens
730                        && !preg_match('/[\.-]$/',  $param) // no trailing dots/hyphens
731                        ) {
732                 // all is ok - $param is respected
733             } else {
734                 // all is not ok...
735                 $param='';
736             }
737             return $param;
739         case PARAM_URL:          // allow safe ftp, http, mailto urls
740             $param = fix_utf8($param);
741             include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
742             if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
743                 // all is ok, param is respected
744             } else {
745                 $param =''; // not really ok
746             }
747             return $param;
749         case PARAM_LOCALURL:     // allow http absolute, root relative and relative URLs within wwwroot
750             $param = clean_param($param, PARAM_URL);
751             if (!empty($param)) {
752                 if (preg_match(':^/:', $param)) {
753                     // root-relative, ok!
754                 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
755                     // absolute, and matches our wwwroot
756                 } else {
757                     // relative - let's make sure there are no tricks
758                     if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
759                         // looks ok.
760                     } else {
761                         $param = '';
762                     }
763                 }
764             }
765             return $param;
767         case PARAM_PEM:
768             $param = trim($param);
769             // PEM formatted strings may contain letters/numbers and the symbols
770             // forward slash: /
771             // plus sign:     +
772             // equal sign:    =
773             // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
774             if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
775                 list($wholething, $body) = $matches;
776                 unset($wholething, $matches);
777                 $b64 = clean_param($body, PARAM_BASE64);
778                 if (!empty($b64)) {
779                     return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
780                 } else {
781                     return '';
782                 }
783             }
784             return '';
786         case PARAM_BASE64:
787             if (!empty($param)) {
788                 // PEM formatted strings may contain letters/numbers and the symbols
789                 // forward slash: /
790                 // plus sign:     +
791                 // equal sign:    =
792                 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
793                     return '';
794                 }
795                 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
796                 // Each line of base64 encoded data must be 64 characters in
797                 // length, except for the last line which may be less than (or
798                 // equal to) 64 characters long.
799                 for ($i=0, $j=count($lines); $i < $j; $i++) {
800                     if ($i + 1 == $j) {
801                         if (64 < strlen($lines[$i])) {
802                             return '';
803                         }
804                         continue;
805                     }
807                     if (64 != strlen($lines[$i])) {
808                         return '';
809                     }
810                 }
811                 return implode("\n",$lines);
812             } else {
813                 return '';
814             }
816         case PARAM_TAG:
817             $param = fix_utf8($param);
818             // Please note it is not safe to use the tag name directly anywhere,
819             // it must be processed with s(), urlencode() before embedding anywhere.
820             // remove some nasties
821             $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
822             //convert many whitespace chars into one
823             $param = preg_replace('/\s+/', ' ', $param);
824             $textlib = textlib_get_instance();
825             $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
826             return $param;
828         case PARAM_TAGLIST:
829             $param = fix_utf8($param);
830             $tags = explode(',', $param);
831             $result = array();
832             foreach ($tags as $tag) {
833                 $res = clean_param($tag, PARAM_TAG);
834                 if ($res !== '') {
835                     $result[] = $res;
836                 }
837             }
838             if ($result) {
839                 return implode(',', $result);
840             } else {
841                 return '';
842             }
844         case PARAM_CAPABILITY:
845             if (get_capability_info($param)) {
846                 return $param;
847             } else {
848                 return '';
849             }
851         case PARAM_PERMISSION:
852             $param = (int)$param;
853             if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
854                 return $param;
855             } else {
856                 return CAP_INHERIT;
857             }
859         case PARAM_AUTH:
860             $param = clean_param($param, PARAM_SAFEDIR);
861             if (exists_auth_plugin($param)) {
862                 return $param;
863             } else {
864                 return '';
865             }
867         case PARAM_LANG:
868             $param = clean_param($param, PARAM_SAFEDIR);
869             if (get_string_manager()->translation_exists($param)) {
870                 return $param;
871             } else {
872                 return ''; // Specified language is not installed or param malformed
873             }
875         case PARAM_THEME:
876             $param = clean_param($param, PARAM_SAFEDIR);
877             if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
878                 return $param;
879             } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
880                 return $param;
881             } else {
882                 return '';  // Specified theme is not installed
883             }
885         case PARAM_USERNAME:
886             $param = fix_utf8($param);
887             $param = str_replace(" " , "", $param);
888             $param = moodle_strtolower($param);  // Convert uppercase to lowercase MDL-16919
889             if (empty($CFG->extendedusernamechars)) {
890                 // regular expression, eliminate all chars EXCEPT:
891                 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
892                 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
893             }
894             return $param;
896         case PARAM_EMAIL:
897             $param = fix_utf8($param);
898             if (validate_email($param)) {
899                 return $param;
900             } else {
901                 return '';
902             }
904         case PARAM_STRINGID:
905             if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
906                 return $param;
907             } else {
908                 return '';
909             }
911         case PARAM_TIMEZONE:    //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
912             $param = fix_utf8($param);
913             $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
914             if (preg_match($timezonepattern, $param)) {
915                 return $param;
916             } else {
917                 return '';
918             }
920         default:                 // throw error, switched parameters in optional_param or another serious problem
921             print_error("unknownparamtype", '', '', $type);
922     }
925 /**
926  * Makes sure the data is using valid utf8, invalid characters are discarded.
927  *
928  * Note: this function is not intended for full objects with methods and private properties.
929  *
930  * @param mixed $value
931  * @return mixed with proper utf-8 encoding
932  */
933 function fix_utf8($value) {
934     if (is_null($value) or $value === '') {
935         return $value;
937     } else if (is_string($value)) {
938         if ((string)(int)$value === $value) {
939             // shortcut
940             return $value;
941         }
942         return iconv('UTF-8', 'UTF-8//IGNORE', $value);
944     } else if (is_array($value)) {
945         foreach ($value as $k=>$v) {
946             $value[$k] = fix_utf8($v);
947         }
948         return $value;
950     } else if (is_object($value)) {
951         $value = clone($value); // do not modify original
952         foreach ($value as $k=>$v) {
953             $value->$k = fix_utf8($v);
954         }
955         return $value;
957     } else {
958         // this is some other type, no utf-8 here
959         return $value;
960     }
963 /**
964  * Return true if given value is integer or string with integer value
965  *
966  * @param mixed $value String or Int
967  * @return bool true if number, false if not
968  */
969 function is_number($value) {
970     if (is_int($value)) {
971         return true;
972     } else if (is_string($value)) {
973         return ((string)(int)$value) === $value;
974     } else {
975         return false;
976     }
979 /**
980  * Returns host part from url
981  * @param string $url full url
982  * @return string host, null if not found
983  */
984 function get_host_from_url($url) {
985     preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
986     if ($matches) {
987         return $matches[1];
988     }
989     return null;
992 /**
993  * Tests whether anything was returned by text editor
994  *
995  * This function is useful for testing whether something you got back from
996  * the HTML editor actually contains anything. Sometimes the HTML editor
997  * appear to be empty, but actually you get back a <br> tag or something.
998  *
999  * @param string $string a string containing HTML.
1000  * @return boolean does the string contain any actual content - that is text,
1001  * images, objects, etc.
1002  */
1003 function html_is_blank($string) {
1004     return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1007 /**
1008  * Set a key in global configuration
1009  *
1010  * Set a key/value pair in both this session's {@link $CFG} global variable
1011  * and in the 'config' database table for future sessions.
1012  *
1013  * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1014  * In that case it doesn't affect $CFG.
1015  *
1016  * A NULL value will delete the entry.
1017  *
1018  * @global object
1019  * @global object
1020  * @param string $name the key to set
1021  * @param string $value the value to set (without magic quotes)
1022  * @param string $plugin (optional) the plugin scope, default NULL
1023  * @return bool true or exception
1024  */
1025 function set_config($name, $value, $plugin=NULL) {
1026     global $CFG, $DB;
1028     if (empty($plugin)) {
1029         if (!array_key_exists($name, $CFG->config_php_settings)) {
1030             // So it's defined for this invocation at least
1031             if (is_null($value)) {
1032                 unset($CFG->$name);
1033             } else {
1034                 $CFG->$name = (string)$value; // settings from db are always strings
1035             }
1036         }
1038         if ($DB->get_field('config', 'name', array('name'=>$name))) {
1039             if ($value === null) {
1040                 $DB->delete_records('config', array('name'=>$name));
1041             } else {
1042                 $DB->set_field('config', 'value', $value, array('name'=>$name));
1043             }
1044         } else {
1045             if ($value !== null) {
1046                 $config = new stdClass();
1047                 $config->name  = $name;
1048                 $config->value = $value;
1049                 $DB->insert_record('config', $config, false);
1050             }
1051         }
1053     } else { // plugin scope
1054         if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1055             if ($value===null) {
1056                 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1057             } else {
1058                 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1059             }
1060         } else {
1061             if ($value !== null) {
1062                 $config = new stdClass();
1063                 $config->plugin = $plugin;
1064                 $config->name   = $name;
1065                 $config->value  = $value;
1066                 $DB->insert_record('config_plugins', $config, false);
1067             }
1068         }
1069     }
1071     return true;
1074 /**
1075  * Get configuration values from the global config table
1076  * or the config_plugins table.
1077  *
1078  * If called with one parameter, it will load all the config
1079  * variables for one plugin, and return them as an object.
1080  *
1081  * If called with 2 parameters it will return a string single
1082  * value or false if the value is not found.
1083  *
1084  * @param string $plugin full component name
1085  * @param string $name default NULL
1086  * @return mixed hash-like object or single value, return false no config found
1087  */
1088 function get_config($plugin, $name = NULL) {
1089     global $CFG, $DB;
1091     // normalise component name
1092     if ($plugin === 'moodle' or $plugin === 'core') {
1093         $plugin = NULL;
1094     }
1096     if (!empty($name)) { // the user is asking for a specific value
1097         if (!empty($plugin)) {
1098             if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1099                 // setting forced in config file
1100                 return $CFG->forced_plugin_settings[$plugin][$name];
1101             } else {
1102                 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1103             }
1104         } else {
1105             if (array_key_exists($name, $CFG->config_php_settings)) {
1106                 // setting force in config file
1107                 return $CFG->config_php_settings[$name];
1108             } else {
1109                 return $DB->get_field('config', 'value', array('name'=>$name));
1110             }
1111         }
1112     }
1114     // the user is after a recordset
1115     if ($plugin) {
1116         $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1117         if (isset($CFG->forced_plugin_settings[$plugin])) {
1118             foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1119                 if (is_null($v) or is_array($v) or is_object($v)) {
1120                     // we do not want any extra mess here, just real settings that could be saved in db
1121                     unset($localcfg[$n]);
1122                 } else {
1123                     //convert to string as if it went through the DB
1124                     $localcfg[$n] = (string)$v;
1125                 }
1126             }
1127         }
1128         if ($localcfg) {
1129             return (object)$localcfg;
1130         } else {
1131             return null;
1132         }
1134     } else {
1135         // this part is not really used any more, but anyway...
1136         $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1137         foreach($CFG->config_php_settings as $n=>$v) {
1138             if (is_null($v) or is_array($v) or is_object($v)) {
1139                 // we do not want any extra mess here, just real settings that could be saved in db
1140                 unset($localcfg[$n]);
1141             } else {
1142                 //convert to string as if it went through the DB
1143                 $localcfg[$n] = (string)$v;
1144             }
1145         }
1146         return (object)$localcfg;
1147     }
1150 /**
1151  * Removes a key from global configuration
1152  *
1153  * @param string $name the key to set
1154  * @param string $plugin (optional) the plugin scope
1155  * @global object
1156  * @return boolean whether the operation succeeded.
1157  */
1158 function unset_config($name, $plugin=NULL) {
1159     global $CFG, $DB;
1161     if (empty($plugin)) {
1162         unset($CFG->$name);
1163         $DB->delete_records('config', array('name'=>$name));
1164     } else {
1165         $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1166     }
1168     return true;
1171 /**
1172  * Remove all the config variables for a given plugin.
1173  *
1174  * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1175  * @return boolean whether the operation succeeded.
1176  */
1177 function unset_all_config_for_plugin($plugin) {
1178     global $DB;
1179     $DB->delete_records('config_plugins', array('plugin' => $plugin));
1180     $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
1181     return true;
1184 /**
1185  * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1186  *
1187  * All users are verified if they still have the necessary capability.
1188  *
1189  * @param string $value the value of the config setting.
1190  * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1191  * @param bool $include admins, include administrators
1192  * @return array of user objects.
1193  */
1194 function get_users_from_config($value, $capability, $includeadmins = true) {
1195     global $CFG, $DB;
1197     if (empty($value) or $value === '$@NONE@$') {
1198         return array();
1199     }
1201     // we have to make sure that users still have the necessary capability,
1202     // it should be faster to fetch them all first and then test if they are present
1203     // instead of validating them one-by-one
1204     $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1205     if ($includeadmins) {
1206         $admins = get_admins();
1207         foreach ($admins as $admin) {
1208             $users[$admin->id] = $admin;
1209         }
1210     }
1212     if ($value === '$@ALL@$') {
1213         return $users;
1214     }
1216     $result = array(); // result in correct order
1217     $allowed = explode(',', $value);
1218     foreach ($allowed as $uid) {
1219         if (isset($users[$uid])) {
1220             $user = $users[$uid];
1221             $result[$user->id] = $user;
1222         }
1223     }
1225     return $result;
1229 /**
1230  * Invalidates browser caches and cached data in temp
1231  * @return void
1232  */
1233 function purge_all_caches() {
1234     global $CFG;
1236     reset_text_filters_cache();
1237     js_reset_all_caches();
1238     theme_reset_all_caches();
1239     get_string_manager()->reset_caches();
1241     // purge all other caches: rss, simplepie, etc.
1242     remove_dir($CFG->dataroot.'/cache', true);
1244     // make sure cache dir is writable, throws exception if not
1245     make_upload_directory('cache');
1247     // hack: this script may get called after the purifier was initialised,
1248     // but we do not want to verify repeatedly this exists in each call
1249     make_upload_directory('cache/htmlpurifier');
1251     clearstatcache();
1254 /**
1255  * Get volatile flags
1256  *
1257  * @param string $type
1258  * @param int    $changedsince default null
1259  * @return records array
1260  */
1261 function get_cache_flags($type, $changedsince=NULL) {
1262     global $DB;
1264     $params = array('type'=>$type, 'expiry'=>time());
1265     $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1266     if ($changedsince !== NULL) {
1267         $params['changedsince'] = $changedsince;
1268         $sqlwhere .= " AND timemodified > :changedsince";
1269     }
1270     $cf = array();
1272     if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1273         foreach ($flags as $flag) {
1274             $cf[$flag->name] = $flag->value;
1275         }
1276     }
1277     return $cf;
1280 /**
1281  * Get volatile flags
1282  *
1283  * @param string $type
1284  * @param string $name
1285  * @param int    $changedsince default null
1286  * @return records array
1287  */
1288 function get_cache_flag($type, $name, $changedsince=NULL) {
1289     global $DB;
1291     $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1293     $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1294     if ($changedsince !== NULL) {
1295         $params['changedsince'] = $changedsince;
1296         $sqlwhere .= " AND timemodified > :changedsince";
1297     }
1299     return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1302 /**
1303  * Set a volatile flag
1304  *
1305  * @param string $type the "type" namespace for the key
1306  * @param string $name the key to set
1307  * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1308  * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1309  * @return bool Always returns true
1310  */
1311 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1312     global $DB;
1314     $timemodified = time();
1315     if ($expiry===NULL || $expiry < $timemodified) {
1316         $expiry = $timemodified + 24 * 60 * 60;
1317     } else {
1318         $expiry = (int)$expiry;
1319     }
1321     if ($value === NULL) {
1322         unset_cache_flag($type,$name);
1323         return true;
1324     }
1326     if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1327         if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1328             return true; //no need to update; helps rcache too
1329         }
1330         $f->value        = $value;
1331         $f->expiry       = $expiry;
1332         $f->timemodified = $timemodified;
1333         $DB->update_record('cache_flags', $f);
1334     } else {
1335         $f = new stdClass();
1336         $f->flagtype     = $type;
1337         $f->name         = $name;
1338         $f->value        = $value;
1339         $f->expiry       = $expiry;
1340         $f->timemodified = $timemodified;
1341         $DB->insert_record('cache_flags', $f);
1342     }
1343     return true;
1346 /**
1347  * Removes a single volatile flag
1348  *
1349  * @global object
1350  * @param string $type the "type" namespace for the key
1351  * @param string $name the key to set
1352  * @return bool
1353  */
1354 function unset_cache_flag($type, $name) {
1355     global $DB;
1356     $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1357     return true;
1360 /**
1361  * Garbage-collect volatile flags
1362  *
1363  * @return bool Always returns true
1364  */
1365 function gc_cache_flags() {
1366     global $DB;
1367     $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1368     return true;
1371 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1373 /**
1374  * Refresh user preference cache. This is used most often for $USER
1375  * object that is stored in session, but it also helps with performance in cron script.
1376  *
1377  * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1378  *
1379  * @param stdClass $user user object, preferences are preloaded into ->preference property
1380  * @param int $cachelifetime cache life time on the current page (ins seconds)
1381  * @return void
1382  */
1383 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1384     global $DB;
1385     static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1387     if (!isset($user->id)) {
1388         throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1389     }
1391     if (empty($user->id) or isguestuser($user->id)) {
1392         // No permanent storage for not-logged-in users and guest
1393         if (!isset($user->preference)) {
1394             $user->preference = array();
1395         }
1396         return;
1397     }
1399     $timenow = time();
1401     if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1402         // Already loaded at least once on this page. Are we up to date?
1403         if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1404             // no need to reload - we are on the same page and we loaded prefs just a moment ago
1405             return;
1407         } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1408             // no change since the lastcheck on this page
1409             $user->preference['_lastloaded'] = $timenow;
1410             return;
1411         }
1412     }
1414     // OK, so we have to reload all preferences
1415     $loadedusers[$user->id] = true;
1416     $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1417     $user->preference['_lastloaded'] = $timenow;
1420 /**
1421  * Called from set/delete_user_preferences, so that the prefs can
1422  * be correctly reloaded in different sessions.
1423  *
1424  * NOTE: internal function, do not call from other code.
1425  *
1426  * @param integer $userid the user whose prefs were changed.
1427  * @return void
1428  */
1429 function mark_user_preferences_changed($userid) {
1430     global $CFG;
1432     if (empty($userid) or isguestuser($userid)) {
1433         // no cache flags for guest and not-logged-in users
1434         return;
1435     }
1437     set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1440 /**
1441  * Sets a preference for the specified user.
1442  *
1443  * If user object submitted, 'preference' property contains the preferences cache.
1444  *
1445  * @param string $name The key to set as preference for the specified user
1446  * @param string $value The value to set for the $name key in the specified user's record,
1447  *                      null means delete current value
1448  * @param stdClass|int $user A moodle user object or id, null means current user
1449  * @return bool always true or exception
1450  */
1451 function set_user_preference($name, $value, $user = null) {
1452     global $USER, $DB;
1454     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1455         throw new coding_exception('Invalid preference name in set_user_preference() call');
1456     }
1458     if (is_null($value)) {
1459         // null means delete current
1460         return unset_user_preference($name, $user);
1461     } else if (is_object($value)) {
1462         throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1463     } else if (is_array($value)) {
1464         throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1465     }
1466     $value = (string)$value;
1468     if (is_null($user)) {
1469         $user = $USER;
1470     } else if (isset($user->id)) {
1471         // $user is valid object
1472     } else if (is_numeric($user)) {
1473         $user = (object)array('id'=>(int)$user);
1474     } else {
1475         throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1476     }
1478     check_user_preferences_loaded($user);
1480     if (empty($user->id) or isguestuser($user->id)) {
1481         // no permanent storage for not-logged-in users and guest
1482         $user->preference[$name] = $value;
1483         return true;
1484     }
1486     if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1487         if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1488             // preference already set to this value
1489             return true;
1490         }
1491         $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1493     } else {
1494         $preference = new stdClass();
1495         $preference->userid = $user->id;
1496         $preference->name   = $name;
1497         $preference->value  = $value;
1498         $DB->insert_record('user_preferences', $preference);
1499     }
1501     // update value in cache
1502     $user->preference[$name] = $value;
1504     // set reload flag for other sessions
1505     mark_user_preferences_changed($user->id);
1507     return true;
1510 /**
1511  * Sets a whole array of preferences for the current user
1512  *
1513  * If user object submitted, 'preference' property contains the preferences cache.
1514  *
1515  * @param array $prefarray An array of key/value pairs to be set
1516  * @param stdClass|int $user A moodle user object or id, null means current user
1517  * @return bool always true or exception
1518  */
1519 function set_user_preferences(array $prefarray, $user = null) {
1520     foreach ($prefarray as $name => $value) {
1521         set_user_preference($name, $value, $user);
1522     }
1523     return true;
1526 /**
1527  * Unsets a preference completely by deleting it from the database
1528  *
1529  * If user object submitted, 'preference' property contains the preferences cache.
1530  *
1531  * @param string  $name The key to unset as preference for the specified user
1532  * @param stdClass|int $user A moodle user object or id, null means current user
1533  * @return bool always true or exception
1534  */
1535 function unset_user_preference($name, $user = null) {
1536     global $USER, $DB;
1538     if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1539         throw new coding_exception('Invalid preference name in unset_user_preference() call');
1540     }
1542     if (is_null($user)) {
1543         $user = $USER;
1544     } else if (isset($user->id)) {
1545         // $user is valid object
1546     } else if (is_numeric($user)) {
1547         $user = (object)array('id'=>(int)$user);
1548     } else {
1549         throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1550     }
1552     check_user_preferences_loaded($user);
1554     if (empty($user->id) or isguestuser($user->id)) {
1555         // no permanent storage for not-logged-in user and guest
1556         unset($user->preference[$name]);
1557         return true;
1558     }
1560     // delete from DB
1561     $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1563     // delete the preference from cache
1564     unset($user->preference[$name]);
1566     // set reload flag for other sessions
1567     mark_user_preferences_changed($user->id);
1569     return true;
1572 /**
1573  * Used to fetch user preference(s)
1574  *
1575  * If no arguments are supplied this function will return
1576  * all of the current user preferences as an array.
1577  *
1578  * If a name is specified then this function
1579  * attempts to return that particular preference value.  If
1580  * none is found, then the optional value $default is returned,
1581  * otherwise NULL.
1582  *
1583  * If user object submitted, 'preference' property contains the preferences cache.
1584  *
1585  * @param string $name Name of the key to use in finding a preference value
1586  * @param mixed $default Value to be returned if the $name key is not set in the user preferences
1587  * @param stdClass|int $user A moodle user object or id, null means current user
1588  * @return mixed string value or default
1589  */
1590 function get_user_preferences($name = null, $default = null, $user = null) {
1591     global $USER;
1593     if (is_null($name)) {
1594         // all prefs
1595     } else if (is_numeric($name) or $name === '_lastloaded') {
1596         throw new coding_exception('Invalid preference name in get_user_preferences() call');
1597     }
1599     if (is_null($user)) {
1600         $user = $USER;
1601     } else if (isset($user->id)) {
1602         // $user is valid object
1603     } else if (is_numeric($user)) {
1604         $user = (object)array('id'=>(int)$user);
1605     } else {
1606         throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1607     }
1609     check_user_preferences_loaded($user);
1611     if (empty($name)) {
1612         return $user->preference; // All values
1613     } else if (isset($user->preference[$name])) {
1614         return $user->preference[$name]; // The single string value
1615     } else {
1616         return $default; // Default value (null if not specified)
1617     }
1620 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1622 /**
1623  * Given date parts in user time produce a GMT timestamp.
1624  *
1625  * @todo Finish documenting this function
1626  * @param int $year The year part to create timestamp of
1627  * @param int $month The month part to create timestamp of
1628  * @param int $day The day part to create timestamp of
1629  * @param int $hour The hour part to create timestamp of
1630  * @param int $minute The minute part to create timestamp of
1631  * @param int $second The second part to create timestamp of
1632  * @param mixed $timezone Timezone modifier, if 99 then use default user's timezone
1633  * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1634  *             applied only if timezone is 99 or string.
1635  * @return int timestamp
1636  */
1637 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1639     //save input timezone, required for dst offset check.
1640     $passedtimezone = $timezone;
1642     $timezone = get_user_timezone_offset($timezone);
1644     if (abs($timezone) > 13) {  //server time
1645         $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1646     } else {
1647         $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1648         $time = usertime($time, $timezone);
1650         //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1651         if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1652             $time -= dst_offset_on($time, $passedtimezone);
1653         }
1654     }
1656     return $time;
1660 /**
1661  * Format a date/time (seconds) as weeks, days, hours etc as needed
1662  *
1663  * Given an amount of time in seconds, returns string
1664  * formatted nicely as weeks, days, hours etc as needed
1665  *
1666  * @uses MINSECS
1667  * @uses HOURSECS
1668  * @uses DAYSECS
1669  * @uses YEARSECS
1670  * @param int $totalsecs Time in seconds
1671  * @param object $str Should be a time object
1672  * @return string A nicely formatted date/time string
1673  */
1674  function format_time($totalsecs, $str=NULL) {
1676     $totalsecs = abs($totalsecs);
1678     if (!$str) {  // Create the str structure the slow way
1679         $str->day   = get_string('day');
1680         $str->days  = get_string('days');
1681         $str->hour  = get_string('hour');
1682         $str->hours = get_string('hours');
1683         $str->min   = get_string('min');
1684         $str->mins  = get_string('mins');
1685         $str->sec   = get_string('sec');
1686         $str->secs  = get_string('secs');
1687         $str->year  = get_string('year');
1688         $str->years = get_string('years');
1689     }
1692     $years     = floor($totalsecs/YEARSECS);
1693     $remainder = $totalsecs - ($years*YEARSECS);
1694     $days      = floor($remainder/DAYSECS);
1695     $remainder = $totalsecs - ($days*DAYSECS);
1696     $hours     = floor($remainder/HOURSECS);
1697     $remainder = $remainder - ($hours*HOURSECS);
1698     $mins      = floor($remainder/MINSECS);
1699     $secs      = $remainder - ($mins*MINSECS);
1701     $ss = ($secs == 1)  ? $str->sec  : $str->secs;
1702     $sm = ($mins == 1)  ? $str->min  : $str->mins;
1703     $sh = ($hours == 1) ? $str->hour : $str->hours;
1704     $sd = ($days == 1)  ? $str->day  : $str->days;
1705     $sy = ($years == 1)  ? $str->year  : $str->years;
1707     $oyears = '';
1708     $odays = '';
1709     $ohours = '';
1710     $omins = '';
1711     $osecs = '';
1713     if ($years)  $oyears  = $years .' '. $sy;
1714     if ($days)  $odays  = $days .' '. $sd;
1715     if ($hours) $ohours = $hours .' '. $sh;
1716     if ($mins)  $omins  = $mins .' '. $sm;
1717     if ($secs)  $osecs  = $secs .' '. $ss;
1719     if ($years) return trim($oyears .' '. $odays);
1720     if ($days)  return trim($odays .' '. $ohours);
1721     if ($hours) return trim($ohours .' '. $omins);
1722     if ($mins)  return trim($omins .' '. $osecs);
1723     if ($secs)  return $osecs;
1724     return get_string('now');
1727 /**
1728  * Returns a formatted string that represents a date in user time
1729  *
1730  * Returns a formatted string that represents a date in user time
1731  * <b>WARNING: note that the format is for strftime(), not date().</b>
1732  * Because of a bug in most Windows time libraries, we can't use
1733  * the nicer %e, so we have to use %d which has leading zeroes.
1734  * A lot of the fuss in the function is just getting rid of these leading
1735  * zeroes as efficiently as possible.
1736  *
1737  * If parameter fixday = true (default), then take off leading
1738  * zero from %d, else maintain it.
1739  *
1740  * @param int $date the timestamp in UTC, as obtained from the database.
1741  * @param string $format strftime format. You should probably get this using
1742  *      get_string('strftime...', 'langconfig');
1743  * @param mixed $timezone by default, uses the user's time zone. if numeric and
1744  *      not 99 then daylight saving will not be added.
1745  * @param bool $fixday If true (default) then the leading zero from %d is removed.
1746  *      If false then the leading zero is maintained.
1747  * @return string the formatted date/time.
1748  */
1749 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1751     global $CFG;
1753     if (empty($format)) {
1754         $format = get_string('strftimedaydatetime', 'langconfig');
1755     }
1757     if (!empty($CFG->nofixday)) {  // Config.php can force %d not to be fixed.
1758         $fixday = false;
1759     } else if ($fixday) {
1760         $formatnoday = str_replace('%d', 'DD', $format);
1761         $fixday = ($formatnoday != $format);
1762     }
1764     //add daylight saving offset for string timezones only, as we can't get dst for
1765     //float values. if timezone is 99 (user default timezone), then try update dst.
1766     if ((99 == $timezone) || !is_numeric($timezone)) {
1767         $date += dst_offset_on($date, $timezone);
1768     }
1770     $timezone = get_user_timezone_offset($timezone);
1772     if (abs($timezone) > 13) {   /// Server time
1773         if ($fixday) {
1774             $datestring = strftime($formatnoday, $date);
1775             $daystring  = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
1776             $datestring = str_replace('DD', $daystring, $datestring);
1777         } else {
1778             $datestring = strftime($format, $date);
1779         }
1780     } else {
1781         $date += (int)($timezone * 3600);
1782         if ($fixday) {
1783             $datestring = gmstrftime($formatnoday, $date);
1784             $daystring  = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
1785             $datestring = str_replace('DD', $daystring, $datestring);
1786         } else {
1787             $datestring = gmstrftime($format, $date);
1788         }
1789     }
1791 /// If we are running under Windows convert from windows encoding to UTF-8
1792 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1794    if ($CFG->ostype == 'WINDOWS') {
1795        if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1796            $textlib = textlib_get_instance();
1797            $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1798        }
1799    }
1801     return $datestring;
1804 /**
1805  * Given a $time timestamp in GMT (seconds since epoch),
1806  * returns an array that represents the date in user time
1807  *
1808  * @todo Finish documenting this function
1809  * @uses HOURSECS
1810  * @param int $time Timestamp in GMT
1811  * @param mixed $timezone offset time with timezone, if float and not 99, then no
1812  *        dst offset is applyed
1813  * @return array An array that represents the date in user time
1814  */
1815 function usergetdate($time, $timezone=99) {
1817     //save input timezone, required for dst offset check.
1818     $passedtimezone = $timezone;
1820     $timezone = get_user_timezone_offset($timezone);
1822     if (abs($timezone) > 13) {    // Server time
1823         return getdate($time);
1824     }
1826     //add daylight saving offset for string timezones only, as we can't get dst for
1827     //float values. if timezone is 99 (user default timezone), then try update dst.
1828     if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
1829         $time += dst_offset_on($time, $passedtimezone);
1830     }
1832     $time += intval((float)$timezone * HOURSECS);
1834     $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
1836     //be careful to ensure the returned array matches that produced by getdate() above
1837     list(
1838         $getdate['month'],
1839         $getdate['weekday'],
1840         $getdate['yday'],
1841         $getdate['year'],
1842         $getdate['mon'],
1843         $getdate['wday'],
1844         $getdate['mday'],
1845         $getdate['hours'],
1846         $getdate['minutes'],
1847         $getdate['seconds']
1848     ) = explode('_', $datestring);
1850     return $getdate;
1853 /**
1854  * Given a GMT timestamp (seconds since epoch), offsets it by
1855  * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1856  *
1857  * @uses HOURSECS
1858  * @param  int $date Timestamp in GMT
1859  * @param float $timezone
1860  * @return int
1861  */
1862 function usertime($date, $timezone=99) {
1864     $timezone = get_user_timezone_offset($timezone);
1866     if (abs($timezone) > 13) {
1867         return $date;
1868     }
1869     return $date - (int)($timezone * HOURSECS);
1872 /**
1873  * Given a time, return the GMT timestamp of the most recent midnight
1874  * for the current user.
1875  *
1876  * @param int $date Timestamp in GMT
1877  * @param float $timezone Defaults to user's timezone
1878  * @return int Returns a GMT timestamp
1879  */
1880 function usergetmidnight($date, $timezone=99) {
1882     $userdate = usergetdate($date, $timezone);
1884     // Time of midnight of this user's day, in GMT
1885     return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1889 /**
1890  * Returns a string that prints the user's timezone
1891  *
1892  * @param float $timezone The user's timezone
1893  * @return string
1894  */
1895 function usertimezone($timezone=99) {
1897     $tz = get_user_timezone($timezone);
1899     if (!is_float($tz)) {
1900         return $tz;
1901     }
1903     if(abs($tz) > 13) { // Server time
1904         return get_string('serverlocaltime');
1905     }
1907     if($tz == intval($tz)) {
1908         // Don't show .0 for whole hours
1909         $tz = intval($tz);
1910     }
1912     if($tz == 0) {
1913         return 'UTC';
1914     }
1915     else if($tz > 0) {
1916         return 'UTC+'.$tz;
1917     }
1918     else {
1919         return 'UTC'.$tz;
1920     }
1924 /**
1925  * Returns a float which represents the user's timezone difference from GMT in hours
1926  * Checks various settings and picks the most dominant of those which have a value
1927  *
1928  * @global object
1929  * @global object
1930  * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
1931  * @return float
1932  */
1933 function get_user_timezone_offset($tz = 99) {
1935     global $USER, $CFG;
1937     $tz = get_user_timezone($tz);
1939     if (is_float($tz)) {
1940         return $tz;
1941     } else {
1942         $tzrecord = get_timezone_record($tz);
1943         if (empty($tzrecord)) {
1944             return 99.0;
1945         }
1946         return (float)$tzrecord->gmtoff / HOURMINS;
1947     }
1950 /**
1951  * Returns an int which represents the systems's timezone difference from GMT in seconds
1952  *
1953  * @global object
1954  * @param mixed $tz timezone
1955  * @return int if found, false is timezone 99 or error
1956  */
1957 function get_timezone_offset($tz) {
1958     global $CFG;
1960     if ($tz == 99) {
1961         return false;
1962     }
1964     if (is_numeric($tz)) {
1965         return intval($tz * 60*60);
1966     }
1968     if (!$tzrecord = get_timezone_record($tz)) {
1969         return false;
1970     }
1971     return intval($tzrecord->gmtoff * 60);
1974 /**
1975  * Returns a float or a string which denotes the user's timezone
1976  * 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)
1977  * means that for this timezone there are also DST rules to be taken into account
1978  * Checks various settings and picks the most dominant of those which have a value
1979  *
1980  * @global object
1981  * @global object
1982  * @param mixed $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
1983  * @return mixed
1984  */
1985 function get_user_timezone($tz = 99) {
1986     global $USER, $CFG;
1988     $timezones = array(
1989         $tz,
1990         isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1991         isset($USER->timezone) ? $USER->timezone : 99,
1992         isset($CFG->timezone) ? $CFG->timezone : 99,
1993         );
1995     $tz = 99;
1997     while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
1998         $tz = $next['value'];
1999     }
2001     return is_numeric($tz) ? (float) $tz : $tz;
2004 /**
2005  * Returns cached timezone record for given $timezonename
2006  *
2007  * @global object
2008  * @global object
2009  * @param string $timezonename
2010  * @return mixed timezonerecord object or false
2011  */
2012 function get_timezone_record($timezonename) {
2013     global $CFG, $DB;
2014     static $cache = NULL;
2016     if ($cache === NULL) {
2017         $cache = array();
2018     }
2020     if (isset($cache[$timezonename])) {
2021         return $cache[$timezonename];
2022     }
2024     return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2025                                                         WHERE name = ? ORDER BY year DESC', array($timezonename), true);
2028 /**
2029  * Build and store the users Daylight Saving Time (DST) table
2030  *
2031  * @global object
2032  * @global object
2033  * @global object
2034  * @param mixed $from_year Start year for the table, defaults to 1971
2035  * @param mixed $to_year End year for the table, defaults to 2035
2036  * @param mixed $strtimezone, if null or 99 then user's default timezone is used
2037  * @return bool
2038  */
2039 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2040     global $CFG, $SESSION, $DB;
2042     $usertz = get_user_timezone($strtimezone);
2044     if (is_float($usertz)) {
2045         // Trivial timezone, no DST
2046         return false;
2047     }
2049     if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2050         // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2051         unset($SESSION->dst_offsets);
2052         unset($SESSION->dst_range);
2053     }
2055     if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2056         // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2057         // This will be the return path most of the time, pretty light computationally
2058         return true;
2059     }
2061     // Reaching here means we either need to extend our table or create it from scratch
2063     // Remember which TZ we calculated these changes for
2064     $SESSION->dst_offsettz = $usertz;
2066     if(empty($SESSION->dst_offsets)) {
2067         // If we 're creating from scratch, put the two guard elements in there
2068         $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2069     }
2070     if(empty($SESSION->dst_range)) {
2071         // If creating from scratch
2072         $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2073         $to   = min((empty($to_year)   ? intval(date('Y')) + 3 : $to_year),   2035);
2075         // Fill in the array with the extra years we need to process
2076         $yearstoprocess = array();
2077         for($i = $from; $i <= $to; ++$i) {
2078             $yearstoprocess[] = $i;
2079         }
2081         // Take note of which years we have processed for future calls
2082         $SESSION->dst_range = array($from, $to);
2083     }
2084     else {
2085         // If needing to extend the table, do the same
2086         $yearstoprocess = array();
2088         $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2089         $to   = min((empty($to_year)   ? $SESSION->dst_range[1] : $to_year),   2035);
2091         if($from < $SESSION->dst_range[0]) {
2092             // Take note of which years we need to process and then note that we have processed them for future calls
2093             for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2094                 $yearstoprocess[] = $i;
2095             }
2096             $SESSION->dst_range[0] = $from;
2097         }
2098         if($to > $SESSION->dst_range[1]) {
2099             // Take note of which years we need to process and then note that we have processed them for future calls
2100             for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2101                 $yearstoprocess[] = $i;
2102             }
2103             $SESSION->dst_range[1] = $to;
2104         }
2105     }
2107     if(empty($yearstoprocess)) {
2108         // This means that there was a call requesting a SMALLER range than we have already calculated
2109         return true;
2110     }
2112     // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2113     // Also, the array is sorted in descending timestamp order!
2115     // Get DB data
2117     static $presets_cache = array();
2118     if (!isset($presets_cache[$usertz])) {
2119         $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');
2120     }
2121     if(empty($presets_cache[$usertz])) {
2122         return false;
2123     }
2125     // Remove ending guard (first element of the array)
2126     reset($SESSION->dst_offsets);
2127     unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2129     // Add all required change timestamps
2130     foreach($yearstoprocess as $y) {
2131         // Find the record which is in effect for the year $y
2132         foreach($presets_cache[$usertz] as $year => $preset) {
2133             if($year <= $y) {
2134                 break;
2135             }
2136         }
2138         $changes = dst_changes_for_year($y, $preset);
2140         if($changes === NULL) {
2141             continue;
2142         }
2143         if($changes['dst'] != 0) {
2144             $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2145         }
2146         if($changes['std'] != 0) {
2147             $SESSION->dst_offsets[$changes['std']] = 0;
2148         }
2149     }
2151     // Put in a guard element at the top
2152     $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2153     $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2155     // Sort again
2156     krsort($SESSION->dst_offsets);
2158     return true;
2161 /**
2162  * Calculates the required DST change and returns a Timestamp Array
2163  *
2164  * @uses HOURSECS
2165  * @uses MINSECS
2166  * @param mixed $year Int or String Year to focus on
2167  * @param object $timezone Instatiated Timezone object
2168  * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
2169  */
2170 function dst_changes_for_year($year, $timezone) {
2172     if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2173         return NULL;
2174     }
2176     $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2177     $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2179     list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2180     list($std_hour, $std_min) = explode(':', $timezone->std_time);
2182     $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2183     $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2185     // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2186     // This has the advantage of being able to have negative values for hour, i.e. for timezones
2187     // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2189     $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2190     $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2192     return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2195 /**
2196  * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2197  * - Note: Daylight saving only works for string timezones and not for float.
2198  *
2199  * @global object
2200  * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2201  * @param mixed $strtimezone timezone for which offset is expected, if 99 or null
2202  *        then user's default timezone is used.
2203  * @return int
2204  */
2205 function dst_offset_on($time, $strtimezone = NULL) {
2206     global $SESSION;
2208     if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2209         return 0;
2210     }
2212     reset($SESSION->dst_offsets);
2213     while(list($from, $offset) = each($SESSION->dst_offsets)) {
2214         if($from <= $time) {
2215             break;
2216         }
2217     }
2219     // This is the normal return path
2220     if($offset !== NULL) {
2221         return $offset;
2222     }
2224     // Reaching this point means we haven't calculated far enough, do it now:
2225     // Calculate extra DST changes if needed and recurse. The recursion always
2226     // moves toward the stopping condition, so will always end.
2228     if($from == 0) {
2229         // We need a year smaller than $SESSION->dst_range[0]
2230         if($SESSION->dst_range[0] == 1971) {
2231             return 0;
2232         }
2233         calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2234         return dst_offset_on($time, $strtimezone);
2235     }
2236     else {
2237         // We need a year larger than $SESSION->dst_range[1]
2238         if($SESSION->dst_range[1] == 2035) {
2239             return 0;
2240         }
2241         calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2242         return dst_offset_on($time, $strtimezone);
2243     }
2246 /**
2247  * ?
2248  *
2249  * @todo Document what this function does
2250  * @param int $startday
2251  * @param int $weekday
2252  * @param int $month
2253  * @param int $year
2254  * @return int
2255  */
2256 function find_day_in_month($startday, $weekday, $month, $year) {
2258     $daysinmonth = days_in_month($month, $year);
2260     if($weekday == -1) {
2261         // Don't care about weekday, so return:
2262         //    abs($startday) if $startday != -1
2263         //    $daysinmonth otherwise
2264         return ($startday == -1) ? $daysinmonth : abs($startday);
2265     }
2267     // From now on we 're looking for a specific weekday
2269     // Give "end of month" its actual value, since we know it
2270     if($startday == -1) {
2271         $startday = -1 * $daysinmonth;
2272     }
2274     // Starting from day $startday, the sign is the direction
2276     if($startday < 1) {
2278         $startday = abs($startday);
2279         $lastmonthweekday  = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2281         // This is the last such weekday of the month
2282         $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2283         if($lastinmonth > $daysinmonth) {
2284             $lastinmonth -= 7;
2285         }
2287         // Find the first such weekday <= $startday
2288         while($lastinmonth > $startday) {
2289             $lastinmonth -= 7;
2290         }
2292         return $lastinmonth;
2294     }
2295     else {
2297         $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2299         $diff = $weekday - $indexweekday;
2300         if($diff < 0) {
2301             $diff += 7;
2302         }
2304         // This is the first such weekday of the month equal to or after $startday
2305         $firstfromindex = $startday + $diff;
2307         return $firstfromindex;
2309     }
2312 /**
2313  * Calculate the number of days in a given month
2314  *
2315  * @param int $month The month whose day count is sought
2316  * @param int $year The year of the month whose day count is sought
2317  * @return int
2318  */
2319 function days_in_month($month, $year) {
2320    return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2323 /**
2324  * Calculate the position in the week of a specific calendar day
2325  *
2326  * @param int $day The day of the date whose position in the week is sought
2327  * @param int $month The month of the date whose position in the week is sought
2328  * @param int $year The year of the date whose position in the week is sought
2329  * @return int
2330  */
2331 function dayofweek($day, $month, $year) {
2332     // I wonder if this is any different from
2333     // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2334     return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2337 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2339 /**
2340  * Returns full login url.
2341  *
2342  * @return string login url
2343  */
2344 function get_login_url() {
2345     global $CFG;
2347     $url = "$CFG->wwwroot/login/index.php";
2349     if (!empty($CFG->loginhttps)) {
2350         $url = str_replace('http:', 'https:', $url);
2351     }
2353     return $url;
2356 /**
2357  * This function checks that the current user is logged in and has the
2358  * required privileges
2359  *
2360  * This function checks that the current user is logged in, and optionally
2361  * whether they are allowed to be in a particular course and view a particular
2362  * course module.
2363  * If they are not logged in, then it redirects them to the site login unless
2364  * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2365  * case they are automatically logged in as guests.
2366  * If $courseid is given and the user is not enrolled in that course then the
2367  * user is redirected to the course enrolment page.
2368  * If $cm is given and the course module is hidden and the user is not a teacher
2369  * in the course then the user is redirected to the course home page.
2370  *
2371  * When $cm parameter specified, this function sets page layout to 'module'.
2372  * You need to change it manually later if some other layout needed.
2373  *
2374  * @param mixed $courseorid id of the course or course object
2375  * @param bool $autologinguest default true
2376  * @param object $cm course module object
2377  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2378  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2379  *             in order to keep redirects working properly. MDL-14495
2380  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2381  * @return mixed Void, exit, and die depending on path
2382  */
2383 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2384     global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2386     // setup global $COURSE, themes, language and locale
2387     if (!empty($courseorid)) {
2388         if (is_object($courseorid)) {
2389             $course = $courseorid;
2390         } else if ($courseorid == SITEID) {
2391             $course = clone($SITE);
2392         } else {
2393             $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2394         }
2395         if ($cm) {
2396             if ($cm->course != $course->id) {
2397                 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2398             }
2399             // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2400             if (!($cm instanceof cm_info)) {
2401                 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2402                 // db queries so this is not really a performance concern, however it is obviously
2403                 // better if you use get_fast_modinfo to get the cm before calling this.
2404                 $modinfo = get_fast_modinfo($course);
2405                 $cm = $modinfo->get_cm($cm->id);
2406             }
2407             $PAGE->set_cm($cm, $course); // set's up global $COURSE
2408             $PAGE->set_pagelayout('incourse');
2409         } else {
2410             $PAGE->set_course($course); // set's up global $COURSE
2411         }
2412     } else {
2413         // do not touch global $COURSE via $PAGE->set_course(),
2414         // the reasons is we need to be able to call require_login() at any time!!
2415         $course = $SITE;
2416         if ($cm) {
2417             throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2418         }
2419     }
2421     // If the user is not even logged in yet then make sure they are
2422     if (!isloggedin()) {
2423         if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2424             if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2425                 // misconfigured site guest, just redirect to login page
2426                 redirect(get_login_url());
2427                 exit; // never reached
2428             }
2429             $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2430             complete_user_login($guest);
2431             $USER->autologinguest = true;
2432             $SESSION->lang = $lang;
2433         } else {
2434             //NOTE: $USER->site check was obsoleted by session test cookie,
2435             //      $USER->confirmed test is in login/index.php
2436             if ($preventredirect) {
2437                 throw new require_login_exception('You are not logged in');
2438             }
2440             if ($setwantsurltome) {
2441                 // TODO: switch to PAGE->url
2442                 $SESSION->wantsurl = $FULLME;
2443             }
2444             if (!empty($_SERVER['HTTP_REFERER'])) {
2445                 $SESSION->fromurl  = $_SERVER['HTTP_REFERER'];
2446             }
2447             redirect(get_login_url());
2448             exit; // never reached
2449         }
2450     }
2452     // loginas as redirection if needed
2453     if ($course->id != SITEID and session_is_loggedinas()) {
2454         if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2455             if ($USER->loginascontext->instanceid != $course->id) {
2456                 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2457             }
2458         }
2459     }
2461     // check whether the user should be changing password (but only if it is REALLY them)
2462     if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2463         $userauth = get_auth_plugin($USER->auth);
2464         if ($userauth->can_change_password() and !$preventredirect) {
2465             $SESSION->wantsurl = $FULLME;
2466             if ($changeurl = $userauth->change_password_url()) {
2467                 //use plugin custom url
2468                 redirect($changeurl);
2469             } else {
2470                 //use moodle internal method
2471                 if (empty($CFG->loginhttps)) {
2472                     redirect($CFG->wwwroot .'/login/change_password.php');
2473                 } else {
2474                     $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2475                     redirect($wwwroot .'/login/change_password.php');
2476                 }
2477             }
2478         } else {
2479             print_error('nopasswordchangeforced', 'auth');
2480         }
2481     }
2483     // Check that the user account is properly set up
2484     if (user_not_fully_set_up($USER)) {
2485         if ($preventredirect) {
2486             throw new require_login_exception('User not fully set-up');
2487         }
2488         $SESSION->wantsurl = $FULLME;
2489         redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2490     }
2492     // Make sure the USER has a sesskey set up. Used for CSRF protection.
2493     sesskey();
2495     // Do not bother admins with any formalities
2496     if (is_siteadmin()) {
2497         //set accesstime or the user will appear offline which messes up messaging
2498         user_accesstime_log($course->id);
2499         return;
2500     }
2502     // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2503     if (!$USER->policyagreed and !is_siteadmin()) {
2504         if (!empty($CFG->sitepolicy) and !isguestuser()) {
2505             if ($preventredirect) {
2506                 throw new require_login_exception('Policy not agreed');
2507             }
2508             $SESSION->wantsurl = $FULLME;
2509             redirect($CFG->wwwroot .'/user/policy.php');
2510         } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2511             if ($preventredirect) {
2512                 throw new require_login_exception('Policy not agreed');
2513             }
2514             $SESSION->wantsurl = $FULLME;
2515             redirect($CFG->wwwroot .'/user/policy.php');
2516         }
2517     }
2519     // Fetch the system context, the course context, and prefetch its child contexts
2520     $sysctx = get_context_instance(CONTEXT_SYSTEM);
2521     $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2522     if ($cm) {
2523         $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2524     } else {
2525         $cmcontext = null;
2526     }
2528     // If the site is currently under maintenance, then print a message
2529     if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2530         if ($preventredirect) {
2531             throw new require_login_exception('Maintenance in progress');
2532         }
2534         print_maintenance_message();
2535     }
2537     // make sure the course itself is not hidden
2538     if ($course->id == SITEID) {
2539         // frontpage can not be hidden
2540     } else {
2541         if (is_role_switched($course->id)) {
2542             // when switching roles ignore the hidden flag - user had to be in course to do the switch
2543         } else {
2544             if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2545                 // originally there was also test of parent category visibility,
2546                 // BUT is was very slow in complex queries involving "my courses"
2547                 // now it is also possible to simply hide all courses user is not enrolled in :-)
2548                 if ($preventredirect) {
2549                     throw new require_login_exception('Course is hidden');
2550                 }
2551                 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2552             }
2553         }
2554     }
2556     // is the user enrolled?
2557     if ($course->id == SITEID) {
2558         // everybody is enrolled on the frontpage
2560     } else {
2561         if (session_is_loggedinas()) {
2562             // Make sure the REAL person can access this course first
2563             $realuser = session_get_realuser();
2564             if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2565                 if ($preventredirect) {
2566                     throw new require_login_exception('Invalid course login-as access');
2567                 }
2568                 echo $OUTPUT->header();
2569                 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2570             }
2571         }
2573         // very simple enrolment caching - changes in course setting are not reflected immediately
2574         if (!isset($USER->enrol)) {
2575             $USER->enrol = array();
2576             $USER->enrol['enrolled'] = array();
2577             $USER->enrol['tempguest'] = array();
2578         }
2580         $access = false;
2582         if (is_viewing($coursecontext, $USER)) {
2583             // ok, no need to mess with enrol
2584             $access = true;
2586         } else {
2587             if (isset($USER->enrol['enrolled'][$course->id])) {
2588                 if ($USER->enrol['enrolled'][$course->id] == 0) {
2589                     $access = true;
2590                 } else if ($USER->enrol['enrolled'][$course->id] > time()) {
2591                     $access = true;
2592                 } else {
2593                     //expired
2594                     unset($USER->enrol['enrolled'][$course->id]);
2595                 }
2596             }
2597             if (isset($USER->enrol['tempguest'][$course->id])) {
2598                 if ($USER->enrol['tempguest'][$course->id] == 0) {
2599                     $access = true;
2600                 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2601                     $access = true;
2602                 } else {
2603                     //expired
2604                     unset($USER->enrol['tempguest'][$course->id]);
2605                     $USER->access = remove_temp_roles($coursecontext, $USER->access);
2606                 }
2607             }
2609             if ($access) {
2610                 // cache ok
2611             } else if (is_enrolled($coursecontext, $USER, '', true)) {
2612                 // active participants may always access
2613                 // TODO: refactor this into some new function
2614                 $now = time();
2615                 $sql = "SELECT MAX(ue.timeend)
2616                           FROM {user_enrolments} ue
2617                           JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2618                           JOIN {user} u ON u.id = ue.userid
2619                          WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0
2620                                AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
2621                 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE,
2622                                 'userid'=>$USER->id, 'courseid'=>$coursecontext->instanceid, 'now1'=>$now, 'now2'=>$now);
2623                 $until = $DB->get_field_sql($sql, $params);
2624                 if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) {
2625                     $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD;
2626                 }
2628                 $USER->enrol['enrolled'][$course->id] = $until;
2629                 $access = true;
2631                 // remove traces of previous temp guest access
2632                 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2634             } else {
2635                 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2636                 $enrols = enrol_get_plugins(true);
2637                 // first ask all enabled enrol instances in course if they want to auto enrol user
2638                 foreach($instances as $instance) {
2639                     if (!isset($enrols[$instance->enrol])) {
2640                         continue;
2641                     }
2642                     // Get a duration for the guestaccess, a timestamp in the future or false.
2643                     $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2644                     if ($until !== false) {
2645                         $USER->enrol['enrolled'][$course->id] = $until;
2646                         $USER->access = remove_temp_roles($coursecontext, $USER->access);
2647                         $access = true;
2648                         break;
2649                     }
2650                 }
2651                 // if not enrolled yet try to gain temporary guest access
2652                 if (!$access) {
2653                     foreach($instances as $instance) {
2654                         if (!isset($enrols[$instance->enrol])) {
2655                             continue;
2656                         }
2657                         // Get a duration for the guestaccess, a timestamp in the future or false.
2658                         $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2659                         if ($until !== false) {
2660                             $USER->enrol['tempguest'][$course->id] = $until;
2661                             $access = true;
2662                             break;
2663                         }
2664                     }
2665                 }
2666             }
2667         }
2669         if (!$access) {
2670             if ($preventredirect) {
2671                 throw new require_login_exception('Not enrolled');
2672             }
2673             $SESSION->wantsurl = $FULLME;
2674             redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2675         }
2676     }
2678     // Check visibility of activity to current user; includes visible flag, groupmembersonly,
2679     // conditional availability, etc
2680     if ($cm && !$cm->uservisible) {
2681         if ($preventredirect) {
2682             throw new require_login_exception('Activity is hidden');
2683         }
2684         redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2685     }
2687     // Finally access granted, update lastaccess times
2688     user_accesstime_log($course->id);
2692 /**
2693  * This function just makes sure a user is logged out.
2694  *
2695  * @global object
2696  */
2697 function require_logout() {
2698     global $USER;
2700     $params = $USER;
2702     if (isloggedin()) {
2703         add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2705         $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2706         foreach($authsequence as $authname) {
2707             $authplugin = get_auth_plugin($authname);
2708             $authplugin->prelogout_hook();
2709         }
2710     }
2712     events_trigger('user_logout', $params);
2713     session_get_instance()->terminate_current();
2714     unset($params);
2717 /**
2718  * Weaker version of require_login()
2719  *
2720  * This is a weaker version of {@link require_login()} which only requires login
2721  * when called from within a course rather than the site page, unless
2722  * the forcelogin option is turned on.
2723  * @see require_login()
2724  *
2725  * @global object
2726  * @param mixed $courseorid The course object or id in question
2727  * @param bool $autologinguest Allow autologin guests if that is wanted
2728  * @param object $cm Course activity module if known
2729  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2730  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2731  *             in order to keep redirects working properly. MDL-14495
2732  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2733  * @return void
2734  */
2735 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2736     global $CFG, $PAGE, $SITE;
2737     $issite = (is_object($courseorid) and $courseorid->id == SITEID)
2738           or (!is_object($courseorid) and $courseorid == SITEID);
2739     if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2740         // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2741         // db queries so this is not really a performance concern, however it is obviously
2742         // better if you use get_fast_modinfo to get the cm before calling this.
2743         if (is_object($courseorid)) {
2744             $course = $courseorid;
2745         } else {
2746             $course = clone($SITE);
2747         }
2748         $modinfo = get_fast_modinfo($course);
2749         $cm = $modinfo->get_cm($cm->id);
2750     }
2751     if (!empty($CFG->forcelogin)) {
2752         // login required for both SITE and courses
2753         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2755     } else if ($issite && !empty($cm) and !$cm->uservisible) {
2756         // always login for hidden activities
2757         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2759     } else if ($issite) {
2760               //login for SITE not required
2761         if ($cm and empty($cm->visible)) {
2762             // hidden activities are not accessible without login
2763             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2764         } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2765             // not-logged-in users do not have any group membership
2766             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2767         } else {
2768             // We still need to instatiate PAGE vars properly so that things
2769             // that rely on it like navigation function correctly.
2770             if (!empty($courseorid)) {
2771                 if (is_object($courseorid)) {
2772                     $course = $courseorid;
2773                 } else {
2774                     $course = clone($SITE);
2775                 }
2776                 if ($cm) {
2777                     if ($cm->course != $course->id) {
2778                         throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2779                     }
2780                     $PAGE->set_cm($cm, $course);
2781                     $PAGE->set_pagelayout('incourse');
2782                 } else {
2783                     $PAGE->set_course($course);
2784                 }
2785             } else {
2786                 // If $PAGE->course, and hence $PAGE->context, have not already been set
2787                 // up properly, set them up now.
2788                 $PAGE->set_course($PAGE->course);
2789             }
2790             //TODO: verify conditional activities here
2791             user_accesstime_log(SITEID);
2792             return;
2793         }
2795     } else {
2796         // course login always required
2797         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2798     }
2801 /**
2802  * Require key login. Function terminates with error if key not found or incorrect.
2803  *
2804  * @global object
2805  * @global object
2806  * @global object
2807  * @global object
2808  * @uses NO_MOODLE_COOKIES
2809  * @uses PARAM_ALPHANUM
2810  * @param string $script unique script identifier
2811  * @param int $instance optional instance id
2812  * @return int Instance ID
2813  */
2814 function require_user_key_login($script, $instance=null) {
2815     global $USER, $SESSION, $CFG, $DB;
2817     if (!NO_MOODLE_COOKIES) {
2818         print_error('sessioncookiesdisable');
2819     }
2821 /// extra safety
2822     @session_write_close();
2824     $keyvalue = required_param('key', PARAM_ALPHANUM);
2826     if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2827         print_error('invalidkey');
2828     }
2830     if (!empty($key->validuntil) and $key->validuntil < time()) {
2831         print_error('expiredkey');
2832     }
2834     if ($key->iprestriction) {
2835         $remoteaddr = getremoteaddr(null);
2836         if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2837             print_error('ipmismatch');
2838         }
2839     }
2841     if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2842         print_error('invaliduserid');
2843     }
2845 /// emulate normal session
2846     session_set_user($user);
2848 /// note we are not using normal login
2849     if (!defined('USER_KEY_LOGIN')) {
2850         define('USER_KEY_LOGIN', true);
2851     }
2853 /// return instance id - it might be empty
2854     return $key->instance;
2857 /**
2858  * Creates a new private user access key.
2859  *
2860  * @global object
2861  * @param string $script unique target identifier
2862  * @param int $userid
2863  * @param int $instance optional instance id
2864  * @param string $iprestriction optional ip restricted access
2865  * @param timestamp $validuntil key valid only until given data
2866  * @return string access key value
2867  */
2868 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2869     global $DB;
2871     $key = new stdClass();
2872     $key->script        = $script;
2873     $key->userid        = $userid;
2874     $key->instance      = $instance;
2875     $key->iprestriction = $iprestriction;
2876     $key->validuntil    = $validuntil;
2877     $key->timecreated   = time();
2879     $key->value         = md5($userid.'_'.time().random_string(40)); // something long and unique
2880     while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
2881         // must be unique
2882         $key->value     = md5($userid.'_'.time().random_string(40));
2883     }
2884     $DB->insert_record('user_private_key', $key);
2885     return $key->value;
2888 /**
2889  * Delete the user's new private user access keys for a particular script.
2890  *
2891  * @global object
2892  * @param string $script unique target identifier
2893  * @param int $userid
2894  * @return void
2895  */
2896 function delete_user_key($script,$userid) {
2897     global $DB;
2898     $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
2901 /**
2902  * Gets a private user access key (and creates one if one doesn't exist).
2903  *
2904  * @global object
2905  * @param string $script unique target identifier
2906  * @param int $userid
2907  * @param int $instance optional instance id
2908  * @param string $iprestriction optional ip restricted access
2909  * @param timestamp $validuntil key valid only until given data
2910  * @return string access key value
2911  */
2912 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2913     global $DB;
2915     if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
2916                                                          'instance'=>$instance, 'iprestriction'=>$iprestriction,
2917                                                          'validuntil'=>$validuntil))) {
2918         return $key->value;
2919     } else {
2920         return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
2921     }
2925 /**
2926  * Modify the user table by setting the currently logged in user's
2927  * last login to now.
2928  *
2929  * @global object
2930  * @global object
2931  * @return bool Always returns true
2932  */
2933 function update_user_login_times() {
2934     global $USER, $DB;
2936     $user = new stdClass();
2937     $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2938     $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2940     $user->id = $USER->id;
2942     $DB->update_record('user', $user);
2943     return true;
2946 /**
2947  * Determines if a user has completed setting up their account.
2948  *
2949  * @param user $user A {@link $USER} object to test for the existence of a valid name and email
2950  * @return bool
2951  */
2952 function user_not_fully_set_up($user) {
2953     if (isguestuser($user)) {
2954         return false;
2955     }
2956     return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
2959 /**
2960  * Check whether the user has exceeded the bounce threshold
2961  *
2962  * @global object
2963  * @global object
2964  * @param user $user A {@link $USER} object
2965  * @return bool true=>User has exceeded bounce threshold
2966  */
2967 function over_bounce_threshold($user) {
2968     global $CFG, $DB;
2970     if (empty($CFG->handlebounces)) {
2971         return false;
2972     }
2974     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2975         return false;
2976     }
2978     // set sensible defaults
2979     if (empty($CFG->minbounces)) {
2980         $CFG->minbounces = 10;
2981     }
2982     if (empty($CFG->bounceratio)) {
2983         $CFG->bounceratio = .20;
2984     }
2985     $bouncecount = 0;
2986     $sendcount = 0;
2987     if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2988         $bouncecount = $bounce->value;
2989     }
2990     if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2991         $sendcount = $send->value;
2992     }
2993     return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2996 /**
2997  * Used to increment or reset email sent count
2998  *
2999  * @global object
3000  * @param user $user object containing an id
3001  * @param bool $reset will reset the count to 0
3002  * @return void
3003  */
3004 function set_send_count($user,$reset=false) {
3005     global $DB;
3007     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3008         return;
3009     }
3011     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3012         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3013         $DB->update_record('user_preferences', $pref);
3014     }
3015     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3016         // make a new one
3017         $pref = new stdClass();
3018         $pref->name   = 'email_send_count';
3019         $pref->value  = 1;
3020         $pref->userid = $user->id;
3021         $DB->insert_record('user_preferences', $pref, false);
3022     }
3025 /**
3026  * Increment or reset user's email bounce count
3027  *
3028  * @global object
3029  * @param user $user object containing an id
3030  * @param bool $reset will reset the count to 0
3031  */
3032 function set_bounce_count($user,$reset=false) {
3033     global $DB;
3035     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3036         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3037         $DB->update_record('user_preferences', $pref);
3038     }
3039     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3040         // make a new one
3041         $pref = new stdClass();
3042         $pref->name   = 'email_bounce_count';
3043         $pref->value  = 1;
3044         $pref->userid = $user->id;
3045         $DB->insert_record('user_preferences', $pref, false);
3046     }
3049 /**
3050  * Keeps track of login attempts
3051  *
3052  * @global object
3053  */
3054 function update_login_count() {
3055     global $SESSION;
3057     $max_logins = 10;
3059     if (empty($SESSION->logincount)) {
3060         $SESSION->logincount = 1;
3061     } else {
3062         $SESSION->logincount++;
3063     }
3065     if ($SESSION->logincount > $max_logins) {
3066         unset($SESSION->wantsurl);
3067         print_error('errortoomanylogins');
3068     }
3071 /**
3072  * Resets login attempts
3073  *
3074  * @global object
3075  */
3076 function reset_login_count() {
3077     global $SESSION;
3079     $SESSION->logincount = 0;
3082 /**
3083  * Determines if the currently logged in user is in editing mode.
3084  * Note: originally this function had $userid parameter - it was not usable anyway
3085  *
3086  * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3087  * @todo Deprecated function remove when ready
3088  *
3089  * @global object
3090  * @uses DEBUG_DEVELOPER
3091  * @return bool
3092  */
3093 function isediting() {
3094     global $PAGE;
3095     debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3096     return $PAGE->user_is_editing();
3099 /**
3100  * Determines if the logged in user is currently moving an activity
3101  *
3102  * @global object
3103  * @param int $courseid The id of the course being tested
3104  * @return bool
3105  */
3106 function ismoving($courseid) {
3107     global $USER;
3109     if (!empty($USER->activitycopy)) {
3110         return ($USER->activitycopycourse == $courseid);
3111     }
3112     return false;
3115 /**
3116  * Returns a persons full name
3117  *
3118  * Given an object containing firstname and lastname
3119  * values, this function returns a string with the
3120  * full name of the person.
3121  * The result may depend on system settings
3122  * or language.  'override' will force both names
3123  * to be used even if system settings specify one.
3124  *
3125  * @global object
3126  * @global object
3127  * @param object $user A {@link $USER} object to get full name of
3128  * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3129  * @return string
3130  */
3131 function fullname($user, $override=false) {
3132     global $CFG, $SESSION;
3134     if (!isset($user->firstname) and !isset($user->lastname)) {
3135         return '';
3136     }
3138     if (!$override) {
3139         if (!empty($CFG->forcefirstname)) {
3140             $user->firstname = $CFG->forcefirstname;
3141         }
3142         if (!empty($CFG->forcelastname)) {
3143             $user->lastname = $CFG->forcelastname;
3144         }
3145     }
3147     if (!empty($SESSION->fullnamedisplay)) {
3148         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3149     }
3151     if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3152         return $user->firstname .' '. $user->lastname;
3154     } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3155         return $user->lastname .' '. $user->firstname;
3157     } else if ($CFG->fullnamedisplay == 'firstname') {
3158         if ($override) {
3159             return get_string('fullnamedisplay', '', $user);
3160         } else {
3161             return $user->firstname;
3162         }
3163     }
3165     return get_string('fullnamedisplay', '', $user);
3168 /**
3169  * Returns whether a given authentication plugin exists.
3170  *
3171  * @global object
3172  * @param string $auth Form of authentication to check for. Defaults to the
3173  *        global setting in {@link $CFG}.
3174  * @return boolean Whether the plugin is available.
3175  */
3176 function exists_auth_plugin($auth) {
3177     global $CFG;
3179     if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3180         return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3181     }
3182     return false;
3185 /**
3186  * Checks if a given plugin is in the list of enabled authentication plugins.
3187  *
3188  * @param string $auth Authentication plugin.
3189  * @return boolean Whether the plugin is enabled.
3190  */
3191 function is_enabled_auth($auth) {
3192     if (empty($auth)) {
3193         return false;
3194     }
3196     $enabled = get_enabled_auth_plugins();
3198     return in_array($auth, $enabled);
3201 /**
3202  * Returns an authentication plugin instance.
3203  *
3204  * @global object
3205  * @param string $auth name of authentication plugin
3206  * @return auth_plugin_base An instance of the required authentication plugin.
3207  */
3208 function get_auth_plugin($auth) {
3209     global $CFG;
3211     // check the plugin exists first
3212     if (! exists_auth_plugin($auth)) {
3213         print_error('authpluginnotfound', 'debug', '', $auth);
3214     }
3216     // return auth plugin instance
3217     require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3218     $class = "auth_plugin_$auth";
3219     return new $class;
3222 /**
3223  * Returns array of active auth plugins.
3224  *
3225  * @param bool $fix fix $CFG->auth if needed
3226  * @return array
3227  */
3228 function get_enabled_auth_plugins($fix=false) {
3229     global $CFG;
3231     $default = array('manual', 'nologin');
3233     if (empty($CFG->auth)) {
3234         $auths = array();
3235     } else {
3236         $auths = explode(',', $CFG->auth);
3237     }
3239     if ($fix) {
3240         $auths = array_unique($auths);
3241         foreach($auths as $k=>$authname) {
3242             if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3243                 unset($auths[$k]);
3244             }
3245         }
3246         $newconfig = implode(',', $auths);
3247         if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3248             set_config('auth', $newconfig);
3249         }
3250     }
3252     return (array_merge($default, $auths));
3255 /**
3256  * Returns true if an internal authentication method is being used.
3257  * if method not specified then, global default is assumed
3258  *
3259  * @param string $auth Form of authentication required
3260  * @return bool
3261  */
3262 function is_internal_auth($auth) {
3263     $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3264     return $authplugin->is_internal();
3267 /**
3268  * Returns true if the user is a 'restored' one
3269  *
3270  * Used in the login process to inform the user
3271  * and allow him/her to reset the password
3272  *
3273  * @uses $CFG
3274  * @uses $DB
3275  * @param string $username username to be checked
3276  * @return bool
3277  */
3278 function is_restored_user($username) {
3279     global $CFG, $DB;
3281     return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3284 /**
3285  * Returns an array of user fields
3286  *
3287  * @return array User field/column names
3288  */
3289 function get_user_fieldnames() {
3290     global $DB;
3292     $fieldarray = $DB->get_columns('user');
3293     unset($fieldarray['id']);
3294     $fieldarray = array_keys($fieldarray);
3296     return $fieldarray;
3299 /**
3300  * Creates a bare-bones user record
3301  *
3302  * @todo Outline auth types and provide code example
3303  *
3304  * @param string $username New user's username to add to record
3305  * @param string $password New user's password to add to record
3306  * @param string $auth Form of authentication required
3307  * @return stdClass A complete user object
3308  */
3309 function create_user_record($username, $password, $auth = 'manual') {
3310     global $CFG, $DB;
3312     //just in case check text case
3313     $username = trim(moodle_strtolower($username));
3315     $authplugin = get_auth_plugin($auth);
3317     $newuser = new stdClass();
3319     if ($newinfo = $authplugin->get_userinfo($username)) {
3320         $newinfo = truncate_userinfo($newinfo);
3321         foreach ($newinfo as $key => $value){
3322             $newuser->$key = $value;
3323         }
3324     }
3326     if (!empty($newuser->email)) {
3327         if (email_is_not_allowed($newuser->email)) {
3328             unset($newuser->email);
3329         }
3330     }
3332     if (!isset($newuser->city)) {
3333         $newuser->city = '';
3334     }
3336     $newuser->auth = $auth;
3337     $newuser->username = $username;
3339     // fix for MDL-8480
3340     // user CFG lang for user if $newuser->lang is empty
3341     // or $user->lang is not an installed language
3342     if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3343         $newuser->lang = $CFG->lang;
3344     }
3345     $newuser->confirmed = 1;
3346     $newuser->lastip = getremoteaddr();
3347     $newuser->timemodified = time();
3348     $newuser->mnethostid = $CFG->mnet_localhost_id;
3350     $newuser->id = $DB->insert_record('user', $newuser);
3351     $user = get_complete_user_data('id', $newuser->id);
3352     if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3353         set_user_preference('auth_forcepasswordchange', 1, $user);
3354     }
3355     update_internal_user_password($user, $password);
3357     // fetch full user record for the event, the complete user data contains too much info
3358     // and we want to be consistent with other places that trigger this event
3359     events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
3361     return $user;
3364 /**
3365  * Will update a local user record from an external source.
3366  * (MNET users can not be updated using this method!)
3367  *
3368  * @param string $username user's username to update the record
3369  * @return stdClass A complete user object
3370  */
3371 function update_user_record($username) {
3372     global $DB, $CFG;
3374     $username = trim(moodle_strtolower($username)); /// just in case check text case
3376     $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
3377     $newuser = array();
3378     $userauth = get_auth_plugin($oldinfo->auth);
3380     if ($newinfo = $userauth->get_userinfo($username)) {
3381         $newinfo = truncate_userinfo($newinfo);
3382         foreach ($newinfo as $key => $value){
3383             $key = strtolower($key);
3384             if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id'
3385                     or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3386                 // unknown or must not be changed
3387                 continue;
3388             }
3389             $confval = $userauth->config->{'field_updatelocal_' . $key};
3390             $lockval = $userauth->config->{'field_lock_' . $key};
3391             if (empty($confval) || empty($lockval)) {
3392                 continue;
3393             }
3394             if ($confval === 'onlogin') {
3395                 // MDL-4207 Don't overwrite modified user profile values with
3396                 // empty LDAP values when 'unlocked if empty' is set. The purpose
3397                 // of the setting 'unlocked if empty' is to allow the user to fill
3398                 // in a value for the selected field _if LDAP is giving
3399                 // nothing_ for this field. Thus it makes sense to let this value
3400                 // stand in until LDAP is giving a value for this field.
3401                 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3402                     if ((string)$oldinfo->$key !== (string)$value) {
3403                         $newuser[$key] = (string)$value;
3404                     }
3405                 }
3406             }
3407         }
3408         if ($newuser) {
3409             $newuser['id'] = $oldinfo->id;
3410             $DB->update_record('user', $newuser);
3411             // fetch full user record for the event, the complete user data contains too much info
3412             // and we want to be consistent with other places that trigger this event
3413             events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id)));
3414         }
3415     }
3417     return get_complete_user_data('id', $oldinfo->id);
3420 /**
3421  * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3422  * which may have large fields
3423  *
3424  * @todo Add vartype handling to ensure $info is an array
3425  *
3426  * @param array $info Array of user properties to truncate if needed
3427  * @return array The now truncated information that was passed in
3428  */
3429 function truncate_userinfo($info) {
3430     // define the limits
3431     $limit = array(
3432                     'username'    => 100,
3433                     'idnumber'    => 255,
3434                     'firstname'   => 100,
3435                     'lastname'    => 100,
3436                     'email'       => 100,
3437                     'icq'         =>  15,
3438                     'phone1'      =>  20,
3439                     'phone2'      =>  20,
3440                     'institution' =>  40,
3441                     'department'  =>  30,
3442                     'address'     =>  70,
3443                     'city'        => 120,
3444                     'country'     =>   2,
3445                     'url'         => 255,
3446                     );
3448     $textlib = textlib_get_instance();
3449     // apply where needed
3450     foreach (array_keys($info) as $key) {
3451         if (!empty($limit[$key])) {
3452             $info[$key] = trim($textlib->substr($info[$key],0, $limit[$key]));
3453         }
3454     }
3456     return $info;
3459 /**
3460  * Marks user deleted in internal user database and notifies the auth plugin.
3461  * Also unenrols user from all roles and does other cleanup.
3462  *
3463  * Any plugin that needs to purge user data should register the 'user_deleted' event.
3464  *
3465  * @param stdClass $user full user object before delete
3466  * @return boolean always true
3467  */
3468 function delete_user($user) {
3469     global $CFG, $DB;
3470     require_once($CFG->libdir.'/grouplib.php');
3471     require_once($CFG->libdir.'/gradelib.php');
3472     require_once($CFG->dirroot.'/message/lib.php');
3473     require_once($CFG->dirroot.'/tag/lib.php');
3475     // delete all grades - backup is kept in grade_grades_history table
3476     grade_user_delete($user->id);
3478     //move unread messages from this user to read
3479     message_move_userfrom_unread2read($user->id);
3481     // TODO: remove from cohorts using standard API here
3483     // remove user tags
3484     tag_set('user', $user->id, array());
3486     // unconditionally unenrol from all courses
3487     enrol_user_delete($user);
3489     // unenrol from all roles in all contexts
3490     role_unassign_all(array('userid'=>$user->id)); // this might be slow but it is really needed - modules might do some extra cleanup!
3492     //now do a brute force cleanup
3494     // remove from all cohorts
3495     $DB->delete_records('cohort_members', array('userid'=>$user->id));
3497     // remove from all groups
3498     $DB->delete_records('groups_members', array('userid'=>$user->id));
3500     // brute force unenrol from all courses
3501     $DB->delete_records('user_enrolments', array('userid'=>$user->id));
3503     // purge user preferences
3504     $DB->delete_records('user_preferences', array('userid'=>$user->id));
3506     // purge user extra profile info
3507     $DB->delete_records('user_info_data', array('userid'=>$user->id));
3509     // last course access not necessary either
3510     $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
3512     // force logout - may fail if file based sessions used, sorry
3513     session_kill_user($user->id);
3515     // now do a final accesslib cleanup - removes all role assignments in user context and context itself
3516     delete_context(CONTEXT_USER, $user->id);
3518     // workaround for bulk deletes of users with the same email address
3519     $delname = "$user->email.".time();
3520     while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3521         $delname++;
3522     }
3524     // mark internal user record as "deleted"
3525     $updateuser = new stdClass();
3526     $updateuser->id           = $user->id;
3527     $updateuser->deleted      = 1;
3528     $updateuser->username     = $delname;            // Remember it just in case
3529     $updateuser->email        = md5($user->username);// Store hash of username, useful importing/restoring users
3530     $updateuser->idnumber     = '';                  // Clear this field to free it up
3531     $updateuser->timemodified = time();
3533     $DB->update_record('user', $updateuser);
3535     // notify auth plugin - do not block the delete even when plugin fails
3536     $authplugin = get_auth_plugin($user->auth);
3537     $authplugin->user_delete($user);
3539     // any plugin that needs to cleanup should register this event
3540     events_trigger('user_deleted', $user);
3542     return true;
3545 /**
3546  * Retrieve the guest user object
3547  *
3548  * @global object
3549  * @global object
3550  * @return user A {@link $USER} object
3551  */
3552 function guest_user() {
3553     global $CFG, $DB;
3555     if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
3556         $newuser->confirmed = 1;
3557         $newuser->lang = $CFG->lang;
3558         $newuser->lastip = getremoteaddr();
3559     }
3561     return $newuser;
3564 /**
3565  * Authenticates a user against the chosen authentication mechanism
3566  *
3567  * Given a username and password, this function looks them
3568  * up using the currently selected authentication mechanism,
3569  * and if the authentication is successful, it returns a
3570  * valid $user object from the 'user' table.
3571  *
3572  * Uses auth_ functions from the currently active auth module
3573  *
3574  * After authenticate_user_login() returns success, you will need to
3575  * log that the user has logged in, and call complete_user_login() to set
3576  * the session up.
3577  *
3578  * Note: this function works only with non-mnet accounts!
3579  *
3580  * @param string $username  User's username
3581  * @param string $password  User's password
3582  * @return user|flase A {@link $USER} object or false if error
3583  */
3584 function authenticate_user_login($username, $password) {
3585     global $CFG, $DB;
3587     $authsenabled = get_enabled_auth_plugins();
3589     if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
3590         $auth = empty($user->auth) ? 'manual' : $user->auth;  // use manual if auth not set
3591         if (!empty($user->suspended)) {
3592             add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3593             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Suspended Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3594             return false;
3595         }
3596         if ($auth=='nologin' or !is_enabled_auth($auth)) {
3597             add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3598             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Disabled Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3599             return false;
3600         }
3601         $auths = array($auth);
3603     } else {
3604         // check if there's a deleted record (cheaply)
3605         if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
3606             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Deleted Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3607             return false;
3608         }
3610         // User does not exist
3611         $auths = $authsenabled;
3612         $user = new stdClass();
3613         $user->id = 0;
3614     }
3616     foreach ($auths as $auth) {
3617         $authplugin = get_auth_plugin($auth);
3619         // on auth fail fall through to the next plugin
3620         if (!$authplugin->user_login($username, $password)) {
3621             continue;
3622         }
3624         // successful authentication
3625         if ($user->id) {                          // User already exists in database
3626             if (empty($user->auth)) {             // For some reason auth isn't set yet
3627                 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
3628                 $user->auth = $auth;
3629             }
3630             if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3631                 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
3632                 $user->firstaccess = $user->timemodified;
3633             }
3635             update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3637             if ($authplugin->is_synchronised_with_external()) { // update user record from external DB
3638                 $user = update_user_record($username);
3639             }
3640         } else {
3641             // if user not found, create him
3642             $user = create_user_record($username, $password, $auth);
3643         }
3645         $authplugin->sync_roles($user);
3647         foreach ($authsenabled as $hau) {
3648             $hauth = get_auth_plugin($hau);
3649             $hauth->user_authenticated_hook($user, $username, $password);
3650         }
3652         if (empty($user->id)) {
3653             return false;
3654         }
3656         if (!empty($user->suspended)) {
3657             // just in case some auth plugin suspended account
3658             add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3659             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Suspended Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3660             return false;
3661         }
3663         return $user;
3664     }
3666     // failed if all the plugins have failed
3667     add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3668     if (debugging('', DEBUG_ALL)) {
3669         error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Failed Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3670     }
3671     return false;
3674 /**
3675  * Call to complete the user login process after authenticate_user_login()
3676  * has succeeded. It will setup the $USER variable and other required bits
3677  * and pieces.
3678  *
3679  * NOTE:
3680  * - It will NOT log anything -- up to the caller to decide what to log.
3681  * - this function does not set any cookies any more!
3682  *
3683  * @param object $user
3684  * @return object A {@link $USER} object - BC only, do not use
3685  */