MDL-24446 prevent problems with invalid values of CFG->maxbytes
[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
182  */
183 define('PARAM_RAW', 'raw');
185 /**
186  * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
187  */
188 define('PARAM_SAFEDIR',  'safedir');
190 /**
191  * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
192  */
193 define('PARAM_SAFEPATH',  'safepath');
195 /**
196  * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9.  Numbers and comma only.
197  */
198 define('PARAM_SEQUENCE',  'sequence');
200 /**
201  * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
202  */
203 define('PARAM_TAG',   'tag');
205 /**
206  * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
207  */
208 define('PARAM_TAGLIST',   'taglist');
210 /**
211  * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
212  */
213 define('PARAM_TEXT',  'text');
215 /**
216  * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
217  */
218 define('PARAM_THEME',  'theme');
220 /**
221  * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
222  */
223 define('PARAM_URL',      'url');
225 /**
226  * 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!!
227  */
228 define('PARAM_USERNAME',    'username');
230 /**
231  * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
232  */
233 define('PARAM_STRINGID',    'stringid');
235 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE  /////
236 /**
237  * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
238  * It was one of the first types, that is why it is abused so much ;-)
239  * @deprecated since 2.0
240  */
241 define('PARAM_CLEAN',    'clean');
243 /**
244  * PARAM_INTEGER - deprecated alias for PARAM_INT
245  */
246 define('PARAM_INTEGER',  'int');
248 /**
249  * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
250  */
251 define('PARAM_NUMBER',  'float');
253 /**
254  * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
255  * NOTE: originally alias for PARAM_APLHA
256  */
257 define('PARAM_ACTION',   'alphanumext');
259 /**
260  * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
261  * NOTE: originally alias for PARAM_APLHA
262  */
263 define('PARAM_FORMAT',   'alphanumext');
265 /**
266  * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
267  */
268 define('PARAM_MULTILANG',  'text');
270 /**
271  * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
272  */
273 define('PARAM_CLEANFILE', 'file');
275 /// Web Services ///
277 /**
278  * VALUE_REQUIRED - if the parameter is not supplied, there is an error
279  */
280 define('VALUE_REQUIRED', 1);
282 /**
283  * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
284  */
285 define('VALUE_OPTIONAL', 2);
287 /**
288  * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
289  */
290 define('VALUE_DEFAULT', 0);
292 /**
293  * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
294  */
295 define('NULL_NOT_ALLOWED', false);
297 /**
298  * NULL_ALLOWED - the parameter can be set to null in the database
299  */
300 define('NULL_ALLOWED', true);
302 /// Page types ///
303 /**
304  * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
305  */
306 define('PAGE_COURSE_VIEW', 'course-view');
308 /** Get remote addr constant */
309 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
310 /** Get remote addr constant */
311 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
313 /// Blog access level constant declaration ///
314 define ('BLOG_USER_LEVEL', 1);
315 define ('BLOG_GROUP_LEVEL', 2);
316 define ('BLOG_COURSE_LEVEL', 3);
317 define ('BLOG_SITE_LEVEL', 4);
318 define ('BLOG_GLOBAL_LEVEL', 5);
321 ///Tag constants///
322 /**
323  * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
324  * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
325  * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
326  *
327  * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
328  */
329 define('TAG_MAX_LENGTH', 50);
331 /// Password policy constants ///
332 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
333 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
334 define ('PASSWORD_DIGITS', '0123456789');
335 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
337 /// Feature constants ///
338 // Used for plugin_supports() to report features that are, or are not, supported by a module.
340 /** True if module can provide a grade */
341 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
342 /** True if module supports outcomes */
343 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
345 /** True if module has code to track whether somebody viewed it */
346 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
347 /** True if module has custom completion rules */
348 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
350 /** True if module supports outcomes */
351 define('FEATURE_IDNUMBER', 'idnumber');
352 /** True if module supports groups */
353 define('FEATURE_GROUPS', 'groups');
354 /** True if module supports groupings */
355 define('FEATURE_GROUPINGS', 'groupings');
356 /** True if module supports groupmembersonly */
357 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
359 /** Type of module */
360 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
361 /** True if module supports intro editor */
362 define('FEATURE_MOD_INTRO', 'mod_intro');
363 /** True if module has default completion */
364 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
366 define('FEATURE_COMMENT', 'comment');
368 define('FEATURE_RATE', 'rate');
369 /** True if module supports backup/restore of moodle2 format */
370 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
372 /** Unspecified module archetype */
373 define('MOD_ARCHETYPE_OTHER', 0);
374 /** Resource-like type module */
375 define('MOD_ARCHETYPE_RESOURCE', 1);
376 /** Assignment module archetype */
377 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
379 /**
380  * Security token used for allowing access
381  * from external application such as web services.
382  * Scripts do not use any session, performance is relatively
383  * low because we need to load access info in each request.
384  * Scripts are executed in parallel.
385  */
386 define('EXTERNAL_TOKEN_PERMANENT', 0);
388 /**
389  * Security token used for allowing access
390  * of embedded applications, the code is executed in the
391  * active user session. Token is invalidated after user logs out.
392  * Scripts are executed serially - normal session locking is used.
393  */
394 define('EXTERNAL_TOKEN_EMBEDDED', 1);
396 /**
397  * The home page should be the site home
398  */
399 define('HOMEPAGE_SITE', 0);
400 /**
401  * The home page should be the users my page
402  */
403 define('HOMEPAGE_MY', 1);
404 /**
405  * The home page can be chosen by the user
406  */
407 define('HOMEPAGE_USER', 2);
409 /**
410  * Hub directory url (should be moodle.org)
411  */
412 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
415 /**
416  * Moodle.org url (should be moodle.org)
417  */
418 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
421 /// PARAMETER HANDLING ////////////////////////////////////////////////////
423 /**
424  * Returns a particular value for the named variable, taken from
425  * POST or GET.  If the parameter doesn't exist then an error is
426  * thrown because we require this variable.
427  *
428  * This function should be used to initialise all required values
429  * in a script that are based on parameters.  Usually it will be
430  * used like this:
431  *    $id = required_param('id', PARAM_INT);
432  *
433  * Please note the $type parameter is now required,
434  * for now PARAM_CLEAN is used for backwards compatibility only.
435  *
436  * @param string $parname the name of the page parameter we want
437  * @param string $type expected type of parameter
438  * @return mixed
439  */
440 function required_param($parname, $type) {
441     if (!isset($type)) {
442         debugging('required_param() requires $type to be specified.');
443         $type = PARAM_CLEAN; // for now let's use this deprecated type
444     }
445     if (isset($_POST[$parname])) {       // POST has precedence
446         $param = $_POST[$parname];
447     } else if (isset($_GET[$parname])) {
448         $param = $_GET[$parname];
449     } else {
450         print_error('missingparam', '', '', $parname);
451     }
453     return clean_param($param, $type);
456 /**
457  * Returns a particular value for the named variable, taken from
458  * POST or GET, otherwise returning a given default.
459  *
460  * This function should be used to initialise all optional values
461  * in a script that are based on parameters.  Usually it will be
462  * used like this:
463  *    $name = optional_param('name', 'Fred', PARAM_TEXT);
464  *
465  * Please note $default and $type parameters are now required,
466  * for now PARAM_CLEAN is used for backwards compatibility only.
467  *
468  * @param string $parname the name of the page parameter we want
469  * @param mixed  $default the default value to return if nothing is found
470  * @param string $type expected type of parameter
471  * @return mixed
472  */
473 function optional_param($parname, $default, $type) {
474     if (!isset($type)) {
475         debugging('optional_param() requires $default and $type to be specified.');
476         $type = PARAM_CLEAN; // for now let's use this deprecated type
477     }
478     if (!isset($default)) {
479         $default = null;
480     }
482     if (isset($_POST[$parname])) {       // POST has precedence
483         $param = $_POST[$parname];
484     } else if (isset($_GET[$parname])) {
485         $param = $_GET[$parname];
486     } else {
487         return $default;
488     }
490     return clean_param($param, $type);
493 /**
494  * Strict validation of parameter values, the values are only converted
495  * to requested PHP type. Internally it is using clean_param, the values
496  * before and after cleaning must be equal - otherwise
497  * an invalid_parameter_exception is thrown.
498  * Objects and classes are not accepted.
499  *
500  * @param mixed $param
501  * @param int $type PARAM_ constant
502  * @param bool $allownull are nulls valid value?
503  * @param string $debuginfo optional debug information
504  * @return mixed the $param value converted to PHP type or invalid_parameter_exception
505  */
506 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
507     if (is_null($param)) {
508         if ($allownull == NULL_ALLOWED) {
509             return null;
510         } else {
511             throw new invalid_parameter_exception($debuginfo);
512         }
513     }
514     if (is_array($param) or is_object($param)) {
515         throw new invalid_parameter_exception($debuginfo);
516     }
518     $cleaned = clean_param($param, $type);
519     if ((string)$param !== (string)$cleaned) {
520         // conversion to string is usually lossless
521         throw new invalid_parameter_exception($debuginfo);
522     }
524     return $cleaned;
527 /**
528  * Used by {@link optional_param()} and {@link required_param()} to
529  * clean the variables and/or cast to specific types, based on
530  * an options field.
531  * <code>
532  * $course->format = clean_param($course->format, PARAM_ALPHA);
533  * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
534  * </code>
535  *
536  * @param mixed $param the variable we are cleaning
537  * @param int $type expected format of param after cleaning.
538  * @return mixed
539  */
540 function clean_param($param, $type) {
542     global $CFG;
544     if (is_array($param)) {              // Let's loop
545         $newparam = array();
546         foreach ($param as $key => $value) {
547             $newparam[$key] = clean_param($value, $type);
548         }
549         return $newparam;
550     }
552     switch ($type) {
553         case PARAM_RAW:          // no cleaning at all
554             return $param;
556         case PARAM_CLEAN:        // General HTML cleaning, try to use more specific type if possible
557             // this is deprecated!, please use more specific type instead
558             if (is_numeric($param)) {
559                 return $param;
560             }
561             return clean_text($param);     // Sweep for scripts, etc
563         case PARAM_CLEANHTML:    // clean html fragment
564             $param = clean_text($param, FORMAT_HTML);     // Sweep for scripts, etc
565             return trim($param);
567         case PARAM_INT:
568             return (int)$param;  // Convert to integer
570         case PARAM_FLOAT:
571         case PARAM_NUMBER:
572             return (float)$param;  // Convert to float
574         case PARAM_ALPHA:        // Remove everything not a-z
575             return preg_replace('/[^a-zA-Z]/i', '', $param);
577         case PARAM_ALPHAEXT:     // Remove everything not a-zA-Z_- (originally allowed "/" too)
578             return preg_replace('/[^a-zA-Z_-]/i', '', $param);
580         case PARAM_ALPHANUM:     // Remove everything not a-zA-Z0-9
581             return preg_replace('/[^A-Za-z0-9]/i', '', $param);
583         case PARAM_ALPHANUMEXT:     // Remove everything not a-zA-Z0-9_-
584             return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
586         case PARAM_SEQUENCE:     // Remove everything not 0-9,
587             return preg_replace('/[^0-9,]/i', '', $param);
589         case PARAM_BOOL:         // Convert to 1 or 0
590             $tempstr = strtolower($param);
591             if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
592                 $param = 1;
593             } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
594                 $param = 0;
595             } else {
596                 $param = empty($param) ? 0 : 1;
597             }
598             return $param;
600         case PARAM_NOTAGS:       // Strip all tags
601             return strip_tags($param);
603         case PARAM_TEXT:    // leave only tags needed for multilang
604             // if the multilang syntax is not correct we strip all tags
605             // because it would break xhtml strict which is required for accessibility standards
606             // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
607             do {
608                 if (strpos($param, '</lang>') !== false) {
609                     // old and future mutilang syntax
610                     $param = strip_tags($param, '<lang>');
611                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
612                         break;
613                     }
614                     $open = false;
615                     foreach ($matches[0] as $match) {
616                         if ($match === '</lang>') {
617                             if ($open) {
618                                 $open = false;
619                                 continue;
620                             } else {
621                                 break 2;
622                             }
623                         }
624                         if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
625                             break 2;
626                         } else {
627                             $open = true;
628                         }
629                     }
630                     if ($open) {
631                         break;
632                     }
633                     return $param;
635                 } else if (strpos($param, '</span>') !== false) {
636                     // current problematic multilang syntax
637                     $param = strip_tags($param, '<span>');
638                     if (!preg_match_all('/<.*>/suU', $param, $matches)) {
639                         break;
640                     }
641                     $open = false;
642                     foreach ($matches[0] as $match) {
643                         if ($match === '</span>') {
644                             if ($open) {
645                                 $open = false;
646                                 continue;
647                             } else {
648                                 break 2;
649                             }
650                         }
651                         if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
652                             break 2;
653                         } else {
654                             $open = true;
655                         }
656                     }
657                     if ($open) {
658                         break;
659                     }
660                     return $param;
661                 }
662             } while (false);
663             // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
664             return strip_tags($param);
666         case PARAM_SAFEDIR:      // Remove everything not a-zA-Z0-9_-
667             return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
669         case PARAM_SAFEPATH:     // Remove everything not a-zA-Z0-9/_-
670             return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
672         case PARAM_FILE:         // Strip all suspicious characters from filename
673             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
674             $param = preg_replace('~\.\.+~', '', $param);
675             if ($param === '.') {
676                 $param = '';
677             }
678             return $param;
680         case PARAM_PATH:         // Strip all suspicious characters from file path
681             $param = str_replace('\\', '/', $param);
682             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
683             $param = preg_replace('~\.\.+~', '', $param);
684             $param = preg_replace('~//+~', '/', $param);
685             return preg_replace('~/(\./)+~', '/', $param);
687         case PARAM_HOST:         // allow FQDN or IPv4 dotted quad
688             $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
689             // match ipv4 dotted quad
690             if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
691                 // confirm values are ok
692                 if ( $match[0] > 255
693                      || $match[1] > 255
694                      || $match[3] > 255
695                      || $match[4] > 255 ) {
696                     // hmmm, what kind of dotted quad is this?
697                     $param = '';
698                 }
699             } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
700                        && !preg_match('/^[\.-]/',  $param) // no leading dots/hyphens
701                        && !preg_match('/[\.-]$/',  $param) // no trailing dots/hyphens
702                        ) {
703                 // all is ok - $param is respected
704             } else {
705                 // all is not ok...
706                 $param='';
707             }
708             return $param;
710         case PARAM_URL:          // allow safe ftp, http, mailto urls
711             include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
712             if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
713                 // all is ok, param is respected
714             } else {
715                 $param =''; // not really ok
716             }
717             return $param;
719         case PARAM_LOCALURL:     // allow http absolute, root relative and relative URLs within wwwroot
720             $param = clean_param($param, PARAM_URL);
721             if (!empty($param)) {
722                 if (preg_match(':^/:', $param)) {
723                     // root-relative, ok!
724                 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
725                     // absolute, and matches our wwwroot
726                 } else {
727                     // relative - let's make sure there are no tricks
728                     if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
729                         // looks ok.
730                     } else {
731                         $param = '';
732                     }
733                 }
734             }
735             return $param;
737         case PARAM_PEM:
738             $param = trim($param);
739             // PEM formatted strings may contain letters/numbers and the symbols
740             // forward slash: /
741             // plus sign:     +
742             // equal sign:    =
743             // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
744             if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
745                 list($wholething, $body) = $matches;
746                 unset($wholething, $matches);
747                 $b64 = clean_param($body, PARAM_BASE64);
748                 if (!empty($b64)) {
749                     return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
750                 } else {
751                     return '';
752                 }
753             }
754             return '';
756         case PARAM_BASE64:
757             if (!empty($param)) {
758                 // PEM formatted strings may contain letters/numbers and the symbols
759                 // forward slash: /
760                 // plus sign:     +
761                 // equal sign:    =
762                 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
763                     return '';
764                 }
765                 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
766                 // Each line of base64 encoded data must be 64 characters in
767                 // length, except for the last line which may be less than (or
768                 // equal to) 64 characters long.
769                 for ($i=0, $j=count($lines); $i < $j; $i++) {
770                     if ($i + 1 == $j) {
771                         if (64 < strlen($lines[$i])) {
772                             return '';
773                         }
774                         continue;
775                     }
777                     if (64 != strlen($lines[$i])) {
778                         return '';
779                     }
780                 }
781                 return implode("\n",$lines);
782             } else {
783                 return '';
784             }
786         case PARAM_TAG:
787             //as long as magic_quotes_gpc is used, a backslash will be a
788             //problem, so remove *all* backslash.
789             //$param = str_replace('\\', '', $param);
790             //remove some nasties
791             $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
792             //convert many whitespace chars into one
793             $param = preg_replace('/\s+/', ' ', $param);
794             $textlib = textlib_get_instance();
795             $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
796             return $param;
799         case PARAM_TAGLIST:
800             $tags = explode(',', $param);
801             $result = array();
802             foreach ($tags as $tag) {
803                 $res = clean_param($tag, PARAM_TAG);
804                 if ($res !== '') {
805                     $result[] = $res;
806                 }
807             }
808             if ($result) {
809                 return implode(',', $result);
810             } else {
811                 return '';
812             }
814         case PARAM_CAPABILITY:
815             if (get_capability_info($param)) {
816                 return $param;
817             } else {
818                 return '';
819             }
821         case PARAM_PERMISSION:
822             $param = (int)$param;
823             if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
824                 return $param;
825             } else {
826                 return CAP_INHERIT;
827             }
829         case PARAM_AUTH:
830             $param = clean_param($param, PARAM_SAFEDIR);
831             if (exists_auth_plugin($param)) {
832                 return $param;
833             } else {
834                 return '';
835             }
837         case PARAM_LANG:
838             $param = clean_param($param, PARAM_SAFEDIR);
839             if (get_string_manager()->translation_exists($param)) {
840                 return $param;
841             } else {
842                 return ''; // Specified language is not installed or param malformed
843             }
845         case PARAM_THEME:
846             $param = clean_param($param, PARAM_SAFEDIR);
847             if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
848                 return $param;
849             } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
850                 return $param;
851             } else {
852                 return '';  // Specified theme is not installed
853             }
855         case PARAM_USERNAME:
856             $param = str_replace(" " , "", $param);
857             $param = moodle_strtolower($param);  // Convert uppercase to lowercase MDL-16919
858             if (empty($CFG->extendedusernamechars)) {
859                 // regular expression, eliminate all chars EXCEPT:
860                 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
861                 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
862             }
863             return $param;
865         case PARAM_EMAIL:
866             if (validate_email($param)) {
867                 return $param;
868             } else {
869                 return '';
870             }
872         case PARAM_STRINGID:
873             if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
874                 return $param;
875             } else {
876                 return '';
877             }
879         default:                 // throw error, switched parameters in optional_param or another serious problem
880             print_error("unknownparamtype", '', '', $type);
881     }
884 /**
885  * Return true if given value is integer or string with integer value
886  *
887  * @param mixed $value String or Int
888  * @return bool true if number, false if not
889  */
890 function is_number($value) {
891     if (is_int($value)) {
892         return true;
893     } else if (is_string($value)) {
894         return ((string)(int)$value) === $value;
895     } else {
896         return false;
897     }
900 /**
901  * Returns host part from url
902  * @param string $url full url
903  * @return string host, null if not found
904  */
905 function get_host_from_url($url) {
906     preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
907     if ($matches) {
908         return $matches[1];
909     }
910     return null;
913 /**
914  * Tests whether anything was returned by text editor
915  *
916  * This function is useful for testing whether something you got back from
917  * the HTML editor actually contains anything. Sometimes the HTML editor
918  * appear to be empty, but actually you get back a <br> tag or something.
919  *
920  * @param string $string a string containing HTML.
921  * @return boolean does the string contain any actual content - that is text,
922  * images, objects, etc.
923  */
924 function html_is_blank($string) {
925     return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
928 /**
929  * Set a key in global configuration
930  *
931  * Set a key/value pair in both this session's {@link $CFG} global variable
932  * and in the 'config' database table for future sessions.
933  *
934  * Can also be used to update keys for plugin-scoped configs in config_plugin table.
935  * In that case it doesn't affect $CFG.
936  *
937  * A NULL value will delete the entry.
938  *
939  * @global object
940  * @global object
941  * @param string $name the key to set
942  * @param string $value the value to set (without magic quotes)
943  * @param string $plugin (optional) the plugin scope, default NULL
944  * @return bool true or exception
945  */
946 function set_config($name, $value, $plugin=NULL) {
947     global $CFG, $DB;
949     if (empty($plugin)) {
950         if (!array_key_exists($name, $CFG->config_php_settings)) {
951             // So it's defined for this invocation at least
952             if (is_null($value)) {
953                 unset($CFG->$name);
954             } else {
955                 $CFG->$name = (string)$value; // settings from db are always strings
956             }
957         }
959         if ($DB->get_field('config', 'name', array('name'=>$name))) {
960             if ($value === null) {
961                 $DB->delete_records('config', array('name'=>$name));
962             } else {
963                 $DB->set_field('config', 'value', $value, array('name'=>$name));
964             }
965         } else {
966             if ($value !== null) {
967                 $config = new stdClass();
968                 $config->name  = $name;
969                 $config->value = $value;
970                 $DB->insert_record('config', $config, false);
971             }
972         }
974     } else { // plugin scope
975         if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
976             if ($value===null) {
977                 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
978             } else {
979                 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
980             }
981         } else {
982             if ($value !== null) {
983                 $config = new stdClass();
984                 $config->plugin = $plugin;
985                 $config->name   = $name;
986                 $config->value  = $value;
987                 $DB->insert_record('config_plugins', $config, false);
988             }
989         }
990     }
992     return true;
995 /**
996  * Get configuration values from the global config table
997  * or the config_plugins table.
998  *
999  * If called with one parameter, it will load all the config
1000  * variables for one plugin, and return them as an object.
1001  *
1002  * If called with 2 parameters it will return a string single
1003  * value or false if the value is not found.
1004  *
1005  * @param string $plugin full component name
1006  * @param string $name default NULL
1007  * @return mixed hash-like object or single value, return false no config found
1008  */
1009 function get_config($plugin, $name = NULL) {
1010     global $CFG, $DB;
1012     // normalise component name
1013     if ($plugin === 'moodle' or $plugin === 'core') {
1014         $plugin = NULL;
1015     }
1017     if (!empty($name)) { // the user is asking for a specific value
1018         if (!empty($plugin)) {
1019             if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1020                 // setting forced in config file
1021                 return $CFG->forced_plugin_settings[$plugin][$name];
1022             } else {
1023                 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1024             }
1025         } else {
1026             if (array_key_exists($name, $CFG->config_php_settings)) {
1027                 // setting force in config file
1028                 return $CFG->config_php_settings[$name];
1029             } else {
1030                 return $DB->get_field('config', 'value', array('name'=>$name));
1031             }
1032         }
1033     }
1035     // the user is after a recordset
1036     if ($plugin) {
1037         $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1038         if (isset($CFG->forced_plugin_settings[$plugin])) {
1039             foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1040                 if (is_null($v) or is_array($v) or is_object($v)) {
1041                     // we do not want any extra mess here, just real settings that could be saved in db
1042                     unset($localcfg[$n]);
1043                 } else {
1044                     //convert to string as if it went through the DB
1045                     $localcfg[$n] = (string)$v;
1046                 }
1047             }
1048         }
1049         return (object)$localcfg;
1051     } else {
1052         // this part is not really used any more, but anyway...
1053         $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1054         foreach($CFG->config_php_settings as $n=>$v) {
1055             if (is_null($v) or is_array($v) or is_object($v)) {
1056                 // we do not want any extra mess here, just real settings that could be saved in db
1057                 unset($localcfg[$n]);
1058             } else {
1059                 //convert to string as if it went through the DB
1060                 $localcfg[$n] = (string)$v;
1061             }
1062         }
1063         return (object)$localcfg;
1064     }
1067 /**
1068  * Removes a key from global configuration
1069  *
1070  * @param string $name the key to set
1071  * @param string $plugin (optional) the plugin scope
1072  * @global object
1073  * @return boolean whether the operation succeeded.
1074  */
1075 function unset_config($name, $plugin=NULL) {
1076     global $CFG, $DB;
1078     if (empty($plugin)) {
1079         unset($CFG->$name);
1080         $DB->delete_records('config', array('name'=>$name));
1081     } else {
1082         $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1083     }
1085     return true;
1088 /**
1089  * Remove all the config variables for a given plugin.
1090  *
1091  * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1092  * @return boolean whether the operation succeeded.
1093  */
1094 function unset_all_config_for_plugin($plugin) {
1095     global $DB;
1096     $DB->delete_records('config_plugins', array('plugin' => $plugin));
1097     $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
1098     return true;
1101 /**
1102  * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1103  *
1104  * All users are verified if they still have the necessary capability.
1105  *
1106  * @param string $value the value of the config setting.
1107  * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1108  * @param bool $include admins, include administrators
1109  * @return array of user objects.
1110  */
1111 function get_users_from_config($value, $capability, $includeadmins = true) {
1112     global $CFG, $DB;
1114     if (empty($value) or $value === '$@NONE@$') {
1115         return array();
1116     }
1118     // we have to make sure that users still have the necessary capability,
1119     // it should be faster to fetch them all first and then test if they are present
1120     // instead of validating them one-by-one
1121     $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1122     if ($includeadmins) {
1123         $admins = get_admins();
1124         foreach ($admins as $admin) {
1125             $users[$admin->id] = $admin;
1126         }
1127     }
1129     if ($value === '$@ALL@$') {
1130         return $users;
1131     }
1133     $result = array(); // result in correct order
1134     $allowed = explode(',', $value);
1135     foreach ($allowed as $uid) {
1136         if (isset($users[$uid])) {
1137             $user = $users[$uid];
1138             $result[$user->id] = $user;
1139         }
1140     }
1142     return $result;
1146 /**
1147  * Invalidates browser caches and cached data in temp
1148  * @return void
1149  */
1150 function purge_all_caches() {
1151     global $CFG;
1153     reset_text_filters_cache();
1154     js_reset_all_caches();
1155     theme_reset_all_caches();
1156     get_string_manager()->reset_caches();
1158     // purge all other caches: rss, simplepie, etc.
1159     remove_dir($CFG->dataroot.'/cache', true);
1161     // make sure cache dir is writable, throws exception if not
1162     make_upload_directory('cache');
1164     clearstatcache();
1167 /**
1168  * Get volatile flags
1169  *
1170  * @param string $type
1171  * @param int    $changedsince default null
1172  * @return records array
1173  */
1174 function get_cache_flags($type, $changedsince=NULL) {
1175     global $DB;
1177     $params = array('type'=>$type, 'expiry'=>time());
1178     $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1179     if ($changedsince !== NULL) {
1180         $params['changedsince'] = $changedsince;
1181         $sqlwhere .= " AND timemodified > :changedsince";
1182     }
1183     $cf = array();
1185     if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1186         foreach ($flags as $flag) {
1187             $cf[$flag->name] = $flag->value;
1188         }
1189     }
1190     return $cf;
1193 /**
1194  * Get volatile flags
1195  *
1196  * @param string $type
1197  * @param string $name
1198  * @param int    $changedsince default null
1199  * @return records array
1200  */
1201 function get_cache_flag($type, $name, $changedsince=NULL) {
1202     global $DB;
1204     $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1206     $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1207     if ($changedsince !== NULL) {
1208         $params['changedsince'] = $changedsince;
1209         $sqlwhere .= " AND timemodified > :changedsince";
1210     }
1212     return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1215 /**
1216  * Set a volatile flag
1217  *
1218  * @param string $type the "type" namespace for the key
1219  * @param string $name the key to set
1220  * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1221  * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1222  * @return bool Always returns true
1223  */
1224 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1225     global $DB;
1227     $timemodified = time();
1228     if ($expiry===NULL || $expiry < $timemodified) {
1229         $expiry = $timemodified + 24 * 60 * 60;
1230     } else {
1231         $expiry = (int)$expiry;
1232     }
1234     if ($value === NULL) {
1235         unset_cache_flag($type,$name);
1236         return true;
1237     }
1239     if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potentail problem in DEBUG_DEVELOPER
1240         if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1241             return true; //no need to update; helps rcache too
1242         }
1243         $f->value        = $value;
1244         $f->expiry       = $expiry;
1245         $f->timemodified = $timemodified;
1246         $DB->update_record('cache_flags', $f);
1247     } else {
1248         $f = new stdClass();
1249         $f->flagtype     = $type;
1250         $f->name         = $name;
1251         $f->value        = $value;
1252         $f->expiry       = $expiry;
1253         $f->timemodified = $timemodified;
1254         $DB->insert_record('cache_flags', $f);
1255     }
1256     return true;
1259 /**
1260  * Removes a single volatile flag
1261  *
1262  * @global object
1263  * @param string $type the "type" namespace for the key
1264  * @param string $name the key to set
1265  * @return bool
1266  */
1267 function unset_cache_flag($type, $name) {
1268     global $DB;
1269     $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1270     return true;
1273 /**
1274  * Garbage-collect volatile flags
1275  *
1276  * @return bool Always returns true
1277  */
1278 function gc_cache_flags() {
1279     global $DB;
1280     $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1281     return true;
1284 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1286 /**
1287  * Refresh current $USER session global variable with all their current preferences.
1288  *
1289  * @global object
1290  * @param mixed $time default null
1291  * @return void
1292  */
1293 function check_user_preferences_loaded($time = null) {
1294     global $USER, $DB;
1295     static $timenow = null; // Static cache, so we only check up-to-dateness once per request.
1297     if (!empty($USER->preference) && isset($USER->preference['_lastloaded'])) {
1298         // Already loaded. Are we up to date?
1300         if (is_null($timenow) || (!is_null($time) && $time != $timenow)) {
1301             $timenow = time();
1302             if (!get_cache_flag('userpreferenceschanged', $USER->id, $USER->preference['_lastloaded'])) {
1303                 // We are up-to-date.
1304                 return;
1305             }
1306         } else {
1307             // Already checked for up-to-date-ness.
1308             return;
1309         }
1310     }
1312     // OK, so we have to reload. Reset preference
1313     $USER->preference = array();
1315     if (!isloggedin() or isguestuser()) {
1316         // No permanent storage for not-logged-in user and guest
1318     } else if ($preferences = $DB->get_records('user_preferences', array('userid'=>$USER->id))) {
1319         foreach ($preferences as $preference) {
1320             $USER->preference[$preference->name] = $preference->value;
1321         }
1322     }
1324     $USER->preference['_lastloaded'] = $timenow;
1327 /**
1328  * Called from set/delete_user_preferences, so that the prefs can be correctly reloaded.
1329  *
1330  * @global object
1331  * @global object
1332  * @param integer $userid the user whose prefs were changed.
1333  */
1334 function mark_user_preferences_changed($userid) {
1335     global $CFG, $USER;
1336     if ($userid == $USER->id) {
1337         check_user_preferences_loaded(time());
1338     }
1339     set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1342 /**
1343  * Sets a preference for the current user
1344  *
1345  * Optionally, can set a preference for a different user object
1346  *
1347  * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
1348  *
1349  * @global object
1350  * @global object
1351  * @param string $name The key to set as preference for the specified user
1352  * @param string $value The value to set for the $name key in the specified user's record
1353  * @param int $otheruserid A moodle user ID, default null
1354  * @return bool
1355  */
1356 function set_user_preference($name, $value, $otheruserid=NULL) {
1357     global $USER, $DB;
1359     if (empty($name)) {
1360         return false;
1361     }
1363     $nostore = false;
1364     if (empty($otheruserid)){
1365         if (!isloggedin() or isguestuser()) {
1366             $nostore = true;
1367         }
1368         $userid = $USER->id;
1369     } else {
1370         if (isguestuser($otheruserid)) {
1371             $nostore = true;
1372         }
1373         $userid = $otheruserid;
1374     }
1376     if ($nostore) {
1377         // no permanent storage for not-logged-in user and guest
1379     } else if ($preference = $DB->get_record('user_preferences', array('userid'=>$userid, 'name'=>$name))) {
1380         if ($preference->value === $value) {
1381             return true;
1382         }
1383         $DB->set_field('user_preferences', 'value', (string)$value, array('id'=>$preference->id));
1385     } else {
1386         $preference = new stdClass();
1387         $preference->userid = $userid;
1388         $preference->name   = $name;
1389         $preference->value  = (string)$value;
1390         $DB->insert_record('user_preferences', $preference);
1391     }
1393     mark_user_preferences_changed($userid);
1394     // update value in USER session if needed
1395     if ($userid == $USER->id) {
1396         $USER->preference[$name] = (string)$value;
1397         $USER->preference['_lastloaded'] = time();
1398     }
1400     return true;
1403 /**
1404  * Sets a whole array of preferences for the current user
1405  *
1406  * @param array $prefarray An array of key/value pairs to be set
1407  * @param int $otheruserid A moodle user ID
1408  * @return bool
1409  */
1410 function set_user_preferences($prefarray, $otheruserid=NULL) {
1412     if (!is_array($prefarray) or empty($prefarray)) {
1413         return false;
1414     }
1416     foreach ($prefarray as $name => $value) {
1417         set_user_preference($name, $value, $otheruserid);
1418     }
1419     return true;
1422 /**
1423  * Unsets a preference completely by deleting it from the database
1424  *
1425  * Optionally, can set a preference for a different user id
1426  *
1427  * @global object
1428  * @param string  $name The key to unset as preference for the specified user
1429  * @param int $otheruserid A moodle user ID
1430  */
1431 function unset_user_preference($name, $otheruserid=NULL) {
1432     global $USER, $DB;
1434     if (empty($otheruserid)){
1435         $userid = $USER->id;
1436         check_user_preferences_loaded();
1437     } else {
1438         $userid = $otheruserid;
1439     }
1441     //Then from DB
1442     $DB->delete_records('user_preferences', array('userid'=>$userid, 'name'=>$name));
1444     mark_user_preferences_changed($userid);
1445     //Delete the preference from $USER if needed
1446     if ($userid == $USER->id) {
1447         unset($USER->preference[$name]);
1448         $USER->preference['_lastloaded'] = time();
1449     }
1451     return true;
1454 /**
1455  * Used to fetch user preference(s)
1456  *
1457  * If no arguments are supplied this function will return
1458  * all of the current user preferences as an array.
1459  *
1460  * If a name is specified then this function
1461  * attempts to return that particular preference value.  If
1462  * none is found, then the optional value $default is returned,
1463  * otherwise NULL.
1464  *
1465  * @global object
1466  * @global object
1467  * @param string $name Name of the key to use in finding a preference value
1468  * @param string $default Value to be returned if the $name key is not set in the user preferences
1469  * @param int $otheruserid A moodle user ID
1470  * @return string
1471  */
1472 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
1473     global $USER, $DB;
1475     if (empty($otheruserid) || (isloggedin() && ($USER->id == $otheruserid))){
1476         check_user_preferences_loaded();
1478         if (empty($name)) {
1479             return $USER->preference; // All values
1480         } else if (array_key_exists($name, $USER->preference)) {
1481             return $USER->preference[$name]; // The single value
1482         } else {
1483             return $default; // Default value (or NULL)
1484         }
1486     } else {
1487         if (empty($name)) {
1488             return $DB->get_records_menu('user_preferences', array('userid'=>$otheruserid), '', 'name,value'); // All values
1489         } else if ($value = $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>$name))) {
1490             return $value; // The single value
1491         } else {
1492             return $default; // Default value (or NULL)
1493         }
1494     }
1497 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1499 /**
1500  * Given date parts in user time produce a GMT timestamp.
1501  *
1502  * @todo Finish documenting this function
1503  * @param int $year The year part to create timestamp of
1504  * @param int $month The month part to create timestamp of
1505  * @param int $day The day part to create timestamp of
1506  * @param int $hour The hour part to create timestamp of
1507  * @param int $minute The minute part to create timestamp of
1508  * @param int $second The second part to create timestamp of
1509  * @param float $timezone Timezone modifier
1510  * @param bool $applydst Toggle Daylight Saving Time, default true
1511  * @return int timestamp
1512  */
1513 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1515     $strtimezone = NULL;
1516     if (!is_numeric($timezone)) {
1517         $strtimezone = $timezone;
1518     }
1520     $timezone = get_user_timezone_offset($timezone);
1522     if (abs($timezone) > 13) {
1523         $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1524     } else {
1525         $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1526         $time = usertime($time, $timezone);
1527         if($applydst) {
1528             $time -= dst_offset_on($time, $strtimezone);
1529         }
1530     }
1532     return $time;
1536 /**
1537  * Format a date/time (seconds) as weeks, days, hours etc as needed
1538  *
1539  * Given an amount of time in seconds, returns string
1540  * formatted nicely as weeks, days, hours etc as needed
1541  *
1542  * @uses MINSECS
1543  * @uses HOURSECS
1544  * @uses DAYSECS
1545  * @uses YEARSECS
1546  * @param int $totalsecs Time in seconds
1547  * @param object $str Should be a time object
1548  * @return string A nicely formatted date/time string
1549  */
1550  function format_time($totalsecs, $str=NULL) {
1552     $totalsecs = abs($totalsecs);
1554     if (!$str) {  // Create the str structure the slow way
1555         $str->day   = get_string('day');
1556         $str->days  = get_string('days');
1557         $str->hour  = get_string('hour');
1558         $str->hours = get_string('hours');
1559         $str->min   = get_string('min');
1560         $str->mins  = get_string('mins');
1561         $str->sec   = get_string('sec');
1562         $str->secs  = get_string('secs');
1563         $str->year  = get_string('year');
1564         $str->years = get_string('years');
1565     }
1568     $years     = floor($totalsecs/YEARSECS);
1569     $remainder = $totalsecs - ($years*YEARSECS);
1570     $days      = floor($remainder/DAYSECS);
1571     $remainder = $totalsecs - ($days*DAYSECS);
1572     $hours     = floor($remainder/HOURSECS);
1573     $remainder = $remainder - ($hours*HOURSECS);
1574     $mins      = floor($remainder/MINSECS);
1575     $secs      = $remainder - ($mins*MINSECS);
1577     $ss = ($secs == 1)  ? $str->sec  : $str->secs;
1578     $sm = ($mins == 1)  ? $str->min  : $str->mins;
1579     $sh = ($hours == 1) ? $str->hour : $str->hours;
1580     $sd = ($days == 1)  ? $str->day  : $str->days;
1581     $sy = ($years == 1)  ? $str->year  : $str->years;
1583     $oyears = '';
1584     $odays = '';
1585     $ohours = '';
1586     $omins = '';
1587     $osecs = '';
1589     if ($years)  $oyears  = $years .' '. $sy;
1590     if ($days)  $odays  = $days .' '. $sd;
1591     if ($hours) $ohours = $hours .' '. $sh;
1592     if ($mins)  $omins  = $mins .' '. $sm;
1593     if ($secs)  $osecs  = $secs .' '. $ss;
1595     if ($years) return trim($oyears .' '. $odays);
1596     if ($days)  return trim($odays .' '. $ohours);
1597     if ($hours) return trim($ohours .' '. $omins);
1598     if ($mins)  return trim($omins .' '. $osecs);
1599     if ($secs)  return $osecs;
1600     return get_string('now');
1603 /**
1604  * Returns a formatted string that represents a date in user time
1605  *
1606  * Returns a formatted string that represents a date in user time
1607  * <b>WARNING: note that the format is for strftime(), not date().</b>
1608  * Because of a bug in most Windows time libraries, we can't use
1609  * the nicer %e, so we have to use %d which has leading zeroes.
1610  * A lot of the fuss in the function is just getting rid of these leading
1611  * zeroes as efficiently as possible.
1612  *
1613  * If parameter fixday = true (default), then take off leading
1614  * zero from %d, else maintain it.
1615  *
1616  * @param int $date the timestamp in UTC, as obtained from the database.
1617  * @param string $format strftime format. You should probably get this using
1618  *      get_string('strftime...', 'langconfig');
1619  * @param float $timezone by default, uses the user's time zone.
1620  * @param bool $fixday If true (default) then the leading zero from %d is removed.
1621  *      If false then the leading zero is maintained.
1622  * @return string the formatted date/time.
1623  */
1624 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1626     global $CFG;
1628     $strtimezone = NULL;
1629     if (!is_numeric($timezone)) {
1630         $strtimezone = $timezone;
1631     }
1633     if (empty($format)) {
1634         $format = get_string('strftimedaydatetime', 'langconfig');
1635     }
1637     if (!empty($CFG->nofixday)) {  // Config.php can force %d not to be fixed.
1638         $fixday = false;
1639     } else if ($fixday) {
1640         $formatnoday = str_replace('%d', 'DD', $format);
1641         $fixday = ($formatnoday != $format);
1642     }
1644     $date += dst_offset_on($date, $strtimezone);
1646     $timezone = get_user_timezone_offset($timezone);
1648     if (abs($timezone) > 13) {   /// Server time
1649         if ($fixday) {
1650             $datestring = strftime($formatnoday, $date);
1651             $daystring  = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
1652             $datestring = str_replace('DD', $daystring, $datestring);
1653         } else {
1654             $datestring = strftime($format, $date);
1655         }
1656     } else {
1657         $date += (int)($timezone * 3600);
1658         if ($fixday) {
1659             $datestring = gmstrftime($formatnoday, $date);
1660             $daystring  = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
1661             $datestring = str_replace('DD', $daystring, $datestring);
1662         } else {
1663             $datestring = gmstrftime($format, $date);
1664         }
1665     }
1667 /// If we are running under Windows convert from windows encoding to UTF-8
1668 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1670    if ($CFG->ostype == 'WINDOWS') {
1671        if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1672            $textlib = textlib_get_instance();
1673            $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1674        }
1675    }
1677     return $datestring;
1680 /**
1681  * Given a $time timestamp in GMT (seconds since epoch),
1682  * returns an array that represents the date in user time
1683  *
1684  * @todo Finish documenting this function
1685  * @uses HOURSECS
1686  * @param int $time Timestamp in GMT
1687  * @param float $timezone ?
1688  * @return array An array that represents the date in user time
1689  */
1690 function usergetdate($time, $timezone=99) {
1692     $strtimezone = NULL;
1693     if (!is_numeric($timezone)) {
1694         $strtimezone = $timezone;
1695     }
1697     $timezone = get_user_timezone_offset($timezone);
1699     if (abs($timezone) > 13) {    // Server time
1700         return getdate($time);
1701     }
1703     // There is no gmgetdate so we use gmdate instead
1704     $time += dst_offset_on($time, $strtimezone);
1705     $time += intval((float)$timezone * HOURSECS);
1707     $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
1709     //be careful to ensure the returned array matches that produced by getdate() above
1710     list(
1711         $getdate['month'],
1712         $getdate['weekday'],
1713         $getdate['yday'],
1714         $getdate['year'],
1715         $getdate['mon'],
1716         $getdate['wday'],
1717         $getdate['mday'],
1718         $getdate['hours'],
1719         $getdate['minutes'],
1720         $getdate['seconds']
1721     ) = explode('_', $datestring);
1723     return $getdate;
1726 /**
1727  * Given a GMT timestamp (seconds since epoch), offsets it by
1728  * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1729  *
1730  * @uses HOURSECS
1731  * @param  int $date Timestamp in GMT
1732  * @param float $timezone
1733  * @return int
1734  */
1735 function usertime($date, $timezone=99) {
1737     $timezone = get_user_timezone_offset($timezone);
1739     if (abs($timezone) > 13) {
1740         return $date;
1741     }
1742     return $date - (int)($timezone * HOURSECS);
1745 /**
1746  * Given a time, return the GMT timestamp of the most recent midnight
1747  * for the current user.
1748  *
1749  * @param int $date Timestamp in GMT
1750  * @param float $timezone Defaults to user's timezone
1751  * @return int Returns a GMT timestamp
1752  */
1753 function usergetmidnight($date, $timezone=99) {
1755     $userdate = usergetdate($date, $timezone);
1757     // Time of midnight of this user's day, in GMT
1758     return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1762 /**
1763  * Returns a string that prints the user's timezone
1764  *
1765  * @param float $timezone The user's timezone
1766  * @return string
1767  */
1768 function usertimezone($timezone=99) {
1770     $tz = get_user_timezone($timezone);
1772     if (!is_float($tz)) {
1773         return $tz;
1774     }
1776     if(abs($tz) > 13) { // Server time
1777         return get_string('serverlocaltime');
1778     }
1780     if($tz == intval($tz)) {
1781         // Don't show .0 for whole hours
1782         $tz = intval($tz);
1783     }
1785     if($tz == 0) {
1786         return 'UTC';
1787     }
1788     else if($tz > 0) {
1789         return 'UTC+'.$tz;
1790     }
1791     else {
1792         return 'UTC'.$tz;
1793     }
1797 /**
1798  * Returns a float which represents the user's timezone difference from GMT in hours
1799  * Checks various settings and picks the most dominant of those which have a value
1800  *
1801  * @global object
1802  * @global object
1803  * @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
1804  * @return float
1805  */
1806 function get_user_timezone_offset($tz = 99) {
1808     global $USER, $CFG;
1810     $tz = get_user_timezone($tz);
1812     if (is_float($tz)) {
1813         return $tz;
1814     } else {
1815         $tzrecord = get_timezone_record($tz);
1816         if (empty($tzrecord)) {
1817             return 99.0;
1818         }
1819         return (float)$tzrecord->gmtoff / HOURMINS;
1820     }
1823 /**
1824  * Returns an int which represents the systems's timezone difference from GMT in seconds
1825  *
1826  * @global object
1827  * @param mixed $tz timezone
1828  * @return int if found, false is timezone 99 or error
1829  */
1830 function get_timezone_offset($tz) {
1831     global $CFG;
1833     if ($tz == 99) {
1834         return false;
1835     }
1837     if (is_numeric($tz)) {
1838         return intval($tz * 60*60);
1839     }
1841     if (!$tzrecord = get_timezone_record($tz)) {
1842         return false;
1843     }
1844     return intval($tzrecord->gmtoff * 60);
1847 /**
1848  * Returns a float or a string which denotes the user's timezone
1849  * 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)
1850  * means that for this timezone there are also DST rules to be taken into account
1851  * Checks various settings and picks the most dominant of those which have a value
1852  *
1853  * @global object
1854  * @global object
1855  * @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
1856  * @return mixed
1857  */
1858 function get_user_timezone($tz = 99) {
1859     global $USER, $CFG;
1861     $timezones = array(
1862         $tz,
1863         isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1864         isset($USER->timezone) ? $USER->timezone : 99,
1865         isset($CFG->timezone) ? $CFG->timezone : 99,
1866         );
1868     $tz = 99;
1870     while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
1871         $tz = $next['value'];
1872     }
1874     return is_numeric($tz) ? (float) $tz : $tz;
1877 /**
1878  * Returns cached timezone record for given $timezonename
1879  *
1880  * @global object
1881  * @global object
1882  * @param string $timezonename
1883  * @return mixed timezonerecord object or false
1884  */
1885 function get_timezone_record($timezonename) {
1886     global $CFG, $DB;
1887     static $cache = NULL;
1889     if ($cache === NULL) {
1890         $cache = array();
1891     }
1893     if (isset($cache[$timezonename])) {
1894         return $cache[$timezonename];
1895     }
1897     return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
1898                                                         WHERE name = ? ORDER BY year DESC', array($timezonename), true);
1901 /**
1902  * Build and store the users Daylight Saving Time (DST) table
1903  *
1904  * @global object
1905  * @global object
1906  * @global object
1907  * @param mixed $from_year Start year for the table, defaults to 1971
1908  * @param mixed $to_year End year for the table, defaults to 2035
1909  * @param mixed $strtimezone
1910  * @return bool
1911  */
1912 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
1913     global $CFG, $SESSION, $DB;
1915     $usertz = get_user_timezone($strtimezone);
1917     if (is_float($usertz)) {
1918         // Trivial timezone, no DST
1919         return false;
1920     }
1922     if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1923         // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1924         unset($SESSION->dst_offsets);
1925         unset($SESSION->dst_range);
1926     }
1928     if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1929         // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1930         // This will be the return path most of the time, pretty light computationally
1931         return true;
1932     }
1934     // Reaching here means we either need to extend our table or create it from scratch
1936     // Remember which TZ we calculated these changes for
1937     $SESSION->dst_offsettz = $usertz;
1939     if(empty($SESSION->dst_offsets)) {
1940         // If we 're creating from scratch, put the two guard elements in there
1941         $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1942     }
1943     if(empty($SESSION->dst_range)) {
1944         // If creating from scratch
1945         $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1946         $to   = min((empty($to_year)   ? intval(date('Y')) + 3 : $to_year),   2035);
1948         // Fill in the array with the extra years we need to process
1949         $yearstoprocess = array();
1950         for($i = $from; $i <= $to; ++$i) {
1951             $yearstoprocess[] = $i;
1952         }
1954         // Take note of which years we have processed for future calls
1955         $SESSION->dst_range = array($from, $to);
1956     }
1957     else {
1958         // If needing to extend the table, do the same
1959         $yearstoprocess = array();
1961         $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1962         $to   = min((empty($to_year)   ? $SESSION->dst_range[1] : $to_year),   2035);
1964         if($from < $SESSION->dst_range[0]) {
1965             // Take note of which years we need to process and then note that we have processed them for future calls
1966             for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
1967                 $yearstoprocess[] = $i;
1968             }
1969             $SESSION->dst_range[0] = $from;
1970         }
1971         if($to > $SESSION->dst_range[1]) {
1972             // Take note of which years we need to process and then note that we have processed them for future calls
1973             for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
1974                 $yearstoprocess[] = $i;
1975             }
1976             $SESSION->dst_range[1] = $to;
1977         }
1978     }
1980     if(empty($yearstoprocess)) {
1981         // This means that there was a call requesting a SMALLER range than we have already calculated
1982         return true;
1983     }
1985     // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1986     // Also, the array is sorted in descending timestamp order!
1988     // Get DB data
1990     static $presets_cache = array();
1991     if (!isset($presets_cache[$usertz])) {
1992         $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');
1993     }
1994     if(empty($presets_cache[$usertz])) {
1995         return false;
1996     }
1998     // Remove ending guard (first element of the array)
1999     reset($SESSION->dst_offsets);
2000     unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2002     // Add all required change timestamps
2003     foreach($yearstoprocess as $y) {
2004         // Find the record which is in effect for the year $y
2005         foreach($presets_cache[$usertz] as $year => $preset) {
2006             if($year <= $y) {
2007                 break;
2008             }
2009         }
2011         $changes = dst_changes_for_year($y, $preset);
2013         if($changes === NULL) {
2014             continue;
2015         }
2016         if($changes['dst'] != 0) {
2017             $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2018         }
2019         if($changes['std'] != 0) {
2020             $SESSION->dst_offsets[$changes['std']] = 0;
2021         }
2022     }
2024     // Put in a guard element at the top
2025     $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2026     $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2028     // Sort again
2029     krsort($SESSION->dst_offsets);
2031     return true;
2034 /**
2035  * Calculates the required DST change and returns a Timestamp Array
2036  *
2037  * @uses HOURSECS
2038  * @uses MINSECS
2039  * @param mixed $year Int or String Year to focus on
2040  * @param object $timezone Instatiated Timezone object
2041  * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
2042  */
2043 function dst_changes_for_year($year, $timezone) {
2045     if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2046         return NULL;
2047     }
2049     $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2050     $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2052     list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2053     list($std_hour, $std_min) = explode(':', $timezone->std_time);
2055     $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2056     $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2058     // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2059     // This has the advantage of being able to have negative values for hour, i.e. for timezones
2060     // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2062     $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2063     $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2065     return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2068 /**
2069  * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2070  *
2071  * @global object
2072  * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2073  * @return int
2074  */
2075 function dst_offset_on($time, $strtimezone = NULL) {
2076     global $SESSION;
2078     if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2079         return 0;
2080     }
2082     reset($SESSION->dst_offsets);
2083     while(list($from, $offset) = each($SESSION->dst_offsets)) {
2084         if($from <= $time) {
2085             break;
2086         }
2087     }
2089     // This is the normal return path
2090     if($offset !== NULL) {
2091         return $offset;
2092     }
2094     // Reaching this point means we haven't calculated far enough, do it now:
2095     // Calculate extra DST changes if needed and recurse. The recursion always
2096     // moves toward the stopping condition, so will always end.
2098     if($from == 0) {
2099         // We need a year smaller than $SESSION->dst_range[0]
2100         if($SESSION->dst_range[0] == 1971) {
2101             return 0;
2102         }
2103         calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2104         return dst_offset_on($time, $strtimezone);
2105     }
2106     else {
2107         // We need a year larger than $SESSION->dst_range[1]
2108         if($SESSION->dst_range[1] == 2035) {
2109             return 0;
2110         }
2111         calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2112         return dst_offset_on($time, $strtimezone);
2113     }
2116 /**
2117  * ?
2118  *
2119  * @todo Document what this function does
2120  * @param int $startday
2121  * @param int $weekday
2122  * @param int $month
2123  * @param int $year
2124  * @return int
2125  */
2126 function find_day_in_month($startday, $weekday, $month, $year) {
2128     $daysinmonth = days_in_month($month, $year);
2130     if($weekday == -1) {
2131         // Don't care about weekday, so return:
2132         //    abs($startday) if $startday != -1
2133         //    $daysinmonth otherwise
2134         return ($startday == -1) ? $daysinmonth : abs($startday);
2135     }
2137     // From now on we 're looking for a specific weekday
2139     // Give "end of month" its actual value, since we know it
2140     if($startday == -1) {
2141         $startday = -1 * $daysinmonth;
2142     }
2144     // Starting from day $startday, the sign is the direction
2146     if($startday < 1) {
2148         $startday = abs($startday);
2149         $lastmonthweekday  = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2151         // This is the last such weekday of the month
2152         $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2153         if($lastinmonth > $daysinmonth) {
2154             $lastinmonth -= 7;
2155         }
2157         // Find the first such weekday <= $startday
2158         while($lastinmonth > $startday) {
2159             $lastinmonth -= 7;
2160         }
2162         return $lastinmonth;
2164     }
2165     else {
2167         $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
2169         $diff = $weekday - $indexweekday;
2170         if($diff < 0) {
2171             $diff += 7;
2172         }
2174         // This is the first such weekday of the month equal to or after $startday
2175         $firstfromindex = $startday + $diff;
2177         return $firstfromindex;
2179     }
2182 /**
2183  * Calculate the number of days in a given month
2184  *
2185  * @param int $month The month whose day count is sought
2186  * @param int $year The year of the month whose day count is sought
2187  * @return int
2188  */
2189 function days_in_month($month, $year) {
2190    return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
2193 /**
2194  * Calculate the position in the week of a specific calendar day
2195  *
2196  * @param int $day The day of the date whose position in the week is sought
2197  * @param int $month The month of the date whose position in the week is sought
2198  * @param int $year The year of the date whose position in the week is sought
2199  * @return int
2200  */
2201 function dayofweek($day, $month, $year) {
2202     // I wonder if this is any different from
2203     // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2204     return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2207 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2209 /**
2210  * Returns full login url.
2211  *
2212  * @return string login url
2213  */
2214 function get_login_url() {
2215     global $CFG;
2217     $url = "$CFG->wwwroot/login/index.php";
2219     if (!empty($CFG->loginhttps)) {
2220         $url = str_replace('http:', 'https:', $url);
2221     }
2223     return $url;
2226 /**
2227  * This function checks that the current user is logged in and has the
2228  * required privileges
2229  *
2230  * This function checks that the current user is logged in, and optionally
2231  * whether they are allowed to be in a particular course and view a particular
2232  * course module.
2233  * If they are not logged in, then it redirects them to the site login unless
2234  * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2235  * case they are automatically logged in as guests.
2236  * If $courseid is given and the user is not enrolled in that course then the
2237  * user is redirected to the course enrolment page.
2238  * If $cm is given and the course module is hidden and the user is not a teacher
2239  * in the course then the user is redirected to the course home page.
2240  *
2241  * When $cm parameter specified, this function sets page layout to 'module'.
2242  * You need to change it manually later if some other layout needed.
2243  *
2244  * @param mixed $courseorid id of the course or course object
2245  * @param bool $autologinguest default true
2246  * @param object $cm course module object
2247  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2248  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2249  *             in order to keep redirects working properly. MDL-14495
2250  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2251  * @return mixed Void, exit, and die depending on path
2252  */
2253 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2254     global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2256     // setup global $COURSE, themes, language and locale
2257     if (!empty($courseorid)) {
2258         if (is_object($courseorid)) {
2259             $course = $courseorid;
2260         } else if ($courseorid == SITEID) {
2261             $course = clone($SITE);
2262         } else {
2263             $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2264         }
2265         if ($cm) {
2266             if ($cm->course != $course->id) {
2267                 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2268             }
2269             $PAGE->set_cm($cm, $course); // set's up global $COURSE
2270             $PAGE->set_pagelayout('incourse');
2271         } else {
2272             $PAGE->set_course($course); // set's up global $COURSE
2273         }
2274     } else {
2275         // do not touch global $COURSE via $PAGE->set_course(),
2276         // the reasons is we need to be able to call require_login() at any time!!
2277         $course = $SITE;
2278         if ($cm) {
2279             throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2280         }
2281     }
2283     // If the user is not even logged in yet then make sure they are
2284     if (!isloggedin()) {
2285         if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2286             if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2287                 // misconfigured site guest, just redirect to login page
2288                 redirect(get_login_url());
2289                 exit; // never reached
2290             }
2291             $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2292             complete_user_login($guest, false);
2293             $SESSION->lang = $lang;
2294         } else {
2295             //NOTE: $USER->site check was obsoleted by session test cookie,
2296             //      $USER->confirmed test is in login/index.php
2297             if ($preventredirect) {
2298                 throw new require_login_exception('You are not logged in');
2299             }
2301             if ($setwantsurltome) {
2302                 // TODO: switch to PAGE->url
2303                 $SESSION->wantsurl = $FULLME;
2304             }
2305             if (!empty($_SERVER['HTTP_REFERER'])) {
2306                 $SESSION->fromurl  = $_SERVER['HTTP_REFERER'];
2307             }
2308             redirect(get_login_url());
2309             exit; // never reached
2310         }
2311     }
2313     // loginas as redirection if needed
2314     if ($course->id != SITEID and session_is_loggedinas()) {
2315         if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2316             if ($USER->loginascontext->instanceid != $course->id) {
2317                 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2318             }
2319         }
2320     }
2322     // check whether the user should be changing password (but only if it is REALLY them)
2323     if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2324         $userauth = get_auth_plugin($USER->auth);
2325         if ($userauth->can_change_password() and !$preventredirect) {
2326             $SESSION->wantsurl = $FULLME;
2327             if ($changeurl = $userauth->change_password_url()) {
2328                 //use plugin custom url
2329                 redirect($changeurl);
2330             } else {
2331                 //use moodle internal method
2332                 if (empty($CFG->loginhttps)) {
2333                     redirect($CFG->wwwroot .'/login/change_password.php');
2334                 } else {
2335                     $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2336                     redirect($wwwroot .'/login/change_password.php');
2337                 }
2338             }
2339         } else {
2340             print_error('nopasswordchangeforced', 'auth');
2341         }
2342     }
2344     // Check that the user account is properly set up
2345     if (user_not_fully_set_up($USER)) {
2346         if ($preventredirect) {
2347             throw new require_login_exception('User not fully set-up');
2348         }
2349         $SESSION->wantsurl = $FULLME;
2350         redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2351     }
2353     // Make sure the USER has a sesskey set up. Used for CSRF protection.
2354     sesskey();
2356     // Do not bother admins with any formalities
2357     if (is_siteadmin()) {
2358         //set accesstime or the user will appear offline which messes up messaging
2359         user_accesstime_log($course->id);
2360         return;
2361     }
2363     // Check that the user has agreed to a site policy if there is one
2364     if (!empty($CFG->sitepolicy)) {
2365         if ($preventredirect) {
2366             throw new require_login_exception('Policy not agreed');
2367         }
2368         if (!$USER->policyagreed) {
2369             $SESSION->wantsurl = $FULLME;
2370             redirect($CFG->wwwroot .'/user/policy.php');
2371         }
2372     }
2374     // Fetch the system context, the course context, and prefetch its child contexts
2375     $sysctx = get_context_instance(CONTEXT_SYSTEM);
2376     $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2377     if ($cm) {
2378         $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2379     } else {
2380         $cmcontext = null;
2381     }
2383     // If the site is currently under maintenance, then print a message
2384     if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2385         if ($preventredirect) {
2386             throw new require_login_exception('Maintenance in progress');
2387         }
2389         print_maintenance_message();
2390     }
2392     // make sure the course itself is not hidden
2393     if ($course->id == SITEID) {
2394         // frontpage can not be hidden
2395     } else {
2396         if (is_role_switched($course->id)) {
2397             // when switching roles ignore the hidden flag - user had to be in course to do the switch
2398         } else {
2399             if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2400                 // originally there was also test of parent category visibility,
2401                 // BUT is was very slow in complex queries involving "my courses"
2402                 // now it is also possible to simply hide all courses user is not enrolled in :-)
2403                 if ($preventredirect) {
2404                     throw new require_login_exception('Course is hidden');
2405                 }
2406                 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2407             }
2408         }
2409     }
2411     // is the user enrolled?
2412     if ($course->id == SITEID) {
2413         // everybody is enrolled on the frontpage
2415     } else {
2416         if (session_is_loggedinas()) {
2417             // Make sure the REAL person can access this course first
2418             $realuser = session_get_realuser();
2419             if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2420                 if ($preventredirect) {
2421                     throw new require_login_exception('Invalid course login-as access');
2422                 }
2423                 echo $OUTPUT->header();
2424                 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2425             }
2426         }
2428         // very simple enrolment caching - changes in course setting are not reflected immediately
2429         if (!isset($USER->enrol)) {
2430             $USER->enrol = array();
2431             $USER->enrol['enrolled'] = array();
2432             $USER->enrol['tempguest'] = array();
2433         }
2435         $access = false;
2437         if (is_viewing($coursecontext, $USER)) {
2438             // ok, no need to mess with enrol
2439             $access = true;
2441         } else {
2442             if (isset($USER->enrol['enrolled'][$course->id])) {
2443                 if ($USER->enrol['enrolled'][$course->id] == 0) {
2444                     $access = true;
2445                 } else if ($USER->enrol['enrolled'][$course->id] > time()) {
2446                     $access = true;
2447                 } else {
2448                     //expired
2449                     unset($USER->enrol['enrolled'][$course->id]);
2450                 }
2451             }
2452             if (isset($USER->enrol['tempguest'][$course->id])) {
2453                 if ($USER->enrol['tempguest'][$course->id] == 0) {
2454                     $access = true;
2455                 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2456                     $access = true;
2457                 } else {
2458                     //expired
2459                     unset($USER->enrol['tempguest'][$course->id]);
2460                     $USER->access = remove_temp_roles($coursecontext, $USER->access);
2461                 }
2462             }
2464             if ($access) {
2465                 // cache ok
2466             } else if (is_enrolled($coursecontext, $USER, '', true)) {
2467                 // active participants may always access
2468                 // TODO: refactor this into some new function
2469                 $now = time();
2470                 $sql = "SELECT MAX(ue.timeend)
2471                           FROM {user_enrolments} ue
2472                           JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2473                           JOIN {user} u ON u.id = ue.userid
2474                          WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0
2475                                AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
2476                 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE,
2477                                 'userid'=>$USER->id, 'courseid'=>$coursecontext->instanceid, 'now1'=>$now, 'now2'=>$now);
2478                 $until = $DB->get_field_sql($sql, $params);
2479                 if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) {
2480                     $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD;
2481                 }
2483                 $USER->enrol['enrolled'][$course->id] = $until;
2484                 $access = true;
2486                 // remove traces of previous temp guest access
2487                 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2489             } else {
2490                 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2491                 $enrols = enrol_get_plugins(true);
2492                 // first ask all enabled enrol instances in course if they want to auto enrol user
2493                 foreach($instances as $instance) {
2494                     if (!isset($enrols[$instance->enrol])) {
2495                         continue;
2496                     }
2497                     $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2498                     if ($until !== false) {
2499                         $USER->enrol['enrolled'][$course->id] = $until;
2500                         $USER->access = remove_temp_roles($coursecontext, $USER->access);
2501                         $access = true;
2502                         break;
2503                     }
2504                 }
2505                 // if not enrolled yet try to gain temporary guest access
2506                 if (!$access) {
2507                     foreach($instances as $instance) {
2508                         if (!isset($enrols[$instance->enrol])) {
2509                             continue;
2510                         }
2511                         $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2512                         if ($until !== false) {
2513                             $USER->enrol['tempguest'][$course->id] = $until;
2514                             $access = true;
2515                             break;
2516                         }
2517                     }
2518                 }
2519             }
2520         }
2522         if (!$access) {
2523             if ($preventredirect) {
2524                 throw new require_login_exception('Not enrolled');
2525             }
2526             $SESSION->wantsurl = $FULLME;
2527             redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2528         }
2529     }
2531     // test visibility
2532     if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2533         if ($preventredirect) {
2534             throw new require_login_exception('Activity is hidden');
2535         }
2536         redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2537     }
2539     // groupmembersonly access control
2540     if (!empty($CFG->enablegroupmembersonly) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2541         if (isguestuser() or !groups_has_membership($cm)) {
2542             if ($preventredirect) {
2543                 throw new require_login_exception('Not member of a group');
2544             }
2545             print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
2546         }
2547     }
2549     // Conditional activity access control
2550     if (!empty($CFG->enableavailability) and $cm) {
2551         // TODO: this is going to work with login-as-user, sorry!
2552         // We cache conditional access in session
2553         if (!isset($SESSION->conditionaccessok)) {
2554             $SESSION->conditionaccessok = array();
2555         }
2556         // If you have been allowed into the module once then you are allowed
2557         // in for rest of session, no need to do conditional checks
2558         if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
2559             // Get condition info (does a query for the availability table)
2560             require_once($CFG->libdir.'/conditionlib.php');
2561             $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
2562             // Check condition for user (this will do a query if the availability
2563             // information depends on grade or completion information)
2564             if ($ci->is_available($junk) || has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2565                 $SESSION->conditionaccessok[$cm->id] = true;
2566             } else {
2567                 print_error('activityiscurrentlyhidden');
2568             }
2569         }
2570     }
2572     // Finally access granted, update lastaccess times
2573     user_accesstime_log($course->id);
2577 /**
2578  * This function just makes sure a user is logged out.
2579  *
2580  * @global object
2581  */
2582 function require_logout() {
2583     global $USER;
2585     if (isloggedin()) {
2586         add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2588         $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2589         foreach($authsequence as $authname) {
2590             $authplugin = get_auth_plugin($authname);
2591             $authplugin->prelogout_hook();
2592         }
2593     }
2595     session_get_instance()->terminate_current();
2598 /**
2599  * Weaker version of require_login()
2600  *
2601  * This is a weaker version of {@link require_login()} which only requires login
2602  * when called from within a course rather than the site page, unless
2603  * the forcelogin option is turned on.
2604  * @see require_login()
2605  *
2606  * @global object
2607  * @param mixed $courseorid The course object or id in question
2608  * @param bool $autologinguest Allow autologin guests if that is wanted
2609  * @param object $cm Course activity module if known
2610  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2611  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2612  *             in order to keep redirects working properly. MDL-14495
2613  * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2614  * @return void
2615  */
2616 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2617     global $CFG, $PAGE, $SITE;
2618     if (!empty($CFG->forcelogin)) {
2619         // login required for both SITE and courses
2620         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2622     } else if (!empty($cm) and !$cm->visible) {
2623         // always login for hidden activities
2624         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2626     } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2627           or (!is_object($courseorid) and $courseorid == SITEID)) {
2628               //login for SITE not required
2629         if ($cm and empty($cm->visible)) {
2630             // hidden activities are not accessible without login
2631             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2632         } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2633             // not-logged-in users do not have any group membership
2634             require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2635         } else {
2636             // We still need to instatiate PAGE vars properly so that things
2637             // that rely on it like navigation function correctly.
2638             if (!empty($courseorid)) {
2639                 if (is_object($courseorid)) {
2640                     $course = $courseorid;
2641                 } else {
2642                     $course = clone($SITE);
2643                 }
2644                 if ($cm) {
2645                     if ($cm->course != $course->id) {
2646                         throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2647                     }
2648                     $PAGE->set_cm($cm, $course);
2649                     $PAGE->set_pagelayout('incourse');
2650                 } else {
2651                     $PAGE->set_course($course);
2652                 }
2653             } else {
2654                 // If $PAGE->course, and hence $PAGE->context, have not already been set
2655                 // up properly, set them up now.
2656                 $PAGE->set_course($PAGE->course);
2657             }
2658             //TODO: verify conditional activities here
2659             user_accesstime_log(SITEID);
2660             return;
2661         }
2663     } else {
2664         // course login always required
2665         require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2666     }
2669 /**
2670  * Require key login. Function terminates with error if key not found or incorrect.
2671  *
2672  * @global object
2673  * @global object
2674  * @global object
2675  * @global object
2676  * @uses NO_MOODLE_COOKIES
2677  * @uses PARAM_ALPHANUM
2678  * @param string $script unique script identifier
2679  * @param int $instance optional instance id
2680  * @return int Instance ID
2681  */
2682 function require_user_key_login($script, $instance=null) {
2683     global $USER, $SESSION, $CFG, $DB;
2685     if (!NO_MOODLE_COOKIES) {
2686         print_error('sessioncookiesdisable');
2687     }
2689 /// extra safety
2690     @session_write_close();
2692     $keyvalue = required_param('key', PARAM_ALPHANUM);
2694     if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2695         print_error('invalidkey');
2696     }
2698     if (!empty($key->validuntil) and $key->validuntil < time()) {
2699         print_error('expiredkey');
2700     }
2702     if ($key->iprestriction) {
2703         $remoteaddr = getremoteaddr(null);
2704         if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2705             print_error('ipmismatch');
2706         }
2707     }
2709     if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2710         print_error('invaliduserid');
2711     }
2713 /// emulate normal session
2714     session_set_user($user);
2716 /// note we are not using normal login
2717     if (!defined('USER_KEY_LOGIN')) {
2718         define('USER_KEY_LOGIN', true);
2719     }
2721 /// return instance id - it might be empty
2722     return $key->instance;
2725 /**
2726  * Creates a new private user access key.
2727  *
2728  * @global object
2729  * @param string $script unique target identifier
2730  * @param int $userid
2731  * @param int $instance optional instance id
2732  * @param string $iprestriction optional ip restricted access
2733  * @param timestamp $validuntil key valid only until given data
2734  * @return string access key value
2735  */
2736 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2737     global $DB;
2739     $key = new stdClass();
2740     $key->script        = $script;
2741     $key->userid        = $userid;
2742     $key->instance      = $instance;
2743     $key->iprestriction = $iprestriction;
2744     $key->validuntil    = $validuntil;
2745     $key->timecreated   = time();
2747     $key->value         = md5($userid.'_'.time().random_string(40)); // something long and unique
2748     while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
2749         // must be unique
2750         $key->value     = md5($userid.'_'.time().random_string(40));
2751     }
2752     $DB->insert_record('user_private_key', $key);
2753     return $key->value;
2756 /**
2757  * Delete the user's new private user access keys for a particular script.
2758  *
2759  * @global object
2760  * @param string $script unique target identifier
2761  * @param int $userid
2762  * @return void
2763  */
2764 function delete_user_key($script,$userid) {
2765     global $DB;
2766     $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
2769 /**
2770  * Gets a private user access key (and creates one if one doesn't exist).
2771  *
2772  * @global object
2773  * @param string $script unique target identifier
2774  * @param int $userid
2775  * @param int $instance optional instance id
2776  * @param string $iprestriction optional ip restricted access
2777  * @param timestamp $validuntil key valid only until given data
2778  * @return string access key value
2779  */
2780 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2781     global $DB;
2783     if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
2784                                                          'instance'=>$instance, 'iprestriction'=>$iprestriction,
2785                                                          'validuntil'=>$validuntil))) {
2786         return $key->value;
2787     } else {
2788         return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
2789     }
2793 /**
2794  * Modify the user table by setting the currently logged in user's
2795  * last login to now.
2796  *
2797  * @global object
2798  * @global object
2799  * @return bool Always returns true
2800  */
2801 function update_user_login_times() {
2802     global $USER, $DB;
2804     $user = new stdClass();
2805     $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2806     $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2808     $user->id = $USER->id;
2810     $DB->update_record('user', $user);
2811     return true;
2814 /**
2815  * Determines if a user has completed setting up their account.
2816  *
2817  * @param user $user A {@link $USER} object to test for the existence of a valid name and email
2818  * @return bool
2819  */
2820 function user_not_fully_set_up($user) {
2821     if (isguestuser($user)) {
2822         return false;
2823     }
2824     return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
2827 /**
2828  * Check whether the user has exceeded the bounce threshold
2829  *
2830  * @global object
2831  * @global object
2832  * @param user $user A {@link $USER} object
2833  * @return bool true=>User has exceeded bounce threshold
2834  */
2835 function over_bounce_threshold($user) {
2836     global $CFG, $DB;
2838     if (empty($CFG->handlebounces)) {
2839         return false;
2840     }
2842     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2843         return false;
2844     }
2846     // set sensible defaults
2847     if (empty($CFG->minbounces)) {
2848         $CFG->minbounces = 10;
2849     }
2850     if (empty($CFG->bounceratio)) {
2851         $CFG->bounceratio = .20;
2852     }
2853     $bouncecount = 0;
2854     $sendcount = 0;
2855     if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2856         $bouncecount = $bounce->value;
2857     }
2858     if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2859         $sendcount = $send->value;
2860     }
2861     return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2864 /**
2865  * Used to increment or reset email sent count
2866  *
2867  * @global object
2868  * @param user $user object containing an id
2869  * @param bool $reset will reset the count to 0
2870  * @return void
2871  */
2872 function set_send_count($user,$reset=false) {
2873     global $DB;
2875     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2876         return;
2877     }
2879     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2880         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2881         $DB->update_record('user_preferences', $pref);
2882     }
2883     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2884         // make a new one
2885         $pref = new stdClass();
2886         $pref->name   = 'email_send_count';
2887         $pref->value  = 1;
2888         $pref->userid = $user->id;
2889         $DB->insert_record('user_preferences', $pref, false);
2890     }
2893 /**
2894  * Increment or reset user's email bounce count
2895  *
2896  * @global object
2897  * @param user $user object containing an id
2898  * @param bool $reset will reset the count to 0
2899  */
2900 function set_bounce_count($user,$reset=false) {
2901     global $DB;
2903     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2904         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2905         $DB->update_record('user_preferences', $pref);
2906     }
2907     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2908         // make a new one
2909         $pref = new stdClass();
2910         $pref->name   = 'email_bounce_count';
2911         $pref->value  = 1;
2912         $pref->userid = $user->id;
2913         $DB->insert_record('user_preferences', $pref, false);
2914     }
2917 /**
2918  * Keeps track of login attempts
2919  *
2920  * @global object
2921  */
2922 function update_login_count() {
2923     global $SESSION;
2925     $max_logins = 10;
2927     if (empty($SESSION->logincount)) {
2928         $SESSION->logincount = 1;
2929     } else {
2930         $SESSION->logincount++;
2931     }
2933     if ($SESSION->logincount > $max_logins) {
2934         unset($SESSION->wantsurl);
2935         print_error('errortoomanylogins');
2936     }
2939 /**
2940  * Resets login attempts
2941  *
2942  * @global object
2943  */
2944 function reset_login_count() {
2945     global $SESSION;
2947     $SESSION->logincount = 0;
2950 /**
2951  * Returns reference to full info about modules in course (including visibility).
2952  * Cached and as fast as possible (0 or 1 db query).
2953  *
2954  * @global object
2955  * @global object
2956  * @global object
2957  * @uses CONTEXT_MODULE
2958  * @uses MAX_MODINFO_CACHE_SIZE
2959  * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
2960  * @param int $userid Defaults to current user id
2961  * @return mixed courseinfo object or nothing if resetting
2962  */
2963 function &get_fast_modinfo(&$course, $userid=0) {
2964     global $CFG, $USER, $DB;
2965     require_once($CFG->dirroot.'/course/lib.php');
2967     if (!empty($CFG->enableavailability)) {
2968         require_once($CFG->libdir.'/conditionlib.php');
2969     }
2971     static $cache = array();
2973     if ($course === 'reset') {
2974         $cache = array();
2975         $nothing = null;
2976         return $nothing; // we must return some reference
2977     }
2979     if (empty($userid)) {
2980         $userid = $USER->id;
2981     }
2983     if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
2984         return $cache[$course->id];
2985     }
2987     if (empty($course->modinfo)) {
2988         // no modinfo yet - load it
2989         rebuild_course_cache($course->id);
2990         $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2991     }
2993     $modinfo = new stdClass();
2994     $modinfo->courseid  = $course->id;
2995     $modinfo->userid    = $userid;
2996     $modinfo->sections  = array();
2997     $modinfo->cms       = array();
2998     $modinfo->instances = array();
2999     $modinfo->groups    = null; // loaded only when really needed - the only one db query
3001     $info = unserialize($course->modinfo);
3002     if (!is_array($info)) {
3003         // hmm, something is wrong - lets try to fix it
3004         rebuild_course_cache($course->id);
3005         $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
3006         $info = unserialize($course->modinfo);
3007         if (!is_array($info)) {
3008             return $modinfo;
3009         }
3010     }
3012     if ($info) {
3013         // detect if upgrade required
3014         $first = reset($info);
3015         if (!isset($first->id)) {
3016             rebuild_course_cache($course->id);
3017             $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
3018             $info = unserialize($course->modinfo);
3019             if (!is_array($info)) {
3020                 return $modinfo;
3021             }
3022         }
3023     }
3025     $modlurals = array();
3027     // If we haven't already preloaded contexts for the course, do it now
3028     preload_course_contexts($course->id);
3030     foreach ($info as $mod) {
3031         if (empty($mod->name)) {
3032             // something is wrong here
3033             continue;
3034         }
3035         // reconstruct minimalistic $cm
3036         $cm = new stdClass();
3037         $cm->id               = $mod->cm;
3038         $cm->instance         = $mod->id;
3039         $cm->course           = $course->id;
3040         $cm->modname          = $mod->mod;
3041         $cm->idnumber         = $mod->idnumber;
3042         $cm->name             = $mod->name;
3043         $cm->visible          = $mod->visible;
3044         $cm->sectionnum       = $mod->section;
3045         $cm->groupmode        = $mod->groupmode;
3046         $cm->groupingid       = $mod->groupingid;
3047         $cm->groupmembersonly = $mod->groupmembersonly;
3048         $cm->indent           = $mod->indent;
3049         $cm->completion       = $mod->completion;
3050         $cm->extra            = isset($mod->extra) ? $mod->extra : '';
3051         $cm->icon             = isset($mod->icon) ? $mod->icon : '';
3052         $cm->iconcomponent    = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
3053         $cm->uservisible      = true;
3054         if (!empty($CFG->enableavailability)) {
3055             // We must have completion information from modinfo. If it's not
3056             // there, cache needs rebuilding
3057             if(!isset($mod->availablefrom)) {
3058                 debugging('enableavailability option was changed; rebuilding '.
3059                     'cache for course '.$course->id);
3060                 rebuild_course_cache($course->id,true);
3061                 // Re-enter this routine to do it all properly
3062                 return get_fast_modinfo($course, $userid);
3063             }
3064             $cm->availablefrom    = $mod->availablefrom;
3065             $cm->availableuntil   = $mod->availableuntil;
3066             $cm->showavailability = $mod->showavailability;
3067             $cm->conditionscompletion = $mod->conditionscompletion;
3068             $cm->conditionsgrade  = $mod->conditionsgrade;
3069         }
3071         // preload long names plurals and also check module is installed properly
3072         if (!isset($modlurals[$cm->modname])) {
3073             if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
3074                 continue;
3075             }
3076             $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
3077         }
3078         $cm->modplural = $modlurals[$cm->modname];
3079         $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id);
3081         if (!empty($CFG->enableavailability)) {
3082             // Unfortunately the next call really wants to call
3083             // get_fast_modinfo, but that would be recursive, so we fake up a
3084             // modinfo for it already
3085             if (empty($minimalmodinfo)) { //TODO: this is suspicious (skodak)
3086                 $minimalmodinfo = new stdClass();
3087                 $minimalmodinfo->cms = array();
3088                 foreach($info as $mod) {
3089                     if (empty($mod->name)) {
3090                         // something is wrong here
3091                         continue;
3092                     }
3093                     $minimalcm = new stdClass();
3094                     $minimalcm->id = $mod->cm;
3095                     $minimalcm->name = $mod->name;
3096                     $minimalmodinfo->cms[$minimalcm->id]=$minimalcm;
3097                 }
3098             }
3100             // Get availability information
3101             $ci = new condition_info($cm);
3102             $cm->available = $ci->is_available($cm->availableinfo, true, $userid, $minimalmodinfo);
3103         } else {
3104             $cm->available = true;
3105         }
3106         if ((!$cm->visible or !$cm->available) and !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
3107             $cm->uservisible = false;
3109         } else if (!empty($CFG->enablegroupmembersonly) and !empty($cm->groupmembersonly)
3110                 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
3111             if (is_null($modinfo->groups)) {
3112                 $modinfo->groups = groups_get_user_groups($course->id, $userid);
3113             }
3114             if (empty($modinfo->groups[$cm->groupingid])) {
3115                 $cm->uservisible = false;
3116             }
3117         }
3119         if (!isset($modinfo->instances[$cm->modname])) {
3120             $modinfo->instances[$cm->modname] = array();
3121         }
3122         $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
3123         $modinfo->cms[$cm->id] =& $cm;
3125         // reconstruct sections
3126         if (!isset($modinfo->sections[$cm->sectionnum])) {
3127             $modinfo->sections[$cm->sectionnum] = array();
3128         }
3129         $modinfo->sections[$cm->sectionnum][] = $cm->id;
3131         unset($cm);
3132     }
3134     unset($cache[$course->id]); // prevent potential reference problems when switching users
3135     $cache[$course->id] = $modinfo;
3137     // Ensure cache does not use too much RAM
3138     if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
3139         reset($cache);
3140         $key = key($cache);
3141         unset($cache[$key]);
3142     }
3144     return $cache[$course->id];
3147 /**
3148  * Determines if the currently logged in user is in editing mode.
3149  * Note: originally this function had $userid parameter - it was not usable anyway
3150  *
3151  * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3152  * @todo Deprecated function remove when ready
3153  *
3154  * @global object
3155  * @uses DEBUG_DEVELOPER
3156  * @return bool
3157  */
3158 function isediting() {
3159     global $PAGE;
3160     debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3161     return $PAGE->user_is_editing();
3164 /**
3165  * Determines if the logged in user is currently moving an activity
3166  *
3167  * @global object
3168  * @param int $courseid The id of the course being tested
3169  * @return bool
3170  */
3171 function ismoving($courseid) {
3172     global $USER;
3174     if (!empty($USER->activitycopy)) {
3175         return ($USER->activitycopycourse == $courseid);
3176     }
3177     return false;
3180 /**
3181  * Returns a persons full name
3182  *
3183  * Given an object containing firstname and lastname
3184  * values, this function returns a string with the
3185  * full name of the person.
3186  * The result may depend on system settings
3187  * or language.  'override' will force both names
3188  * to be used even if system settings specify one.
3189  *
3190  * @global object
3191  * @global object
3192  * @param object $user A {@link $USER} object to get full name of
3193  * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3194  * @return string
3195  */
3196 function fullname($user, $override=false) {
3197     global $CFG, $SESSION;
3199     if (!isset($user->firstname) and !isset($user->lastname)) {
3200         return '';
3201     }
3203     if (!$override) {
3204         if (!empty($CFG->forcefirstname)) {
3205             $user->firstname = $CFG->forcefirstname;
3206         }
3207         if (!empty($CFG->forcelastname)) {
3208             $user->lastname = $CFG->forcelastname;
3209         }
3210     }
3212     if (!empty($SESSION->fullnamedisplay)) {
3213         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3214     }
3216     if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3217         return $user->firstname .' '. $user->lastname;
3219     } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3220         return $user->lastname .' '. $user->firstname;
3222     } else if ($CFG->fullnamedisplay == 'firstname') {
3223         if ($override) {
3224             return get_string('fullnamedisplay', '', $user);
3225         } else {
3226             return $user->firstname;
3227         }
3228     }
3230     return get_string('fullnamedisplay', '', $user);
3233 /**
3234  * Returns whether a given authentication plugin exists.
3235  *
3236  * @global object
3237  * @param string $auth Form of authentication to check for. Defaults to the
3238  *        global setting in {@link $CFG}.
3239  * @return boolean Whether the plugin is available.
3240  */
3241 function exists_auth_plugin($auth) {
3242     global $CFG;
3244     if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3245         return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3246     }
3247     return false;
3250 /**
3251  * Checks if a given plugin is in the list of enabled authentication plugins.
3252  *
3253  * @param string $auth Authentication plugin.
3254  * @return boolean Whether the plugin is enabled.
3255  */
3256 function is_enabled_auth($auth) {
3257     if (empty($auth)) {
3258         return false;
3259     }
3261     $enabled = get_enabled_auth_plugins();
3263     return in_array($auth, $enabled);
3266 /**
3267  * Returns an authentication plugin instance.
3268  *
3269  * @global object
3270  * @param string $auth name of authentication plugin
3271  * @return auth_plugin_base An instance of the required authentication plugin.
3272  */
3273 function get_auth_plugin($auth) {
3274     global $CFG;
3276     // check the plugin exists first
3277     if (! exists_auth_plugin($auth)) {
3278         print_error('authpluginnotfound', 'debug', '', $auth);
3279     }
3281     // return auth plugin instance
3282     require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3283     $class = "auth_plugin_$auth";
3284     return new $class;
3287 /**
3288  * Returns array of active auth plugins.
3289  *
3290  * @param bool $fix fix $CFG->auth if needed
3291  * @return array
3292  */
3293 function get_enabled_auth_plugins($fix=false) {
3294     global $CFG;
3296     $default = array('manual', 'nologin');
3298     if (empty($CFG->auth)) {
3299         $auths = array();
3300     } else {
3301         $auths = explode(',', $CFG->auth);
3302     }
3304     if ($fix) {
3305         $auths = array_unique($auths);
3306         foreach($auths as $k=>$authname) {
3307             if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3308                 unset($auths[$k]);
3309             }
3310         }
3311         $newconfig = implode(',', $auths);
3312         if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3313             set_config('auth', $newconfig);
3314         }
3315     }
3317     return (array_merge($default, $auths));
3320 /**
3321  * Returns true if an internal authentication method is being used.
3322  * if method not specified then, global default is assumed
3323  *
3324  * @param string $auth Form of authentication required
3325  * @return bool
3326  */
3327 function is_internal_auth($auth) {
3328     $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3329     return $authplugin->is_internal();
3332 /**
3333  * Returns true if the user is a 'restored' one
3334  *
3335  * Used in the login process to inform the user
3336  * and allow him/her to reset the password
3337  *
3338  * @uses $CFG
3339  * @uses $DB
3340  * @param string $username username to be checked
3341  * @return bool
3342  */
3343 function is_restored_user($username) {
3344     global $CFG, $DB;
3346     return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3349 /**
3350  * Returns an array of user fields
3351  *
3352  * @return array User field/column names
3353  */
3354 function get_user_fieldnames() {
3355     global $DB;
3357     $fieldarray = $DB->get_columns('user');
3358     unset($fieldarray['id']);
3359     $fieldarray = array_keys($fieldarray);
3361     return $fieldarray;
3364 /**
3365  * Creates a bare-bones user record
3366  *
3367  * @todo Outline auth types and provide code example
3368  *
3369  * @global object
3370  * @global object
3371  * @param string $username New user's username to add to record
3372  * @param string $password New user's password to add to record
3373  * @param string $auth Form of authentication required
3374  * @return object A {@link $USER} object
3375  */
3376 function create_user_record($username, $password, $auth='manual') {
3377     global $CFG, $DB;
3379     //just in case check text case
3380     $username = trim(moodle_strtolower($username));
3382     $authplugin = get_auth_plugin($auth);
3384     $newuser = new stdClass();
3386     if ($newinfo = $authplugin->get_userinfo($username)) {
3387         $newinfo = truncate_userinfo($newinfo);
3388         foreach ($newinfo as $key => $value){
3389             $newuser->$key = $value;
3390         }
3391     }
3393     if (!empty($newuser->email)) {
3394         if (email_is_not_allowed($newuser->email)) {
3395             unset($newuser->email);
3396         }
3397     }
3399     if (!isset($newuser->city)) {
3400         $newuser->city = '';
3401     }
3403     $newuser->auth = $auth;
3404     $newuser->username = $username;
3406     // fix for MDL-8480
3407     // user CFG lang for user if $newuser->lang is empty
3408     // or $user->lang is not an installed language
3409     if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3410         $newuser->lang = $CFG->lang;
3411     }
3412     $newuser->confirmed = 1;
3413     $newuser->lastip = getremoteaddr();
3414     $newuser->timemodified = time();
3415     $newuser->mnethostid = $CFG->mnet_localhost_id;
3417     $DB->insert_record('user', $newuser);
3418     $user = get_complete_user_data('username', $newuser->username);
3419     if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3420         set_user_preference('auth_forcepasswordchange', 1, $user->id);
3421     }
3422     update_internal_user_password($user, $password);
3423     return $user;
3426 /**
3427  * Will update a local user record from an external source
3428  *
3429  * @global object
3430  * @param string $username New user's username to add to record
3431  * @param string $authplugin Unused
3432  * @return user A {@link $USER} object
3433  */
3434 function update_user_record($username, $authplugin) {
3435     global $DB;
3437     $username = trim(moodle_strtolower($username)); /// just in case check text case
3439     $oldinfo = $DB->get_record('user', array('username'=>$username), 'username, auth');
3440     $userauth = get_auth_plugin($oldinfo->auth);
3442     if ($newinfo = $userauth->get_userinfo($username)) {
3443         $newinfo = truncate_userinfo($newinfo);
3444         foreach ($newinfo as $key => $value){
3445             if ($key === 'username') {
3446                 // 'username' is not a mapped updateable/lockable field, so skip it.
3447                 continue;
3448             }
3449             $confval = $userauth->config->{'field_updatelocal_' . $key};
3450             $lockval = $userauth->config->{'field_lock_' . $key};
3451             if (empty($confval) || empty($lockval)) {
3452                 continue;
3453             }
3454             if ($confval === 'onlogin') {
3455                 // MDL-4207 Don't overwrite modified user profile values with
3456                 // empty LDAP values when 'unlocked if empty' is set. The purpose
3457                 // of the setting 'unlocked if empty' is to allow the user to fill
3458                 // in a value for the selected field _if LDAP is giving
3459                 // nothing_ for this field. Thus it makes sense to let this value
3460                 // stand in until LDAP is giving a value for this field.
3461                 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3462                     $DB->set_field('user', $key, $value, array('username'=>$username));
3463                 }
3464             }
3465         }
3466     }
3468     return get_complete_user_data('username', $username);
3471 /**
3472  * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3473  * which may have large fields
3474  *
3475  * @todo Add vartype handling to ensure $info is an array
3476  *
3477  * @param array $info Array of user properties to truncate if needed
3478  * @return array The now truncated information that was passed in
3479  */
3480 function truncate_userinfo($info) {
3481     // define the limits
3482     $limit = array(
3483                     'username'    => 100,
3484                     'idnumber'    => 255,
3485                     'firstname'   => 100,
3486                     'lastname'    => 100,
3487                     'email'       => 100,
3488                     'icq'         =>  15,
3489                     'phone1'      =>  20,
3490                     'phone2'      =>  20,
3491                     'institution' =>  40,
3492                     'department'  =>  30,
3493                     'address'     =>  70,
3494                     'city'        => 120,
3495                     'country'     =>   2,
3496                     'url'         => 255,
3497                     );
3499     // apply where needed
3500     foreach (array_keys($info) as $key) {
3501         if (!empty($limit[$key])) {
3502             $info[$key] = trim(substr($info[$key],0, $limit[$key]));
3503         }
3504     }
3506     return $info;
3509 /**
3510  * Marks user deleted in internal user database and notifies the auth plugin.
3511  * Also unenrols user from all roles and does other cleanup.
3512  *
3513  * Any plugin that needs to purge user data should register the 'user_deleted' event.
3514  *
3515  * @param object $user User object before delete
3516  * @return boolean always true
3517  */
3518 function delete_user($user) {
3519     global $CFG, $DB;
3520     require_once($CFG->libdir.'/grouplib.php');
3521     require_once($CFG->libdir.'/gradelib.php');
3522     require_once($CFG->dirroot.'/message/lib.php');
3524     // delete all grades - backup is kept in grade_grades_history table
3525     grade_user_delete($user->id);
3527     //move unread messages from this user to read
3528     message_move_userfrom_unread2read($user->id);
3530     // remove from all cohorts
3531     $DB->delete_records('cohort_members', array('userid'=>$user->id));
3533     // remove from all groups
3534     $DB->delete_records('groups_members', array('userid'=>$user->id));
3536     // brute force unenrol from all courses
3537     $DB->delete_records('user_enrolments', array('userid'=>$user->id));
3539     // purge user preferences
3540     $DB->delete_records('user_preferences', array('userid'=>$user->id));
3542     // purge user extra profile info
3543     $DB->delete_records('user_info_data', array('userid'=>$user->id));
3545     // last course access not necessary either
3546     $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
3548     // final accesslib cleanup - removes all role assignments in user context and context itself, files, etc.
3549     delete_context(CONTEXT_USER, $user->id);
3551     require_once($CFG->dirroot.'/tag/lib.php');
3552     tag_set('user', $user->id, array());
3554     // workaround for bulk deletes of users with the same email address
3555     $delname = "$user->email.".time();
3556     while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3557         $delname++;
3558     }
3560     // mark internal user record as "deleted"
3561     $updateuser = new stdClass();
3562     $updateuser->id           = $user->id;
3563     $updateuser->deleted      = 1;
3564     $updateuser->username     = $delname;            // Remember it just in case
3565     $updateuser->email        = md5($user->username);// Store hash of username, useful importing/restoring users
3566     $updateuser->idnumber     = '';                  // Clear this field to free it up
3567     $updateuser->timemodified = time();
3569     $DB->update_record('user', $updateuser);
3571     // notify auth plugin - do not block the delete even when plugin fails
3572     $authplugin = get_auth_plugin($user->auth);
3573     $authplugin->user_delete($user);
3575     // any plugin that needs to cleanup should register this event
3576     events_trigger('user_deleted', $user);
3578     return true;
3581 /**
3582  * Retrieve the guest user object
3583  *
3584  * @global object
3585  * @global object
3586  * @return user A {@link $USER} object
3587  */
3588 function guest_user() {
3589     global $CFG, $DB;
3591     if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
3592         $newuser->confirmed = 1;
3593         $newuser->lang = $CFG->lang;
3594         $newuser->lastip = getremoteaddr();
3595     }
3597     return $newuser;
3600 /**
3601  * Authenticates a user against the chosen authentication mechanism
3602  *
3603  * Given a username and password, this function looks them
3604  * up using the currently selected authentication mechanism,
3605  * and if the authentication is successful, it returns a
3606  * valid $user object from the 'user' table.
3607  *
3608  * Uses auth_ functions from the currently active auth module
3609  *
3610  * After authenticate_user_login() returns success, you will need to
3611  * log that the user has logged in, and call complete_user_login() to set
3612  * the session up.
3613  *
3614  * @global object
3615  * @global object
3616  * @param string $username  User's username
3617  * @param string $password  User's password
3618  * @return user|flase A {@link $USER} object or false if error
3619  */
3620 function authenticate_user_login($username, $password) {
3621     global $CFG, $DB, $OUTPUT;
3623     $authsenabled = get_enabled_auth_plugins();
3625     if ($user = get_complete_user_data('username', $username)) {
3626         $auth = empty($user->auth) ? 'manual' : $user->auth;  // use manual if auth not set
3627         if (!empty($user->suspended)) {
3628             add_to_log(0, 'login', 'error', 'index.php', $username);
3629             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Suspended Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3630             return false;
3631         }
3632         if ($auth=='nologin' or !is_enabled_auth($auth)) {
3633             add_to_log(0, 'login', 'error', 'index.php', $username);
3634             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Disabled Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3635             return false;
3636         }
3637         $auths = array($auth);
3639     } else {
3640         // check if there's a deleted record (cheaply)
3641         if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
3642             error_log('[client '.$_SERVER['REMOTE_ADDR']."]  $CFG->wwwroot  Deleted Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3643             return false;
3644         }
3646         $auths = $authsenabled;
3647         $user = new stdClass();
3648         $user->id = 0;     // User does not exist
3649     }
3651     foreach ($auths as $auth) {
3652         $authplugin = get_auth_plugin($auth);
3654         // on auth fail fall through to the next plugin
3655         if (!$authplugin->user_login($username, $password)) {
3656             continue;
3657         }
3659         // successful authentication
3660         if ($user->id) {                          // User already exists in database
3661             if (empty($user->auth)) {             // For some reason auth isn't set yet
3662                 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
3663                 $user->auth = $auth;
3664             }
3665             if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3666                 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
3667                 $user->firstaccess = $user->timemodified;
3668             }
3670             update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3672             if (!$authplugin->is_internal()) {            // update user record from external DB
3673                 $user = update_user_record($username, get_auth_plugin($user->auth));
3674             }
3675         } else {
3676             // if user not found, create him
3677             $user = create_user_record($username, $password, $auth);
3678         }
3680         $authplugin->sync_roles($user);
3682         foreach ($authsenabled as $hau) {
3683             $hauth = get_auth_plugin($hau);
3684             $hauth->user_authenticated_hook($user, $username, $password);
3685         }
3687         if (empty($user->id)) {
3688             return false;
3689         }