MDL-21068 do not show admin usernames in cron logs
[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   moodlecore
27  * @copyright 1999 onwards Martin Dougiamas  http://dougiamas.com
28  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29  */
31 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
33 /**
34  * Used by some scripts to check they are being called by Moodle
35  */
36 define('MOODLE_INTERNAL', true);
38 /// Date and time constants ///
39 /**
40  * Time constant - the number of seconds in a year
41  */
42 define('YEARSECS', 31536000);
44 /**
45  * Time constant - the number of seconds in a week
46  */
47 define('WEEKSECS', 604800);
49 /**
50  * Time constant - the number of seconds in a day
51  */
52 define('DAYSECS', 86400);
54 /**
55  * Time constant - the number of seconds in an hour
56  */
57 define('HOURSECS', 3600);
59 /**
60  * Time constant - the number of seconds in a minute
61  */
62 define('MINSECS', 60);
64 /**
65  * Time constant - the number of minutes in a day
66  */
67 define('DAYMINS', 1440);
69 /**
70  * Time constant - the number of minutes in an hour
71  */
72 define('HOURMINS', 60);
74 /// Parameter constants - every call to optional_param(), required_param()  ///
75 /// or clean_param() should have a specified type of parameter.  //////////////
79 /**
80  * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
81  */
82 define('PARAM_ALPHA',    'alpha');
84 /**
85  * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
86  * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
87  */
88 define('PARAM_ALPHAEXT', 'alphaext');
90 /**
91  * PARAM_ALPHANUM - expected numbers and letters only.
92  */
93 define('PARAM_ALPHANUM', 'alphanum');
95 /**
96  * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
97  */
98 define('PARAM_ALPHANUMEXT', 'alphanumext');
100 /**
101  * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
102  */
103 define('PARAM_AUTH',  'auth');
105 /**
106  * PARAM_BASE64 - Base 64 encoded format
107  */
108 define('PARAM_BASE64',   'base64');
110 /**
111  * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
112  */
113 define('PARAM_BOOL',     'bool');
115 /**
116  * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
117  * checked against the list of capabilties in the database.
118  */
119 define('PARAM_CAPABILITY',   'capability');
121 /**
122  * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes. It stays as HTML.
123  */
124 define('PARAM_CLEANHTML', 'cleanhtml');
126 /**
127  * PARAM_EMAIL - an email address following the RFC
128  */
129 define('PARAM_EMAIL',   'email');
131 /**
132  * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
133  */
134 define('PARAM_FILE',   'file');
136 /**
137  * PARAM_FLOAT - a real/floating point number.
138  */
139 define('PARAM_FLOAT',  'float');
141 /**
142  * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
143  */
144 define('PARAM_HOST',     'host');
146 /**
147  * PARAM_INT - integers only, use when expecting only numbers.
148  */
149 define('PARAM_INT',      'int');
151 /**
152  * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
153  */
154 define('PARAM_LANG',  'lang');
156 /**
157  * 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!)
158  */
159 define('PARAM_LOCALURL', 'localurl');
161 /**
162  * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
163  */
164 define('PARAM_NOTAGS',   'notags');
166 /**
167  * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
168  * note: the leading slash is not removed, window drive letter is not allowed
169  */
170 define('PARAM_PATH',     'path');
172 /**
173  * PARAM_PEM - Privacy Enhanced Mail format
174  */
175 define('PARAM_PEM',      'pem');
177 /**
178  * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
179  */
180 define('PARAM_PERMISSION',   'permission');
182 /**
183  * PARAM_RAW specifies a parameter that is not cleaned/processed in any way
184  */
185 define('PARAM_RAW', 'raw');
187 /**
188  * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
189  */
190 define('PARAM_SAFEDIR',  'safedir');
192 /**
193  * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
194  */
195 define('PARAM_SAFEPATH',  'safepath');
197 /**
198  * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9.  Numbers and comma only.
199  */
200 define('PARAM_SEQUENCE',  'sequence');
202 /**
203  * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
204  */
205 define('PARAM_TAG',   'tag');
207 /**
208  * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
209  */
210 define('PARAM_TAGLIST',   'taglist');
212 /**
213  * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
214  */
215 define('PARAM_TEXT',  'text');
217 /**
218  * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
219  */
220 define('PARAM_THEME',  'theme');
222 /**
223  * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not acceppted but http://localhost.localdomain/ is ok.
224  */
225 define('PARAM_URL',      'url');
227 /**
228  * PARAM_USERNAME - Clean username to only contains specified characters.
229  */
230 define('PARAM_USERNAME',    'username');
233 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE  /////
234 /**
235  * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
236  * It was one of the first types, that is why it is abused so much ;-)
237  */
238 define('PARAM_CLEAN',    'clean');
240 /**
241  * PARAM_INTEGER - deprecated alias for PARAM_INT
242  */
243 define('PARAM_INTEGER',  'int');
245 /**
246  * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
247  */
248 define('PARAM_NUMBER',  'float');
250 /**
251  * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in formas and urls
252  * NOTE: originally alias for PARAM_APLHA
253  */
254 define('PARAM_ACTION',   'alphanumext');
256 /**
257  * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
258  * NOTE: originally alias for PARAM_APLHA
259  */
260 define('PARAM_FORMAT',   'alphanumext');
262 /**
263  * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
264  */
265 define('PARAM_MULTILANG',  'text');
267 /**
268  * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
269  */
270 define('PARAM_CLEANFILE', 'file');
272 /// Web Services ///
274 /**
275  * VALUE_REQUIRED - if the parameter is not supplied, there is an error
276  */
277 define('VALUE_REQUIRED', 1);
279 /**
280  * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
281  */
282 define('VALUE_OPTIONAL', 2);
284 /**
285  * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
286  */
287 define('VALUE_DEFAULT', 0);
289 /**
290  * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
291  */
292 define('NULL_NOT_ALLOWED', false);
294 /**
295  * NULL_ALLOWED - the parameter can be set to null in the database
296  */
297 define('NULL_ALLOWED', true);
299 /// Page types ///
300 /**
301  * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
302  */
303 define('PAGE_COURSE_VIEW', 'course-view');
305 /** Get remote addr constant */
306 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
307 /** Get remote addr constant */
308 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
310 /// Blog access level constant declaration ///
311 define ('BLOG_USER_LEVEL', 1);
312 define ('BLOG_GROUP_LEVEL', 2);
313 define ('BLOG_COURSE_LEVEL', 3);
314 define ('BLOG_SITE_LEVEL', 4);
315 define ('BLOG_GLOBAL_LEVEL', 5);
318 ///Tag constants///
319 /**
320  * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
321  * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
322  * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
323  *
324  * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
325  */
326 define('TAG_MAX_LENGTH', 50);
328 /// Password policy constants ///
329 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
330 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
331 define ('PASSWORD_DIGITS', '0123456789');
332 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
334 /// Feature constants ///
335 // Used for plugin_supports() to report features that are, or are not, supported by a module.
337 /** True if module can provide a grade */
338 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
339 /** True if module supports outcomes */
340 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
342 /** True if module has code to track whether somebody viewed it */
343 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
344 /** True if module has custom completion rules */
345 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
347 /** True if module supports outcomes */
348 define('FEATURE_IDNUMBER', 'idnumber');
349 /** True if module supports groups */
350 define('FEATURE_GROUPS', 'groups');
351 /** True if module supports groupings */
352 define('FEATURE_GROUPINGS', 'groupings');
353 /** True if module supports groupmembersonly */
354 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
356 /** Type of module */
357 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
358 /** True if module supports intro editor */
359 define('FEATURE_MOD_INTRO', 'mod_intro');
360 /** True if module supports subplugins */
361 define('FEATURE_MOD_SUBPLUGINS', 'mod_subplugins');
362 /** True if module has default completion */
363 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
365 define('FEATURE_COMMENT', 'comment');
367 define('FEATURE_RATE', 'rate');
369 /** Unspecified module archetype */
370 define('MOD_ARCHETYPE_OTHER', 0);
371 /** Resource-like type module */
372 define('MOD_ARCHETYPE_RESOURCE', 1);
373 /** Assignemnt module archetype */
374 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
376 /**
377  * Security token used for allowing access
378  * from external application such as web services.
379  * Scripts do not use any session, performance is relatively
380  * low because we need to load access info in each request.
381  * Scrits are executed in parallel.
382  */
383 define('EXTERNAL_TOKEN_PERMANENT', 0);
385 /**
386  * Security token used for allowing access
387  * of embedded applications, the code is executed in the
388  * active user session. Token is invalidated after user logs out.
389  * Scripts are executed serially - normal session locking is used.
390  */
391 define('EXTERNAL_TOKEN_EMBEDDED', 1);
393 /// PARAMETER HANDLING ////////////////////////////////////////////////////
395 /**
396  * Returns a particular value for the named variable, taken from
397  * POST or GET.  If the parameter doesn't exist then an error is
398  * thrown because we require this variable.
399  *
400  * This function should be used to initialise all required values
401  * in a script that are based on parameters.  Usually it will be
402  * used like this:
403  *    $id = required_param('id', PARAM_INT);
404  *
405  * @param string $parname the name of the page parameter we want,
406  *                        default PARAM_CLEAN
407  * @param int $type expected type of parameter
408  * @return mixed
409  */
410 function required_param($parname, $type=PARAM_CLEAN) {
411     if (isset($_POST[$parname])) {       // POST has precedence
412         $param = $_POST[$parname];
413     } else if (isset($_GET[$parname])) {
414         $param = $_GET[$parname];
415     } else {
416         print_error('missingparam', '', '', $parname);
417     }
419     return clean_param($param, $type);
422 /**
423  * Returns a particular value for the named variable, taken from
424  * POST or GET, otherwise returning a given default.
425  *
426  * This function should be used to initialise all optional values
427  * in a script that are based on parameters.  Usually it will be
428  * used like this:
429  *    $name = optional_param('name', 'Fred', PARAM_TEXT);
430  *
431  * @param string $parname the name of the page parameter we want
432  * @param mixed  $default the default value to return if nothing is found
433  * @param int $type expected type of parameter, default PARAM_CLEAN
434  * @return mixed
435  */
436 function optional_param($parname, $default=NULL, $type=PARAM_CLEAN) {
437     if (isset($_POST[$parname])) {       // POST has precedence
438         $param = $_POST[$parname];
439     } else if (isset($_GET[$parname])) {
440         $param = $_GET[$parname];
441     } else {
442         return $default;
443     }
445     return clean_param($param, $type);
448 /**
449  * Strict validation of parameter values, the values are only converted
450  * to requested PHP type. Internally it is using clean_param, the values
451  * before and after cleaning must be equal - otherwise
452  * an invalid_parameter_exception is thrown.
453  * Onjects and classes are not accepted.
454  *
455  * @param mixed $param
456  * @param int $type PARAM_ constant
457  * @param bool $allownull are nulls valid value?
458  * @param string $debuginfo optional debug information
459  * @return mixed the $param value converted to PHP type or invalid_parameter_exception
460  */
461 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
462     if (is_null($param)) {
463         if ($allownull == NULL_ALLOWED) {
464             return null;
465         } else {
466             throw new invalid_parameter_exception($debuginfo);
467         }
468     }
469     if (is_array($param) or is_object($param)) {
470         throw new invalid_parameter_exception($debuginfo);
471     }
473     $cleaned = clean_param($param, $type);
474     if ((string)$param !== (string)$cleaned) {
475         // conversion to string is usually lossless
476         throw new invalid_parameter_exception($debuginfo);
477     }
479     return $cleaned;
482 /**
483  * Used by {@link optional_param()} and {@link required_param()} to
484  * clean the variables and/or cast to specific types, based on
485  * an options field.
486  * <code>
487  * $course->format = clean_param($course->format, PARAM_ALPHA);
488  * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
489  * </code>
490  *
491  * @global object
492  * @uses PARAM_RAW
493  * @uses PARAM_CLEAN
494  * @uses PARAM_CLEANHTML
495  * @uses PARAM_INT
496  * @uses PARAM_FLOAT
497  * @uses PARAM_NUMBER
498  * @uses PARAM_ALPHA
499  * @uses PARAM_ALPHAEXT
500  * @uses PARAM_ALPHANUM
501  * @uses PARAM_ALPHANUMEXT
502  * @uses PARAM_SEQUENCE
503  * @uses PARAM_BOOL
504  * @uses PARAM_NOTAGS
505  * @uses PARAM_TEXT
506  * @uses PARAM_SAFEDIR
507  * @uses PARAM_SAFEPATH
508  * @uses PARAM_FILE
509  * @uses PARAM_PATH
510  * @uses PARAM_HOST
511  * @uses PARAM_URL
512  * @uses PARAM_LOCALURL
513  * @uses PARAM_PEM
514  * @uses PARAM_BASE64
515  * @uses PARAM_TAG
516  * @uses PARAM_SEQUENCE
517  * @uses PARAM_USERNAME
518  * @param mixed $param the variable we are cleaning
519  * @param int $type expected format of param after cleaning.
520  * @return mixed
521  */
522 function clean_param($param, $type) {
524     global $CFG;
526     if (is_array($param)) {              // Let's loop
527         $newparam = array();
528         foreach ($param as $key => $value) {
529             $newparam[$key] = clean_param($value, $type);
530         }
531         return $newparam;
532     }
534     switch ($type) {
535         case PARAM_RAW:          // no cleaning at all
536             return $param;
538         case PARAM_CLEAN:        // General HTML cleaning, try to use more specific type if possible
539             if (is_numeric($param)) {
540                 return $param;
541             }
542             return clean_text($param);     // Sweep for scripts, etc
544         case PARAM_CLEANHTML:    // prepare html fragment for display, do not store it into db!!
545             $param = clean_text($param);     // Sweep for scripts, etc
546             return trim($param);
548         case PARAM_INT:
549             return (int)$param;  // Convert to integer
551         case PARAM_FLOAT:
552         case PARAM_NUMBER:
553             return (float)$param;  // Convert to float
555         case PARAM_ALPHA:        // Remove everything not a-z
556             return preg_replace('/[^a-zA-Z]/i', '', $param);
558         case PARAM_ALPHAEXT:     // Remove everything not a-zA-Z_- (originally allowed "/" too)
559             return preg_replace('/[^a-zA-Z_-]/i', '', $param);
561         case PARAM_ALPHANUM:     // Remove everything not a-zA-Z0-9
562             return preg_replace('/[^A-Za-z0-9]/i', '', $param);
564         case PARAM_ALPHANUMEXT:     // Remove everything not a-zA-Z0-9_-
565             return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
567         case PARAM_SEQUENCE:     // Remove everything not 0-9,
568             return preg_replace('/[^0-9,]/i', '', $param);
570         case PARAM_BOOL:         // Convert to 1 or 0
571             $tempstr = strtolower($param);
572             if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
573                 $param = 1;
574             } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
575                 $param = 0;
576             } else {
577                 $param = empty($param) ? 0 : 1;
578             }
579             return $param;
581         case PARAM_NOTAGS:       // Strip all tags
582             return strip_tags($param);
584         case PARAM_TEXT:    // leave only tags needed for multilang
585             return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);
587         case PARAM_SAFEDIR:      // Remove everything not a-zA-Z0-9_-
588             return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
590         case PARAM_SAFEPATH:     // Remove everything not a-zA-Z0-9/_-
591             return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
593         case PARAM_FILE:         // Strip all suspicious characters from filename
594             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\/]~u', '', $param);
595             $param = preg_replace('~\.\.+~', '', $param);
596             if ($param === '.') {
597                 $param = '';
598             }
599             return $param;
601         case PARAM_PATH:         // Strip all suspicious characters from file path
602             $param = str_replace('\\', '/', $param);
603             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
604             $param = preg_replace('~\.\.+~', '', $param);
605             $param = preg_replace('~//+~', '/', $param);
606             return preg_replace('~/(\./)+~', '/', $param);
608         case PARAM_HOST:         // allow FQDN or IPv4 dotted quad
609             $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
610             // match ipv4 dotted quad
611             if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
612                 // confirm values are ok
613                 if ( $match[0] > 255
614                      || $match[1] > 255
615                      || $match[3] > 255
616                      || $match[4] > 255 ) {
617                     // hmmm, what kind of dotted quad is this?
618                     $param = '';
619                 }
620             } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
621                        && !preg_match('/^[\.-]/',  $param) // no leading dots/hyphens
622                        && !preg_match('/[\.-]$/',  $param) // no trailing dots/hyphens
623                        ) {
624                 // all is ok - $param is respected
625             } else {
626                 // all is not ok...
627                 $param='';
628             }
629             return $param;
631         case PARAM_URL:          // allow safe ftp, http, mailto urls
632             include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
633             if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
634                 // all is ok, param is respected
635             } else {
636                 $param =''; // not really ok
637             }
638             return $param;
640         case PARAM_LOCALURL:     // allow http absolute, root relative and relative URLs within wwwroot
641             $param = clean_param($param, PARAM_URL);
642             if (!empty($param)) {
643                 if (preg_match(':^/:', $param)) {
644                     // root-relative, ok!
645                 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
646                     // absolute, and matches our wwwroot
647                 } else {
648                     // relative - let's make sure there are no tricks
649                     if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
650                         // looks ok.
651                     } else {
652                         $param = '';
653                     }
654                 }
655             }
656             return $param;
658         case PARAM_PEM:
659             $param = trim($param);
660             // PEM formatted strings may contain letters/numbers and the symbols
661             // forward slash: /
662             // plus sign:     +
663             // equal sign:    =
664             // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
665             if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
666                 list($wholething, $body) = $matches;
667                 unset($wholething, $matches);
668                 $b64 = clean_param($body, PARAM_BASE64);
669                 if (!empty($b64)) {
670                     return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
671                 } else {
672                     return '';
673                 }
674             }
675             return '';
677         case PARAM_BASE64:
678             if (!empty($param)) {
679                 // PEM formatted strings may contain letters/numbers and the symbols
680                 // forward slash: /
681                 // plus sign:     +
682                 // equal sign:    =
683                 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
684                     return '';
685                 }
686                 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
687                 // Each line of base64 encoded data must be 64 characters in
688                 // length, except for the last line which may be less than (or
689                 // equal to) 64 characters long.
690                 for ($i=0, $j=count($lines); $i < $j; $i++) {
691                     if ($i + 1 == $j) {
692                         if (64 < strlen($lines[$i])) {
693                             return '';
694                         }
695                         continue;
696                     }
698                     if (64 != strlen($lines[$i])) {
699                         return '';
700                     }
701                 }
702                 return implode("\n",$lines);
703             } else {
704                 return '';
705             }
707         case PARAM_TAG:
708             //as long as magic_quotes_gpc is used, a backslash will be a
709             //problem, so remove *all* backslash.
710             //$param = str_replace('\\', '', $param);
711             //remove some nasties
712             $param = preg_replace('~[[:cntrl:]]|[<>`]~', '', $param);
713             //convert many whitespace chars into one
714             $param = preg_replace('/\s+/', ' ', $param);
715             $textlib = textlib_get_instance();
716             $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
717             return $param;
720         case PARAM_TAGLIST:
721             $tags = explode(',', $param);
722             $result = array();
723             foreach ($tags as $tag) {
724                 $res = clean_param($tag, PARAM_TAG);
725                 if ($res !== '') {
726                     $result[] = $res;
727                 }
728             }
729             if ($result) {
730                 return implode(',', $result);
731             } else {
732                 return '';
733             }
735         case PARAM_CAPABILITY:
736             if (is_valid_capability($param)) {
737                 return $param;
738             } else {
739                 return '';
740             }
742         case PARAM_PERMISSION:
743             $param = (int)$param;
744             if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
745                 return $param;
746             } else {
747                 return CAP_INHERIT;
748             }
750         case PARAM_AUTH:
751             $param = clean_param($param, PARAM_SAFEDIR);
752             if (exists_auth_plugin($param)) {
753                 return $param;
754             } else {
755                 return '';
756             }
758         case PARAM_LANG:
759             $param = clean_param($param, PARAM_SAFEDIR);
760             $langs = get_list_of_languages(false, true);
761             if (in_array($param, $langs)) {
762                 return $param;
763             } else {
764                 return '';  // Specified language is not installed
765             }
767         case PARAM_THEME:
768             $param = clean_param($param, PARAM_SAFEDIR);
769             if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
770                 return $param;
771             } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
772                 return $param;
773             } else {
774                 return '';  // Specified theme is not installed
775             }
777         case PARAM_USERNAME:
778             $param = str_replace(" " , "", $param);
779             $param = moodle_strtolower($param);  // Convert uppercase to lowercase MDL-16919
780             if (empty($CFG->extendedusernamechars)) {
781                 // regular expression, eliminate all chars EXCEPT:
782                 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
783                 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
784             } 
785             return $param;
787         case PARAM_EMAIL:
788             if (validate_email($param)) {
789                 return $param;
790             } else {
791                 return '';
792             }
794         default:                 // throw error, switched parameters in optional_param or another serious problem
795             print_error("unknownparamtype", '', '', $type);
796     }
799 /**
800  * Return true if given value is integer or string with integer value
801  *
802  * @param mixed $value String or Int
803  * @return bool true if number, false if not
804  */
805 function is_number($value) {
806     if (is_int($value)) {
807         return true;
808     } else if (is_string($value)) {
809         return ((string)(int)$value) === $value;
810     } else {
811         return false;
812     }
815 /**
816  * Returns host part from url
817  * @param string $url full url
818  * @return string host, null if not found
819  */
820 function get_host_from_url($url) {
821     preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
822     if ($matches) {
823         return $matches[1];
824     }
825     return null;
828 /**
829  * Tests whether anything was returned by text editor
830  *
831  * This function is useful for testing whether something you got back from
832  * the HTML editor actually contains anything. Sometimes the HTML editor
833  * appear to be empty, but actually you get back a <br> tag or something.
834  *
835  * @param string $string a string containing HTML.
836  * @return boolean does the string contain any actual content - that is text,
837  * images, objcts, etc.
838  */
839 function html_is_blank($string) {
840     return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
843 /**
844  * Set a key in global configuration
845  *
846  * Set a key/value pair in both this session's {@link $CFG} global variable
847  * and in the 'config' database table for future sessions.
848  *
849  * Can also be used to update keys for plugin-scoped configs in config_plugin table.
850  * In that case it doesn't affect $CFG.
851  *
852  * A NULL value will delete the entry.
853  *
854  * @global object
855  * @global object
856  * @param string $name the key to set
857  * @param string $value the value to set (without magic quotes)
858  * @param string $plugin (optional) the plugin scope, default NULL
859  * @return bool true or exception
860  */
861 function set_config($name, $value, $plugin=NULL) {
862     global $CFG, $DB;
864     if (empty($plugin)) {
865         if (!array_key_exists($name, $CFG->config_php_settings)) {
866             // So it's defined for this invocation at least
867             if (is_null($value)) {
868                 unset($CFG->$name);
869             } else {
870                 $CFG->$name = (string)$value; // settings from db are always strings
871             }
872         }
874         if ($DB->get_field('config', 'name', array('name'=>$name))) {
875             if ($value === null) {
876                 $DB->delete_records('config', array('name'=>$name));
877             } else {
878                 $DB->set_field('config', 'value', $value, array('name'=>$name));
879             }
880         } else {
881             if ($value !== null) {
882                 $config = new object();
883                 $config->name  = $name;
884                 $config->value = $value;
885                 $DB->insert_record('config', $config, false);
886             }
887         }
889     } else { // plugin scope
890         if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
891             if ($value===null) {
892                 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
893             } else {
894                 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
895             }
896         } else {
897             if ($value !== null) {
898                 $config = new object();
899                 $config->plugin = $plugin;
900                 $config->name   = $name;
901                 $config->value  = $value;
902                 $DB->insert_record('config_plugins', $config, false);
903             }
904         }
905     }
907     return true;
910 /**
911  * Get configuration values from the global config table
912  * or the config_plugins table.
913  *
914  * If called with no parameters it will do the right thing
915  * generating $CFG safely from the database without overwriting
916  * existing values.
917  *
918  * If called with one parameter, it will load all the config
919  * variables for one pugin, and return them as an object.
920  *
921  * If called with 2 parameters it will return a $string single
922  * value or false of the value is not found.
923  *
924  * @global object
925  * @param string $plugin default NULL
926  * @param string $name default NULL
927  * @return mixed hash-like object or single value
928  */
929 function get_config($plugin=NULL, $name=NULL) {
930     global $CFG, $DB;
932     if (!empty($name)) { // the user is asking for a specific value
933         if (!empty($plugin)) {
934             return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
935         } else {
936             return $DB->get_field('config', 'value', array('name'=>$name));
937         }
938     }
940     // the user is after a recordset
941     if (!empty($plugin)) {
942         $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
943         if (!empty($localcfg)) {
944             return (object)$localcfg;
945         } else {
946             return false;
947         }
948     } else {
949         // this was originally in setup.php
950         if ($configs = $DB->get_records('config')) {
951             $localcfg = (array)$CFG;
952             foreach ($configs as $config) {
953                 if (!isset($localcfg[$config->name])) {
954                     $localcfg[$config->name] = $config->value;
955                 }
956                 // do not complain anymore if config.php overrides settings from db
957             }
959             $localcfg = (object)$localcfg;
960             return $localcfg;
961         } else {
962             // preserve $CFG if DB returns nothing or error
963             return $CFG;
964         }
966     }
969 /**
970  * Removes a key from global configuration
971  *
972  * @param string $name the key to set
973  * @param string $plugin (optional) the plugin scope
974  * @global object
975  * @return boolean whether the operation succeeded.
976  */
977 function unset_config($name, $plugin=NULL) {
978     global $CFG, $DB;
980     if (empty($plugin)) {
981         unset($CFG->$name);
982         $DB->delete_records('config', array('name'=>$name));
983     } else {
984         $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
985     }
987     return true;
990 /**
991  * Remove all the config variables for a given plugin.
992  *
993  * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
994  * @return boolean whether the operation succeeded.
995  */
996 function unset_all_config_for_plugin($plugin) {
997     global $DB;
998     $DB->delete_records('config_plugins', array('plugin' => $plugin));
999     $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
1000     return true;
1003 /**
1004  * Use this funciton to get a list of users from a config setting of type admin_setting_users_with_capability.
1005  * @param string $value the value of the config setting.
1006  * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1007  * @return array of user objects.
1008  */
1009 function get_users_from_config($value, $capability) {
1010     global $CFG;
1011     if ($value == '$@ALL@$') {
1012         $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1013     } else {
1014         list($where, $params) = $DB->get_in_or_equal(explode(',', $CFG->courserequestnotify));
1015         $params[] = $CFG->mnet_localhost_id;
1016         $users = $DB->get_records_select('user', 'username ' . $where . ' AND mnethostid = ?', $params);
1017     }
1018     return $users;
1021 /**
1022  * Get volatile flags
1023  *
1024  * @param string $type
1025  * @param int    $changedsince default null
1026  * @return records array
1027  */
1028 function get_cache_flags($type, $changedsince=NULL) {
1029     global $DB;
1031     $params = array('type'=>$type, 'expiry'=>time());
1032     $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1033     if ($changedsince !== NULL) {
1034         $params['changedsince'] = $changedsince;
1035         $sqlwhere .= " AND timemodified > :changedsince";
1036     }
1037     $cf = array();
1039     if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1040         foreach ($flags as $flag) {
1041             $cf[$flag->name] = $flag->value;
1042         }
1043     }
1044     return $cf;
1047 /**
1048  * Get volatile flags
1049  *
1050  * @param string $type
1051  * @param string $name
1052  * @param int    $changedsince default null
1053  * @return records array
1054  */
1055 function get_cache_flag($type, $name, $changedsince=NULL) {
1056     global $DB;
1058     $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1060     $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1061     if ($changedsince !== NULL) {
1062         $params['changedsince'] = $changedsince;
1063         $sqlwhere .= " AND timemodified > :changedsince";
1064     }
1066     return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1069 /**
1070  * Set a volatile flag
1071  *
1072  * @param string $type the "type" namespace for the key
1073  * @param string $name the key to set
1074  * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1075  * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1076  * @return bool Always returns true
1077  */
1078 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1079     global $DB;
1081     $timemodified = time();
1082     if ($expiry===NULL || $expiry < $timemodified) {
1083         $expiry = $timemodified + 24 * 60 * 60;
1084     } else {
1085         $expiry = (int)$expiry;
1086     }
1088     if ($value === NULL) {
1089         unset_cache_flag($type,$name);
1090         return true;
1091     }
1093     if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potentail problem in DEBUG_DEVELOPER
1094         if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1095             return true; //no need to update; helps rcache too
1096         }
1097         $f->value        = $value;
1098         $f->expiry       = $expiry;
1099         $f->timemodified = $timemodified;
1100         $DB->update_record('cache_flags', $f);
1101     } else {
1102         $f = new object();
1103         $f->flagtype     = $type;
1104         $f->name         = $name;
1105         $f->value        = $value;
1106         $f->expiry       = $expiry;
1107         $f->timemodified = $timemodified;
1108         $DB->insert_record('cache_flags', $f);
1109     }
1110     return true;
1113 /**
1114  * Removes a single volatile flag
1115  *
1116  * @global object
1117  * @param string $type the "type" namespace for the key
1118  * @param string $name the key to set
1119  * @return bool
1120  */
1121 function unset_cache_flag($type, $name) {
1122     global $DB;
1123     $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1124     return true;
1127 /**
1128  * Garbage-collect volatile flags
1129  *
1130  * @return bool Always returns true
1131  */
1132 function gc_cache_flags() {
1133     global $DB;
1134     $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1135     return true;
1138 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1140 /**
1141  * Refresh current $USER session global variable with all their current preferences.
1142  *
1143  * @global object
1144  * @param mixed $time default null
1145  * @return void
1146  */
1147 function check_user_preferences_loaded($time = null) {
1148     global $USER, $DB;
1149     static $timenow = null; // Static cache, so we only check up-to-dateness once per request.
1151     if (!empty($USER->preference) && isset($USER->preference['_lastloaded'])) {
1152         // Already loaded. Are we up to date?
1154         if (is_null($timenow) || (!is_null($time) && $time != $timenow)) {
1155             $timenow = time();
1156             if (!get_cache_flag('userpreferenceschanged', $USER->id, $USER->preference['_lastloaded'])) {
1157                 // We are up-to-date.
1158                 return;
1159             }
1160         } else {
1161             // Already checked for up-to-date-ness.
1162             return;
1163         }
1164     }
1166     // OK, so we have to reload. Reset preference
1167     $USER->preference = array();
1169     if (!isloggedin() or isguestuser()) {
1170         // No permanent storage for not-logged-in user and guest
1172     } else if ($preferences = $DB->get_records('user_preferences', array('userid'=>$USER->id))) {
1173         foreach ($preferences as $preference) {
1174             $USER->preference[$preference->name] = $preference->value;
1175         }
1176     }
1178     $USER->preference['_lastloaded'] = $timenow;
1181 /**
1182  * Called from set/delete_user_preferences, so that the prefs can be correctly reloaded.
1183  *
1184  * @global object
1185  * @global object
1186  * @param integer $userid the user whose prefs were changed.
1187  */
1188 function mark_user_preferences_changed($userid) {
1189     global $CFG, $USER;
1190     if ($userid == $USER->id) {
1191         check_user_preferences_loaded(time());
1192     }
1193     set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1196 /**
1197  * Sets a preference for the current user
1198  *
1199  * Optionally, can set a preference for a different user object
1200  *
1201  * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
1202  *
1203  * @global object
1204  * @global object
1205  * @param string $name The key to set as preference for the specified user
1206  * @param string $value The value to set forthe $name key in the specified user's record
1207  * @param int $otheruserid A moodle user ID, default null
1208  * @return bool
1209  */
1210 function set_user_preference($name, $value, $otheruserid=NULL) {
1211     global $USER, $DB;
1213     if (empty($name)) {
1214         return false;
1215     }
1217     $nostore = false;
1218     if (empty($otheruserid)){
1219         if (!isloggedin() or isguestuser()) {
1220             $nostore = true;
1221         }
1222         $userid = $USER->id;
1223     } else {
1224         if (isguestuser($otheruserid)) {
1225             $nostore = true;
1226         }
1227         $userid = $otheruserid;
1228     }
1230     if ($nostore) {
1231         // no permanent storage for not-logged-in user and guest
1233     } else if ($preference = $DB->get_record('user_preferences', array('userid'=>$userid, 'name'=>$name))) {
1234         if ($preference->value === $value) {
1235             return true;
1236         }
1237         $DB->set_field('user_preferences', 'value', (string)$value, array('id'=>$preference->id));
1239     } else {
1240         $preference = new object();
1241         $preference->userid = $userid;
1242         $preference->name   = $name;
1243         $preference->value  = (string)$value;
1244         $DB->insert_record('user_preferences', $preference);
1245     }
1247     mark_user_preferences_changed($userid);
1248     // update value in USER session if needed
1249     if ($userid == $USER->id) {
1250         $USER->preference[$name] = (string)$value;
1251         $USER->preference['_lastloaded'] = time();
1252     }
1254     return true;
1257 /**
1258  * Sets a whole array of preferences for the current user
1259  *
1260  * @param array $prefarray An array of key/value pairs to be set
1261  * @param int $otheruserid A moodle user ID
1262  * @return bool
1263  */
1264 function set_user_preferences($prefarray, $otheruserid=NULL) {
1266     if (!is_array($prefarray) or empty($prefarray)) {
1267         return false;
1268     }
1270     foreach ($prefarray as $name => $value) {
1271         set_user_preference($name, $value, $otheruserid);
1272     }
1273     return true;
1276 /**
1277  * Unsets a preference completely by deleting it from the database
1278  *
1279  * Optionally, can set a preference for a different user id
1280  *
1281  * @global object
1282  * @param string  $name The key to unset as preference for the specified user
1283  * @param int $otheruserid A moodle user ID
1284  */
1285 function unset_user_preference($name, $otheruserid=NULL) {
1286     global $USER, $DB;
1288     if (empty($otheruserid)){
1289         $userid = $USER->id;
1290         check_user_preferences_loaded();
1291     } else {
1292         $userid = $otheruserid;
1293     }
1295     //Then from DB
1296     $DB->delete_records('user_preferences', array('userid'=>$userid, 'name'=>$name));
1298     mark_user_preferences_changed($userid);
1299     //Delete the preference from $USER if needed
1300     if ($userid == $USER->id) {
1301         unset($USER->preference[$name]);
1302         $USER->preference['_lastloaded'] = time();
1303     }
1305     return true;
1308 /**
1309  * Used to fetch user preference(s)
1310  *
1311  * If no arguments are supplied this function will return
1312  * all of the current user preferences as an array.
1313  *
1314  * If a name is specified then this function
1315  * attempts to return that particular preference value.  If
1316  * none is found, then the optional value $default is returned,
1317  * otherwise NULL.
1318  *
1319  * @global object
1320  * @global object
1321  * @param string $name Name of the key to use in finding a preference value
1322  * @param string $default Value to be returned if the $name key is not set in the user preferences
1323  * @param int $otheruserid A moodle user ID
1324  * @return string
1325  */
1326 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
1327     global $USER, $DB;
1329     if (empty($otheruserid) || (!empty($USER->id) && ($USER->id == $otheruserid))){
1330         check_user_preferences_loaded();
1332         if (empty($name)) {
1333             return $USER->preference; // All values
1334         } else if (array_key_exists($name, $USER->preference)) {
1335             return $USER->preference[$name]; // The single value
1336         } else {
1337             return $default; // Default value (or NULL)
1338         }
1340     } else {
1341         if (empty($name)) {
1342             return $DB->get_records_menu('user_preferences', array('userid'=>$otheruserid), '', 'name,value'); // All values
1343         } else if ($value = $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>$name))) {
1344             return $value; // The single value
1345         } else {
1346             return $default; // Default value (or NULL)
1347         }
1348     }
1351 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1353 /**
1354  * Given date parts in user time produce a GMT timestamp.
1355  *
1356  * @todo Finish documenting this function
1357  * @param int $year The year part to create timestamp of
1358  * @param int $month The month part to create timestamp of
1359  * @param int $day The day part to create timestamp of
1360  * @param int $hour The hour part to create timestamp of
1361  * @param int $minute The minute part to create timestamp of
1362  * @param int $second The second part to create timestamp of
1363  * @param float $timezone Timezone modifier
1364  * @param bool $applydst Toggle Daylight Saving Time, default true
1365  * @return int timestamp
1366  */
1367 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1369     $strtimezone = NULL;
1370     if (!is_numeric($timezone)) {
1371         $strtimezone = $timezone;
1372     }
1374     $timezone = get_user_timezone_offset($timezone);
1376     if (abs($timezone) > 13) {
1377         $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1378     } else {
1379         $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1380         $time = usertime($time, $timezone);
1381         if($applydst) {
1382             $time -= dst_offset_on($time, $strtimezone);
1383         }
1384     }
1386     return $time;
1390 /**
1391  * Format a date/time (seconds) as weeks, days, hours etc as needed
1392  *
1393  * Given an amount of time in seconds, returns string
1394  * formatted nicely as weeks, days, hours etc as needed
1395  *
1396  * @uses MINSECS
1397  * @uses HOURSECS
1398  * @uses DAYSECS
1399  * @uses YEARSECS
1400  * @param int $totalsecs Time in seconds
1401  * @param object $str Should be a time object
1402  * @return string A nicely formatted date/time string
1403  */
1404  function format_time($totalsecs, $str=NULL) {
1406     $totalsecs = abs($totalsecs);
1408     if (!$str) {  // Create the str structure the slow way
1409         $str->day   = get_string('day');
1410         $str->days  = get_string('days');
1411         $str->hour  = get_string('hour');
1412         $str->hours = get_string('hours');
1413         $str->min   = get_string('min');
1414         $str->mins  = get_string('mins');
1415         $str->sec   = get_string('sec');
1416         $str->secs  = get_string('secs');
1417         $str->year  = get_string('year');
1418         $str->years = get_string('years');
1419     }
1422     $years     = floor($totalsecs/YEARSECS);
1423     $remainder = $totalsecs - ($years*YEARSECS);
1424     $days      = floor($remainder/DAYSECS);
1425     $remainder = $totalsecs - ($days*DAYSECS);
1426     $hours     = floor($remainder/HOURSECS);
1427     $remainder = $remainder - ($hours*HOURSECS);
1428     $mins      = floor($remainder/MINSECS);
1429     $secs      = $remainder - ($mins*MINSECS);
1431     $ss = ($secs == 1)  ? $str->sec  : $str->secs;
1432     $sm = ($mins == 1)  ? $str->min  : $str->mins;
1433     $sh = ($hours == 1) ? $str->hour : $str->hours;
1434     $sd = ($days == 1)  ? $str->day  : $str->days;
1435     $sy = ($years == 1)  ? $str->year  : $str->years;
1437     $oyears = '';
1438     $odays = '';
1439     $ohours = '';
1440     $omins = '';
1441     $osecs = '';
1443     if ($years)  $oyears  = $years .' '. $sy;
1444     if ($days)  $odays  = $days .' '. $sd;
1445     if ($hours) $ohours = $hours .' '. $sh;
1446     if ($mins)  $omins  = $mins .' '. $sm;
1447     if ($secs)  $osecs  = $secs .' '. $ss;
1449     if ($years) return trim($oyears .' '. $odays);
1450     if ($days)  return trim($odays .' '. $ohours);
1451     if ($hours) return trim($ohours .' '. $omins);
1452     if ($mins)  return trim($omins .' '. $osecs);
1453     if ($secs)  return $osecs;
1454     return get_string('now');
1457 /**
1458  * Returns a formatted string that represents a date in user time
1459  *
1460  * Returns a formatted string that represents a date in user time
1461  * <b>WARNING: note that the format is for strftime(), not date().</b>
1462  * Because of a bug in most Windows time libraries, we can't use
1463  * the nicer %e, so we have to use %d which has leading zeroes.
1464  * A lot of the fuss in the function is just getting rid of these leading
1465  * zeroes as efficiently as possible.
1466  *
1467  * If parameter fixday = true (default), then take off leading
1468  * zero from %d, else mantain it.
1469  *
1470  * @param int $date the timestamp in UTC, as obtained from the database.
1471  * @param string $format strftime format. You should probably get this using
1472  *      get_string('strftime...', 'langconfig');
1473  * @param float $timezone by default, uses the user's time zone.
1474  * @param bool $fixday If true (default) then the leading zero from %d is removed.
1475  *      If false then the leading zero is mantained.
1476  * @return string the formatted date/time.
1477  */
1478 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1480     global $CFG;
1482     $strtimezone = NULL;
1483     if (!is_numeric($timezone)) {
1484         $strtimezone = $timezone;
1485     }
1487     if (empty($format)) {
1488         $format = get_string('strftimedaydatetime', 'langconfig');
1489     }
1491     if (!empty($CFG->nofixday)) {  // Config.php can force %d not to be fixed.
1492         $fixday = false;
1493     } else if ($fixday) {
1494         $formatnoday = str_replace('%d', 'DD', $format);
1495         $fixday = ($formatnoday != $format);
1496     }
1498     $date += dst_offset_on($date, $strtimezone);
1500     $timezone = get_user_timezone_offset($timezone);
1502     if (abs($timezone) > 13) {   /// Server time
1503         if ($fixday) {
1504             $datestring = strftime($formatnoday, $date);
1505             $daystring  = str_replace(array(' 0', ' '), '', strftime(' %d', $date));
1506             $datestring = str_replace('DD', $daystring, $datestring);
1507         } else {
1508             $datestring = strftime($format, $date);
1509         }
1510     } else {
1511         $date += (int)($timezone * 3600);
1512         if ($fixday) {
1513             $datestring = gmstrftime($formatnoday, $date);
1514             $daystring  = str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date));
1515             $datestring = str_replace('DD', $daystring, $datestring);
1516         } else {
1517             $datestring = gmstrftime($format, $date);
1518         }
1519     }
1521 /// If we are running under Windows convert from windows encoding to UTF-8
1522 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1524    if ($CFG->ostype == 'WINDOWS') {
1525        if ($localewincharset = get_string('localewincharset')) {
1526            $textlib = textlib_get_instance();
1527            $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1528        }
1529    }
1531     return $datestring;
1534 /**
1535  * Given a $time timestamp in GMT (seconds since epoch),
1536  * returns an array that represents the date in user time
1537  *
1538  * @todo Finish documenting this function
1539  * @uses HOURSECS
1540  * @param int $time Timestamp in GMT
1541  * @param float $timezone ?
1542  * @return array An array that represents the date in user time
1543  */
1544 function usergetdate($time, $timezone=99) {
1546     $strtimezone = NULL;
1547     if (!is_numeric($timezone)) {
1548         $strtimezone = $timezone;
1549     }
1551     $timezone = get_user_timezone_offset($timezone);
1553     if (abs($timezone) > 13) {    // Server time
1554         return getdate($time);
1555     }
1557     // There is no gmgetdate so we use gmdate instead
1558     $time += dst_offset_on($time, $strtimezone);
1559     $time += intval((float)$timezone * HOURSECS);
1561     $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
1563     //be careful to ensure the returned array matches that produced by getdate() above
1564     list(
1565         $getdate['month'],
1566         $getdate['weekday'],
1567         $getdate['yday'],
1568         $getdate['year'],
1569         $getdate['mon'],
1570         $getdate['wday'],
1571         $getdate['mday'],
1572         $getdate['hours'],
1573         $getdate['minutes'],
1574         $getdate['seconds']
1575     ) = explode('_', $datestring);
1577     return $getdate;
1580 /**
1581  * Given a GMT timestamp (seconds since epoch), offsets it by
1582  * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1583  *
1584  * @uses HOURSECS
1585  * @param  int $date Timestamp in GMT
1586  * @param float $timezone
1587  * @return int
1588  */
1589 function usertime($date, $timezone=99) {
1591     $timezone = get_user_timezone_offset($timezone);
1593     if (abs($timezone) > 13) {
1594         return $date;
1595     }
1596     return $date - (int)($timezone * HOURSECS);
1599 /**
1600  * Given a time, return the GMT timestamp of the most recent midnight
1601  * for the current user.
1602  *
1603  * @param int $date Timestamp in GMT
1604  * @param float $timezone Defaults to user's timezone
1605  * @return int Returns a GMT timestamp
1606  */
1607 function usergetmidnight($date, $timezone=99) {
1609     $userdate = usergetdate($date, $timezone);
1611     // Time of midnight of this user's day, in GMT
1612     return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1616 /**
1617  * Returns a string that prints the user's timezone
1618  *
1619  * @param float $timezone The user's timezone
1620  * @return string
1621  */
1622 function usertimezone($timezone=99) {
1624     $tz = get_user_timezone($timezone);
1626     if (!is_float($tz)) {
1627         return $tz;
1628     }
1630     if(abs($tz) > 13) { // Server time
1631         return get_string('serverlocaltime');
1632     }
1634     if($tz == intval($tz)) {
1635         // Don't show .0 for whole hours
1636         $tz = intval($tz);
1637     }
1639     if($tz == 0) {
1640         return 'UTC';
1641     }
1642     else if($tz > 0) {
1643         return 'UTC+'.$tz;
1644     }
1645     else {
1646         return 'UTC'.$tz;
1647     }
1651 /**
1652  * Returns a float which represents the user's timezone difference from GMT in hours
1653  * Checks various settings and picks the most dominant of those which have a value
1654  *
1655  * @global object
1656  * @global object
1657  * @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
1658  * @return float
1659  */
1660 function get_user_timezone_offset($tz = 99) {
1662     global $USER, $CFG;
1664     $tz = get_user_timezone($tz);
1666     if (is_float($tz)) {
1667         return $tz;
1668     } else {
1669         $tzrecord = get_timezone_record($tz);
1670         if (empty($tzrecord)) {
1671             return 99.0;
1672         }
1673         return (float)$tzrecord->gmtoff / HOURMINS;
1674     }
1677 /**
1678  * Returns an int which represents the systems's timezone difference from GMT in seconds
1679  *
1680  * @global object
1681  * @param mixed $tz timezone
1682  * @return int if found, false is timezone 99 or error
1683  */
1684 function get_timezone_offset($tz) {
1685     global $CFG;
1687     if ($tz == 99) {
1688         return false;
1689     }
1691     if (is_numeric($tz)) {
1692         return intval($tz * 60*60);
1693     }
1695     if (!$tzrecord = get_timezone_record($tz)) {
1696         return false;
1697     }
1698     return intval($tzrecord->gmtoff * 60);
1701 /**
1702  * Returns a float or a string which denotes the user's timezone
1703  * 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)
1704  * means that for this timezone there are also DST rules to be taken into account
1705  * Checks various settings and picks the most dominant of those which have a value
1706  *
1707  * @global object
1708  * @global object
1709  * @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
1710  * @return mixed
1711  */
1712 function get_user_timezone($tz = 99) {
1713     global $USER, $CFG;
1715     $timezones = array(
1716         $tz,
1717         isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1718         isset($USER->timezone) ? $USER->timezone : 99,
1719         isset($CFG->timezone) ? $CFG->timezone : 99,
1720         );
1722     $tz = 99;
1724     while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
1725         $tz = $next['value'];
1726     }
1728     return is_numeric($tz) ? (float) $tz : $tz;
1731 /**
1732  * Returns cached timezone record for given $timezonename
1733  *
1734  * @global object
1735  * @global object
1736  * @param string $timezonename
1737  * @return mixed timezonerecord object or false
1738  */
1739 function get_timezone_record($timezonename) {
1740     global $CFG, $DB;
1741     static $cache = NULL;
1743     if ($cache === NULL) {
1744         $cache = array();
1745     }
1747     if (isset($cache[$timezonename])) {
1748         return $cache[$timezonename];
1749     }
1751     return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
1752                                                         WHERE name = ? ORDER BY year DESC', array($timezonename), true);
1755 /**
1756  * Build and store the users Daylight Saving Time (DST) table
1757  *
1758  * @global object
1759  * @global object
1760  * @global object
1761  * @param mixed $from_year Start year for the table, defaults to 1971
1762  * @param mixed $to_year End year for the table, defaults to 2035
1763  * @param mixed $strtimezone
1764  * @return bool
1765  */
1766 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
1767     global $CFG, $SESSION, $DB;
1769     $usertz = get_user_timezone($strtimezone);
1771     if (is_float($usertz)) {
1772         // Trivial timezone, no DST
1773         return false;
1774     }
1776     if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1777         // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1778         unset($SESSION->dst_offsets);
1779         unset($SESSION->dst_range);
1780     }
1782     if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1783         // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1784         // This will be the return path most of the time, pretty light computationally
1785         return true;
1786     }
1788     // Reaching here means we either need to extend our table or create it from scratch
1790     // Remember which TZ we calculated these changes for
1791     $SESSION->dst_offsettz = $usertz;
1793     if(empty($SESSION->dst_offsets)) {
1794         // If we 're creating from scratch, put the two guard elements in there
1795         $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1796     }
1797     if(empty($SESSION->dst_range)) {
1798         // If creating from scratch
1799         $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1800         $to   = min((empty($to_year)   ? intval(date('Y')) + 3 : $to_year),   2035);
1802         // Fill in the array with the extra years we need to process
1803         $yearstoprocess = array();
1804         for($i = $from; $i <= $to; ++$i) {
1805             $yearstoprocess[] = $i;
1806         }
1808         // Take note of which years we have processed for future calls
1809         $SESSION->dst_range = array($from, $to);
1810     }
1811     else {
1812         // If needing to extend the table, do the same
1813         $yearstoprocess = array();
1815         $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1816         $to   = min((empty($to_year)   ? $SESSION->dst_range[1] : $to_year),   2035);
1818         if($from < $SESSION->dst_range[0]) {
1819             // Take note of which years we need to process and then note that we have processed them for future calls
1820             for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
1821                 $yearstoprocess[] = $i;
1822             }
1823             $SESSION->dst_range[0] = $from;
1824         }
1825         if($to > $SESSION->dst_range[1]) {
1826             // Take note of which years we need to process and then note that we have processed them for future calls
1827             for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
1828                 $yearstoprocess[] = $i;
1829             }
1830             $SESSION->dst_range[1] = $to;
1831         }
1832     }
1834     if(empty($yearstoprocess)) {
1835         // This means that there was a call requesting a SMALLER range than we have already calculated
1836         return true;
1837     }
1839     // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1840     // Also, the array is sorted in descending timestamp order!
1842     // Get DB data
1844     static $presets_cache = array();
1845     if (!isset($presets_cache[$usertz])) {
1846         $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');
1847     }
1848     if(empty($presets_cache[$usertz])) {
1849         return false;
1850     }
1852     // Remove ending guard (first element of the array)
1853     reset($SESSION->dst_offsets);
1854     unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
1856     // Add all required change timestamps
1857     foreach($yearstoprocess as $y) {
1858         // Find the record which is in effect for the year $y
1859         foreach($presets_cache[$usertz] as $year => $preset) {
1860             if($year <= $y) {
1861                 break;
1862             }
1863         }
1865         $changes = dst_changes_for_year($y, $preset);
1867         if($changes === NULL) {
1868             continue;
1869         }
1870         if($changes['dst'] != 0) {
1871             $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
1872         }
1873         if($changes['std'] != 0) {
1874             $SESSION->dst_offsets[$changes['std']] = 0;
1875         }
1876     }
1878     // Put in a guard element at the top
1879     $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1880     $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1882     // Sort again
1883     krsort($SESSION->dst_offsets);
1885     return true;
1888 /**
1889  * Calculates the required DST change and returns a Timestamp Array
1890  *
1891  * @uses HOURSECS
1892  * @uses MINSECS
1893  * @param mixed $year Int or String Year to focus on
1894  * @param object $timezone Instatiated Timezone object
1895  * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
1896  */
1897 function dst_changes_for_year($year, $timezone) {
1899     if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1900         return NULL;
1901     }
1903     $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1904     $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1906     list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1907     list($std_hour, $std_min) = explode(':', $timezone->std_time);
1909     $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1910     $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
1912     // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1913     // This has the advantage of being able to have negative values for hour, i.e. for timezones
1914     // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1916     $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1917     $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
1919     return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1922 /**
1923  * Calculates the Daylight Saving Offest for a given date/time (timestamp)
1924  *
1925  * @global object
1926  * @param int $time must NOT be compensated at all, it has to be a pure timestamp
1927  * @return int
1928  */
1929 function dst_offset_on($time, $strtimezone = NULL) {
1930     global $SESSION;
1932     if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
1933         return 0;
1934     }
1936     reset($SESSION->dst_offsets);
1937     while(list($from, $offset) = each($SESSION->dst_offsets)) {
1938         if($from <= $time) {
1939             break;
1940         }
1941     }
1943     // This is the normal return path
1944     if($offset !== NULL) {
1945         return $offset;
1946     }
1948     // Reaching this point means we haven't calculated far enough, do it now:
1949     // Calculate extra DST changes if needed and recurse. The recursion always
1950     // moves toward the stopping condition, so will always end.
1952     if($from == 0) {
1953         // We need a year smaller than $SESSION->dst_range[0]
1954         if($SESSION->dst_range[0] == 1971) {
1955             return 0;
1956         }
1957         calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
1958         return dst_offset_on($time, $strtimezone);
1959     }
1960     else {
1961         // We need a year larger than $SESSION->dst_range[1]
1962         if($SESSION->dst_range[1] == 2035) {
1963             return 0;
1964         }
1965         calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
1966         return dst_offset_on($time, $strtimezone);
1967     }
1970 /**
1971  * ?
1972  *
1973  * @todo Document what this function does
1974  * @param int $startday
1975  * @param int $weekday
1976  * @param int $month
1977  * @param int $year
1978  * @return int
1979  */
1980 function find_day_in_month($startday, $weekday, $month, $year) {
1982     $daysinmonth = days_in_month($month, $year);
1984     if($weekday == -1) {
1985         // Don't care about weekday, so return:
1986         //    abs($startday) if $startday != -1
1987         //    $daysinmonth otherwise
1988         return ($startday == -1) ? $daysinmonth : abs($startday);
1989     }
1991     // From now on we 're looking for a specific weekday
1993     // Give "end of month" its actual value, since we know it
1994     if($startday == -1) {
1995         $startday = -1 * $daysinmonth;
1996     }
1998     // Starting from day $startday, the sign is the direction
2000     if($startday < 1) {
2002         $startday = abs($startday);
2003         $lastmonthweekday  = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2005         // This is the last such weekday of the month
2006         $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2007         if($lastinmonth > $daysinmonth) {
2008             $lastinmonth -= 7;
2009         }
2011         // Find the first such weekday <= $startday
2012         while($lastinmonth > $startday) {
2013             $lastinmonth -= 7;
2014         }
2016         return $lastinmonth;
2018     }
2019     else {
2021         $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
2023         $diff = $weekday - $indexweekday;
2024         if($diff < 0) {
2025             $diff += 7;
2026         }
2028         // This is the first such weekday of the month equal to or after $startday
2029         $firstfromindex = $startday + $diff;
2031         return $firstfromindex;
2033     }
2036 /**
2037  * Calculate the number of days in a given month
2038  *
2039  * @param int $month The month whose day count is sought
2040  * @param int $year The year of the month whose day count is sought
2041  * @return int
2042  */
2043 function days_in_month($month, $year) {
2044    return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
2047 /**
2048  * Calculate the position in the week of a specific calendar day
2049  *
2050  * @param int $day The day of the date whose position in the week is sought
2051  * @param int $month The month of the date whose position in the week is sought
2052  * @param int $year The year of the date whose position in the week is sought
2053  * @return int
2054  */
2055 function dayofweek($day, $month, $year) {
2056     // I wonder if this is any different from
2057     // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2058     return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
2061 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2063 /**
2064  * Returns full login url.
2065  *
2066  * @global object
2067  * @param bool $loginguest add login guest param, return false
2068  * @return string login url
2069  */
2070 function get_login_url($loginguest=false) {
2071     global $CFG;
2073     if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
2074         $loginguest = $loginguest ? '?loginguest=true' : '';
2075         $url = "$CFG->wwwroot/login/index.php$loginguest";
2077     } else {
2078         $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2079         $url = "$wwwroot/login/index.php";
2080     }
2082     return $url;
2085 /**
2086  * This function checks that the current user is logged in and has the
2087  * required privileges
2088  *
2089  * This function checks that the current user is logged in, and optionally
2090  * whether they are allowed to be in a particular course and view a particular
2091  * course module.
2092  * If they are not logged in, then it redirects them to the site login unless
2093  * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2094  * case they are automatically logged in as guests.
2095  * If $courseid is given and the user is not enrolled in that course then the
2096  * user is redirected to the course enrolment page.
2097  * If $cm is given and the coursemodule is hidden and the user is not a teacher
2098  * in the course then the user is redirected to the course home page.
2099  *
2100  * When $cm parameter specified, this function sets page layout to 'module'.
2101  * You need to change it manually later if some other layout needed. 
2102  *
2103  * @global object
2104  * @global object
2105  * @global object
2106  * @global object
2107  * @global string
2108  * @global object
2109  * @global object
2110  * @global object
2111  * @uses SITEID Define
2112  * @param mixed $courseorid id of the course or course object
2113  * @param bool $autologinguest default true
2114  * @param object $cm course module object
2115  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2116  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2117  *             in order to keep redirects working properly. MDL-14495
2118  * @return mixed Void, exit, and die depending on path
2119  */
2120 function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsurltome=true) {
2121     global $CFG, $SESSION, $USER, $COURSE, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2123 /// setup global $COURSE, themes, language and locale
2124     if (!empty($courseorid)) {
2125         if (is_object($courseorid)) {
2126             $course = $courseorid;
2127         } else if ($courseorid == SITEID) {
2128             $course = clone($SITE);
2129         } else {
2130             $course = $DB->get_record('course', array('id' => $courseorid));
2131             if (!$course) {
2132                 throw new moodle_exception('invalidcourseid');
2133             }
2134         }
2135         if ($cm) {
2136             $PAGE->set_cm($cm, $course); // set's up global $COURSE
2137             $PAGE->set_pagelayout('incourse');
2138         } else {
2139             $PAGE->set_course($course); // set's up global $COURSE
2140         }
2141     } else {
2142         // do not touch global $COURSE via $PAGE->set_course() !!
2143     }
2145 /// If the user is not even logged in yet then make sure they are
2146     if (!isloggedin()) {
2147         //NOTE: $USER->site check was obsoleted by session test cookie,
2148         //      $USER->confirmed test is in login/index.php
2149         if ($setwantsurltome) {
2150             $SESSION->wantsurl = $FULLME;
2151         }
2152         if (!empty($_SERVER['HTTP_REFERER'])) {
2153             $SESSION->fromurl  = $_SERVER['HTTP_REFERER'];
2154         }
2155         if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
2156             $loginguest = true;
2157         } else {
2158             $loginguest = false;
2159         }
2160         redirect(get_login_url($loginguest));
2161         exit; // never reached
2162     }
2164 /// loginas as redirection if needed
2165     if ($COURSE->id != SITEID and session_is_loggedinas()) {
2166         if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2167             if ($USER->loginascontext->instanceid != $COURSE->id) {
2168                 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2169             }
2170         }
2171     }
2173 /// check whether the user should be changing password (but only if it is REALLY them)
2174     if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2175         $userauth = get_auth_plugin($USER->auth);
2176         if ($userauth->can_change_password()) {
2177             $SESSION->wantsurl = $FULLME;
2178             if ($changeurl = $userauth->change_password_url()) {
2179                 //use plugin custom url
2180                 redirect($changeurl);
2181             } else {
2182                 //use moodle internal method
2183                 if (empty($CFG->loginhttps)) {
2184                     redirect($CFG->wwwroot .'/login/change_password.php');
2185                 } else {
2186                     $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2187                     redirect($wwwroot .'/login/change_password.php');
2188                 }
2189             }
2190         } else {
2191             print_error('nopasswordchangeforced', 'auth');
2192         }
2193     }
2195 /// Check that the user account is properly set up
2196     if (user_not_fully_set_up($USER)) {
2197         $SESSION->wantsurl = $FULLME;
2198         redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2199     }
2201 /// Make sure the USER has a sesskey set up.  Used for checking script parameters.
2202     sesskey();
2204     // Check that the user has agreed to a site policy if there is one
2205     if (!empty($CFG->sitepolicy)) {
2206         if (!$USER->policyagreed) {
2207             $SESSION->wantsurl = $FULLME;
2208             redirect($CFG->wwwroot .'/user/policy.php');
2209         }
2210     }
2212     // Fetch the system context, we are going to use it a lot.
2213     $sysctx = get_context_instance(CONTEXT_SYSTEM);
2215 /// If the site is currently under maintenance, then print a message
2216     if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2217         print_maintenance_message();
2218     }
2220 /// groupmembersonly access control
2221     if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2222         if (isguestuser() or !groups_has_membership($cm)) {
2223             print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
2224         }
2225     }
2227     // Fetch the course context, and prefetch its child contexts
2228     if (!isset($COURSE->context)) {
2229         if ( ! $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id) ) {
2230             print_error('nocontext');
2231         }
2232     }
2233     if (!empty($cm) && !isset($cm->context)) {
2234         if ( ! $cm->context = get_context_instance(CONTEXT_MODULE, $cm->id) ) {
2235             print_error('nocontext');
2236         }
2237     }
2239     // Conditional activity access control
2240     if(!empty($CFG->enableavailability) and $cm) {
2241         // We cache conditional access in session
2242         if(!isset($SESSION->conditionaccessok)) {
2243             $SESSION->conditionaccessok = array();
2244         }
2245         // If you have been allowed into the module once then you are allowed
2246         // in for rest of session, no need to do conditional checks
2247         if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
2248             // Get condition info (does a query for the availability table)
2249             require_once($CFG->libdir.'/conditionlib.php');
2250             $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
2251             // Check condition for user (this will do a query if the availability
2252             // information depends on grade or completion information)
2253             if ($ci->is_available($junk) ||
2254                 has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
2255                 $SESSION->conditionaccessok[$cm->id] = true;
2256             } else {
2257                 print_error('activityiscurrentlyhidden');
2258             }
2259         }
2260     }
2262     if ($COURSE->id == SITEID) {
2263         /// Eliminate hidden site activities straight away
2264         if (!empty($cm) && !$cm->visible
2265             && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
2266             redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2267         }
2268         user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2269         return;
2271     } else {
2273         /// Check if the user can be in a particular course
2274         if (empty($USER->access['rsw'][$COURSE->context->path])) {
2275             //
2276             // MDL-13900 - If the course or the parent category are hidden
2277             // and the user hasn't the 'course:viewhiddencourses' capability, prevent access
2278             //
2279             if ( !($COURSE->visible && course_parent_visible($COURSE)) &&
2280                    !has_capability('moodle/course:viewhiddencourses', $COURSE->context)) {
2281                 echo $OUTPUT->header();
2282                 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2283             }
2284         }
2286     /// Non-guests who don't currently have access, check if they can be allowed in as a guest
2288         if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) {
2289             if ($COURSE->guest == 1) {
2290                  // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
2291                  $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access);
2292             }
2293         }
2295     /// If the user is a guest then treat them according to the course policy about guests
2297         if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) {
2298             if (has_capability('moodle/site:doanything', $sysctx)) {
2299                 // administrators must be able to access any course - even if somebody gives them guest access
2300                 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2301                 return;
2302             }
2304             switch ($COURSE->guest) {    /// Check course policy about guest access
2306                 case 1:    /// Guests always allowed
2307                     if (!has_capability('moodle/course:view', $COURSE->context)) {    // Prohibited by capability
2308                         echo $OUTPUT->header();
2309                         notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url());
2310                     }
2311                     if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
2312                         redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
2313                                  get_string('activityiscurrentlyhidden'));
2314                     }
2316                     user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2317                     return;   // User is allowed to see this course
2319                     break;
2321                 case 2:    /// Guests allowed with key
2322                     if (!empty($USER->enrolkey[$COURSE->id])) {   // Set by enrol/manual/enrol.php
2323                         user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2324                         return true;
2325                     }
2326                     //  otherwise drop through to logic below (--> enrol.php)
2327                     break;
2329                 default:    /// Guests not allowed
2330                     $strloggedinasguest = get_string('loggedinasguest');
2331                     $PAGE->navbar->add($strloggedinasguest);
2332                     echo $OUTPUT->header();
2333                     if (empty($USER->access['rsw'][$COURSE->context->path])) {  // Normal guest
2334                         notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url());
2335                     } else {
2336                         echo $OUTPUT->notification(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
2337                         echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
2338                         echo $OUTPUT->footer();
2339                         exit;
2340                     }
2341                     break;
2342             }
2344     /// For non-guests, check if they have course view access
2346         } else if (has_capability('moodle/course:view', $COURSE->context)) {
2347             if (session_is_loggedinas()) {   // Make sure the REAL person can also access this course
2348                 $realuser = session_get_realuser();
2349                 if (!has_capability('moodle/course:view', $COURSE->context, $realuser->id)) {
2350                     echo $OUTPUT->header();
2351                     notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2352                 }
2353             }
2355         /// Make sure they can read this activity too, if specified
2357             if (!empty($cm) && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
2358                 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
2359             }
2360             user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2361             return;   // User is allowed to see this course
2363         }
2366     /// Currently not enrolled in the course, so see if they want to enrol
2367         $SESSION->wantsurl = $FULLME;
2368         redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
2369         die;
2370     }
2374 /**
2375  * This function just makes sure a user is logged out.
2376  *
2377  * @global object
2378  */
2379 function require_logout() {
2380     global $USER;
2382     if (isloggedin()) {
2383         add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2385         $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2386         foreach($authsequence as $authname) {
2387             $authplugin = get_auth_plugin($authname);
2388             $authplugin->prelogout_hook();
2389         }
2390     }
2392     session_get_instance()->terminate_current();
2395 /**
2396  * Weaker version of require_login()
2397  *
2398  * This is a weaker version of {@link require_login()} which only requires login
2399  * when called from within a course rather than the site page, unless
2400  * the forcelogin option is turned on.
2401  * @see require_login()
2402  *
2403  * @global object
2404  * @param mixed $courseorid The course object or id in question
2405  * @param bool $autologinguest Allow autologin guests if that is wanted
2406  * @param object $cm Course activity module if known
2407  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2408  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2409  *             in order to keep redirects working properly. MDL-14495
2410  */
2411 function require_course_login($courseorid, $autologinguest=true, $cm=null, $setwantsurltome=true) {
2412     global $CFG, $PAGE, $SITE;
2413     if (!empty($CFG->forcelogin)) {
2414         // login required for both SITE and courses
2415         require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2417     } else if (!empty($cm) and !$cm->visible) {
2418         // always login for hidden activities
2419         require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2421     } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2422           or (!is_object($courseorid) and $courseorid == SITEID)) {
2423               //login for SITE not required
2424         if ($cm and empty($cm->visible)) {
2425             // hidden activities are not accessible without login
2426             require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2427         } else if ($cm and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
2428             // not-logged-in users do not have any group membership
2429             require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2430         } else {
2431             // We still need to instatiate PAGE vars properly so that things
2432             // that rely on it like navigation function correctly.
2433             if (!empty($courseorid)) {
2434                 if (is_object($courseorid)) {
2435                     $course = $courseorid;
2436                 } else {
2437                     $course = clone($SITE);
2438                 }
2439                 if ($cm) {
2440                     $PAGE->set_cm($cm, $course);
2441                     $PAGE->set_pagelayout('incourse');
2442                 } else {
2443                     $PAGE->set_course($course);
2444                 }
2445             } else {
2446                 // If $PAGE->course, and hence $PAGE->context, have not already been set
2447                 // up properly, set them up now.
2448                 $PAGE->set_course($PAGE->course);
2449             }
2450             //TODO: verify conditional activities here
2451             user_accesstime_log(SITEID);
2452             return;
2453         }
2455     } else {
2456         // course login always required
2457         require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2458     }
2461 /**
2462  * Require key login. Function terminates with error if key not found or incorrect.
2463  *
2464  * @global object
2465  * @global object
2466  * @global object
2467  * @global object
2468  * @uses NO_MOODLE_COOKIES
2469  * @uses PARAM_ALPHANUM
2470  * @param string $script unique script identifier
2471  * @param int $instance optional instance id
2472  * @return int Instance ID
2473  */
2474 function require_user_key_login($script, $instance=null) {
2475     global $USER, $SESSION, $CFG, $DB;
2477     if (!NO_MOODLE_COOKIES) {
2478         print_error('sessioncookiesdisable');
2479     }
2481 /// extra safety
2482     @session_write_close();
2484     $keyvalue = required_param('key', PARAM_ALPHANUM);
2486     if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2487         print_error('invalidkey');
2488     }
2490     if (!empty($key->validuntil) and $key->validuntil < time()) {
2491         print_error('expiredkey');
2492     }
2494     if ($key->iprestriction) {
2495         $remoteaddr = getremoteaddr();
2496         if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2497             print_error('ipmismatch');
2498         }
2499     }
2501     if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2502         print_error('invaliduserid');
2503     }
2505 /// emulate normal session
2506     session_set_user($user);
2508 /// note we are not using normal login
2509     if (!defined('USER_KEY_LOGIN')) {
2510         define('USER_KEY_LOGIN', true);
2511     }
2513 /// return isntance id - it might be empty
2514     return $key->instance;
2517 /**
2518  * Creates a new private user access key.
2519  *
2520  * @global object
2521  * @param string $script unique target identifier
2522  * @param int $userid
2523  * @param int $instance optional instance id
2524  * @param string $iprestriction optional ip restricted access
2525  * @param timestamp $validuntil key valid only until given data
2526  * @return string access key value
2527  */
2528 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2529     global $DB;
2531     $key = new object();
2532     $key->script        = $script;
2533     $key->userid        = $userid;
2534     $key->instance      = $instance;
2535     $key->iprestriction = $iprestriction;
2536     $key->validuntil    = $validuntil;
2537     $key->timecreated   = time();
2539     $key->value         = md5($userid.'_'.time().random_string(40)); // something long and unique
2540     while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
2541         // must be unique
2542         $key->value     = md5($userid.'_'.time().random_string(40));
2543     }
2544     $DB->insert_record('user_private_key', $key);
2545     return $key->value;
2548 /**
2549  * Modify the user table by setting the currently logged in user's
2550  * last login to now.
2551  *
2552  * @global object
2553  * @global object
2554  * @return bool Always returns true
2555  */
2556 function update_user_login_times() {
2557     global $USER, $DB;
2559     $user = new object();
2560     $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2561     $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2563     $user->id = $USER->id;
2565     $DB->update_record('user', $user);
2566     return true;
2569 /**
2570  * Determines if a user has completed setting up their account.
2571  *
2572  * @param user $user A {@link $USER} object to test for the existance of a valid name and email
2573  * @return bool
2574  */
2575 function user_not_fully_set_up($user) {
2576     return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
2579 /**
2580  * Check whether the user has exceeded the bounce threshold
2581  *
2582  * @global object
2583  * @global object
2584  * @param user $user A {@link $USER} object
2585  * @return bool true=>User has exceeded bounce threshold
2586  */
2587 function over_bounce_threshold($user) {
2588     global $CFG, $DB;
2590     if (empty($CFG->handlebounces)) {
2591         return false;
2592     }
2594     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2595         return false;
2596     }
2598     // set sensible defaults
2599     if (empty($CFG->minbounces)) {
2600         $CFG->minbounces = 10;
2601     }
2602     if (empty($CFG->bounceratio)) {
2603         $CFG->bounceratio = .20;
2604     }
2605     $bouncecount = 0;
2606     $sendcount = 0;
2607     if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2608         $bouncecount = $bounce->value;
2609     }
2610     if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2611         $sendcount = $send->value;
2612     }
2613     return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2616 /**
2617  * Used to increment or reset email sent count
2618  *
2619  * @global object
2620  * @param user $user object containing an id
2621  * @param bool $reset will reset the count to 0
2622  * @return void
2623  */
2624 function set_send_count($user,$reset=false) {
2625     global $DB;
2627     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2628         return;
2629     }
2631     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2632         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2633         $DB->update_record('user_preferences', $pref);
2634     }
2635     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2636         // make a new one
2637         $pref = new object();
2638         $pref->name   = 'email_send_count';
2639         $pref->value  = 1;
2640         $pref->userid = $user->id;
2641         $DB->insert_record('user_preferences', $pref, false);
2642     }
2645 /**
2646  * Increment or reset user's email bounce count
2647  *
2648  * @global object
2649  * @param user $user object containing an id
2650  * @param bool $reset will reset the count to 0
2651  */
2652 function set_bounce_count($user,$reset=false) {
2653     global $DB;
2655     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2656         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2657         $DB->update_record('user_preferences', $pref);
2658     }
2659     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2660         // make a new one
2661         $pref = new object();
2662         $pref->name   = 'email_bounce_count';
2663         $pref->value  = 1;
2664         $pref->userid = $user->id;
2665         $DB->insert_record('user_preferences', $pref, false);
2666     }
2669 /**
2670  * Keeps track of login attempts
2671  *
2672  * @global object
2673  */
2674 function update_login_count() {
2675     global $SESSION;
2677     $max_logins = 10;
2679     if (empty($SESSION->logincount)) {
2680         $SESSION->logincount = 1;
2681     } else {
2682         $SESSION->logincount++;
2683     }
2685     if ($SESSION->logincount > $max_logins) {
2686         unset($SESSION->wantsurl);
2687         print_error('errortoomanylogins');
2688     }
2691 /**
2692  * Resets login attempts
2693  *
2694  * @global object
2695  */
2696 function reset_login_count() {
2697     global $SESSION;
2699     $SESSION->logincount = 0;
2702 /**
2703  * Sync all meta courses
2704  * Goes through all enrolment records for the courses inside all metacourses and syncs with them.
2705  * @see sync_metacourse()
2706  *
2707  * @global object
2708  */
2709 function sync_metacourses() {
2710     global $DB;
2712     if (!$courses = $DB->get_records('course', array('metacourse'=>1))) {
2713         return;
2714     }
2716     foreach ($courses as $course) {
2717         sync_metacourse($course);
2718     }
2721 /**
2722  * Returns reference to full info about modules in course (including visibility).
2723  * Cached and as fast as possible (0 or 1 db query).
2724  *
2725  * @global object
2726  * @global object
2727  * @global object
2728  * @uses CONTEXT_MODULE
2729  * @uses MAX_MODINFO_CACHE_SIZE
2730  * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
2731  * @param int $userid Defaults to current user id
2732  * @return mixed courseinfo object or nothing if resetting
2733  */
2734 function &get_fast_modinfo(&$course, $userid=0) {
2735     global $CFG, $USER, $DB;
2736     require_once($CFG->dirroot.'/course/lib.php');
2738     if (!empty($CFG->enableavailability)) {
2739         require_once($CFG->libdir.'/conditionlib.php');
2740     }
2742     static $cache = array();
2744     if ($course === 'reset') {
2745         $cache = array();
2746         $nothing = null;
2747         return $nothing; // we must return some reference
2748     }
2750     if (empty($userid)) {
2751         $userid = $USER->id;
2752     }
2754     if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
2755         return $cache[$course->id];
2756     }
2758     if (empty($course->modinfo)) {
2759         // no modinfo yet - load it
2760         rebuild_course_cache($course->id);
2761         $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2762     }
2764     $modinfo = new object();
2765     $modinfo->courseid  = $course->id;
2766     $modinfo->userid    = $userid;
2767     $modinfo->sections  = array();
2768     $modinfo->cms       = array();
2769     $modinfo->instances = array();
2770     $modinfo->groups    = null; // loaded only when really needed - the only one db query
2772     $info = unserialize($course->modinfo);
2773     if (!is_array($info)) {
2774         // hmm, something is wrong - lets try to fix it
2775         rebuild_course_cache($course->id);
2776         $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2777         $info = unserialize($course->modinfo);
2778         if (!is_array($info)) {
2779             return $modinfo;
2780         }
2781     }
2783     if ($info) {
2784         // detect if upgrade required
2785         $first = reset($info);
2786         if (!isset($first->id)) {
2787             rebuild_course_cache($course->id);
2788             $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2789             $info = unserialize($course->modinfo);
2790             if (!is_array($info)) {
2791                 return $modinfo;
2792             }
2793         }
2794     }
2796     $modlurals = array();
2798     // If we haven't already preloaded contexts for the course, do it now
2799     preload_course_contexts($course->id);
2801     foreach ($info as $mod) {
2802         if (empty($mod->name)) {
2803             // something is wrong here
2804             continue;
2805         }
2806         // reconstruct minimalistic $cm
2807         $cm = new object();
2808         $cm->id               = $mod->cm;
2809         $cm->instance         = $mod->id;
2810         $cm->course           = $course->id;
2811         $cm->modname          = $mod->mod;
2812         $cm->name             = $mod->name;
2813         $cm->visible          = $mod->visible;
2814         $cm->sectionnum       = $mod->section;
2815         $cm->groupmode        = $mod->groupmode;
2816         $cm->groupingid       = $mod->groupingid;
2817         $cm->groupmembersonly = $mod->groupmembersonly;
2818         $cm->indent           = $mod->indent;
2819         $cm->completion       = $mod->completion;
2820         $cm->extra            = isset($mod->extra) ? $mod->extra : '';
2821         $cm->icon             = isset($mod->icon) ? $mod->icon : '';
2822         $cm->iconcomponent    = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
2823         $cm->uservisible      = true;
2824         if(!empty($CFG->enableavailability)) {
2825             // We must have completion information from modinfo. If it's not
2826             // there, cache needs rebuilding
2827             if(!isset($mod->availablefrom)) {
2828                 debugging('enableavailability option was changed; rebuilding '.
2829                     'cache for course '.$course->id);
2830                 rebuild_course_cache($course->id,true);
2831                 // Re-enter this routine to do it all properly
2832                 return get_fast_modinfo($course,$userid);
2833             }
2834             $cm->availablefrom    = $mod->availablefrom;
2835             $cm->availableuntil   = $mod->availableuntil;
2836             $cm->showavailability = $mod->showavailability;
2837             $cm->conditionscompletion = $mod->conditionscompletion;
2838             $cm->conditionsgrade  = $mod->conditionsgrade;
2839         }
2841         // preload long names plurals and also check module is installed properly
2842         if (!isset($modlurals[$cm->modname])) {
2843             if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
2844                 continue;
2845             }
2846             $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
2847         }
2848         $cm->modplural = $modlurals[$cm->modname];
2849         $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id);
2851         if(!empty($CFG->enableavailability)) {
2852             // Unfortunately the next call really wants to call
2853             // get_fast_modinfo, but that would be recursive, so we fake up a
2854             // modinfo for it already
2855             if(empty($minimalmodinfo)) {
2856                 $minimalmodinfo=new stdClass();
2857                 $minimalmodinfo->cms=array();
2858                 foreach($info as $mod) {
2859                     $minimalcm = new stdClass();
2860                     $minimalcm->id = $mod->cm;
2861                     $minimalcm->name = $mod->name;
2862                     $minimalmodinfo->cms[$minimalcm->id]=$minimalcm;
2863                 }
2864             }
2866             // Get availability information
2867             $ci = new condition_info($cm);
2868             $cm->available=$ci->is_available($cm->availableinfo, true, $userid, $minimalmodinfo);
2869         } else {
2870             $cm->available=true;
2871         }
2872         if ((!$cm->visible or !$cm->available) and !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
2873             $cm->uservisible = false;
2875         } else if (!empty($CFG->enablegroupings) and !empty($cm->groupmembersonly)
2876                 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
2877             if (is_null($modinfo->groups)) {
2878                 $modinfo->groups = groups_get_user_groups($course->id, $userid);
2879             }
2880             if (empty($modinfo->groups[$cm->groupingid])) {
2881                 $cm->uservisible = false;
2882             }
2883         }
2885         if (!isset($modinfo->instances[$cm->modname])) {
2886             $modinfo->instances[$cm->modname] = array();
2887         }
2888         $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
2889         $modinfo->cms[$cm->id] =& $cm;
2891         // reconstruct sections
2892         if (!isset($modinfo->sections[$cm->sectionnum])) {
2893             $modinfo->sections[$cm->sectionnum] = array();
2894         }
2895         $modinfo->sections[$cm->sectionnum][] = $cm->id;
2897         unset($cm);
2898     }
2900     unset($cache[$course->id]); // prevent potential reference problems when switching users
2901     $cache[$course->id] = $modinfo;
2903     // Ensure cache does not use too much RAM
2904     if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
2905         reset($cache);
2906         $key = key($cache);
2907         unset($cache[$key]);
2908     }
2910     return $cache[$course->id];
2913 /**
2914  * Goes through all enrolment records for the courses inside the metacourse and sync with them.
2915  *
2916  * @todo finish timeend and timestart maybe we could rely on cron
2917  *       job to do the cleaning from time to time
2918  *
2919  * @global object
2920  * @global object
2921  * @uses CONTEXT_COURSE
2922  * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
2923  * @return bool Success
2924  */
2925 function sync_metacourse($course) {
2926     global $CFG, $DB;
2928     // Check the course is valid.
2929     if (!is_object($course)) {
2930         if (!$course = $DB->get_record('course', array('id'=>$course))) {
2931             return false; // invalid course id
2932         }
2933     }
2935     // Check that we actually have a metacourse.
2936     if (empty($course->metacourse)) {
2937         return false;
2938     }
2940     // Get a list of roles that should not be synced.
2941     if (!empty($CFG->nonmetacoursesyncroleids)) {
2942         $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
2943     } else {
2944         $roleexclusions = '';
2945     }
2947     // Get the context of the metacourse.
2948     $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
2950     // We do not ever want to unassign the list of metacourse manager, so get a list of them.
2951     if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
2952         $managers = array_keys($users);
2953     } else {
2954         $managers = array();
2955     }
2957     // Get assignments of a user to a role that exist in a child course, but
2958     // not in the meta coure. That is, get a list of the assignments that need to be made.
2959     if (!$assignments = $DB->get_records_sql("
2960             SELECT ra.id, ra.roleid, ra.userid, ra.hidden
2961               FROM {role_assignments} ra, {context} con, {course_meta} cm
2962              WHERE ra.contextid = con.id AND
2963                    con.contextlevel = ".CONTEXT_COURSE." AND
2964                    con.instanceid = cm.child_course AND
2965                    cm.parent_course = ? AND
2966                    $roleexclusions
2967                    NOT EXISTS (
2968                      SELECT 1
2969                        FROM {role_assignments} ra2
2970                       WHERE ra2.userid = ra.userid AND
2971                             ra2.roleid = ra.roleid AND
2972                             ra2.contextid = ?
2973                   )", array($course->id, $context->id))) {
2974         $assignments = array();
2975     }
2977     // Get assignments of a user to a role that exist in the meta course, but
2978     // not in any child courses. That is, get a list of the unassignments that need to be made.
2979     if (!$unassignments = $DB->get_records_sql("
2980             SELECT ra.id, ra.roleid, ra.userid
2981               FROM {role_assignments} ra
2982              WHERE ra.contextid = ? AND
2983                    $roleexclusions
2984                    NOT EXISTS (
2985                     SELECT 1
2986                       FROM {role_assignments} ra2, {context} con2, {course_meta} cm
2987                     WHERE ra2.userid = ra.userid AND
2988                           ra2.roleid = ra.roleid AND
2989                           ra2.contextid = con2.id AND
2990                           con2.contextlevel = " . CONTEXT_COURSE . " AND
2991                           con2.instanceid = cm.child_course AND
2992                           cm.parent_course = ?
2993                   )", array($context->id, $course->id))) {
2994         $unassignments = array();
2995     }
2997     $success = true;
2999     // Make the unassignments, if they are not managers.
3000     foreach ($unassignments as $unassignment) {
3001         if (!in_array($unassignment->userid, $managers)) {
3002             $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
3003         }
3004     }
3006     // Make the assignments.
3007     foreach ($assignments as $assignment) {
3008         $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id, 0, 0, $assignment->hidden) && $success;
3009     }
3011     return $success;
3013 // TODO: finish timeend and timestart
3014 // maybe we could rely on cron job to do the cleaning from time to time
3017 /**
3018  * Adds a record to the metacourse table and calls sync_metacoures
3019  *
3020  * @global object
3021  * @param int $metacourseid The Metacourse ID for the metacourse to add to
3022  * @param int $courseid The Course ID of the course to add
3023  * @return bool Success
3024  */
3025 function add_to_metacourse ($metacourseid, $courseid) {
3026     global $DB;
3028     if (!$metacourse = $DB->get_record("course", array("id"=>$metacourseid))) {
3029         return false;
3030     }
3032     if (!$course = $DB->get_record("course", array("id"=>$courseid))) {
3033         return false;
3034     }
3036     if (!$record = $DB->get_record("course_meta", array("parent_course"=>$metacourseid, "child_course"=>$courseid))) {
3037         $rec = new object();
3038         $rec->parent_course = $metacourseid;
3039         $rec->child_course  = $courseid;
3040         $DB->insert_record('course_meta', $rec);
3041         return sync_metacourse($metacourseid);
3042     }
3043     return true;
3047 /**
3048  * Removes the record from the metacourse table and calls sync_metacourse
3049  *
3050  * @global object
3051  * @param int $metacourseid The Metacourse ID for the metacourse to remove from
3052  * @param int $courseid The Course ID of the course to remove
3053  * @return bool Success
3054  */
3055 function remove_from_metacourse($metacourseid, $courseid) {
3056     global $DB;
3058     if ($DB->delete_records('course_meta', array('parent_course'=>$metacourseid, 'child_course'=>$courseid))) {
3059         return sync_metacourse($metacourseid);
3060     }
3061     return false;
3065 /**
3066  * Determines if a user is currently logged in
3067  *
3068  * @global object
3069  * @return bool
3070  */
3071 function isloggedin() {
3072     global $USER;
3074     return (!empty($USER->id));
3077 /**
3078  * Determines if a user is logged in as real guest user with username 'guest'.
3079  * This function is similar to original isguest() in 1.6 and earlier.
3080  * Current isguest() is deprecated - do not use it anymore.
3081  *
3082  * @global object
3083  * @global object
3084  * @param int $user mixed user object or id, $USER if not specified
3085  * @return bool true if user is the real guest user, false if not logged in or other user
3086  */
3087 function isguestuser($user=NULL) {
3088     global $USER, $DB;
3090     if ($user === NULL) {
3091         $user = $USER;
3092     } else if (is_numeric($user)) {
3093         $user = $DB->get_record('user', array('id'=>$user), 'id, username');
3094     }
3096     if (empty($user->id)) {
3097         return false; // not logged in, can not be guest
3098     }
3100     return ($user->username == 'guest');
3103 /**
3104  * Determines if the currently logged in user is in editing mode.
3105  * Note: originally this function had $userid parameter - it was not usable anyway
3106  *
3107  * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3108  * @todo Deprecated function remove when ready
3109  *
3110  * @global object
3111  * @uses DEBUG_DEVELOPER
3112  * @return bool
3113  */
3114 function isediting() {
3115     global $PAGE;
3116     debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3117     return $PAGE->user_is_editing();
3120 /**
3121  * Determines if the logged in user is currently moving an activity
3122  *
3123  * @global object
3124  * @param int $courseid The id of the course being tested
3125  * @return bool
3126  */
3127 function ismoving($courseid) {
3128     global $USER;
3130     if (!empty($USER->activitycopy)) {
3131         return ($USER->activitycopycourse == $courseid);
3132     }
3133     return false;
3136 /**
3137  * Returns a persons full name
3138  *
3139  * Given an object containing firstname and lastname
3140  * values, this function returns a string with the
3141  * full name of the person.
3142  * The result may depend on system settings
3143  * or language.  'override' will force both names
3144  * to be used even if system settings specify one.
3145  *
3146  * @global object
3147  * @global object
3148  * @param object $user A {@link $USER} object to get full name of
3149  * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3150  * @return string
3151  */
3152 function fullname($user, $override=false) {
3153     global $CFG, $SESSION;
3155     if (!isset($user->firstname) and !isset($user->lastname)) {
3156         return '';
3157     }
3159     if (!$override) {
3160         if (!empty($CFG->forcefirstname)) {
3161             $user->firstname = $CFG->forcefirstname;
3162         }
3163         if (!empty($CFG->forcelastname)) {
3164             $user->lastname = $CFG->forcelastname;
3165         }
3166     }
3168     if (!empty($SESSION->fullnamedisplay)) {
3169         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3170     }
3172     if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3173         return $user->firstname .' '. $user->lastname;
3175     } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3176         return $user->lastname .' '. $user->firstname;
3178     } else if ($CFG->fullnamedisplay == 'firstname') {
3179         if ($override) {
3180             return get_string('fullnamedisplay', '', $user);
3181         } else {
3182             return $user->firstname;
3183         }
3184     }
3186     return get_string('fullnamedisplay', '', $user);
3189 /**
3190  * Returns whether a given authentication plugin exists.
3191  *
3192  * @global object
3193  * @param string $auth Form of authentication to check for. Defaults to the
3194  *        global setting in {@link $CFG}.
3195  * @return boolean Whether the plugin is available.
3196  */
3197 function exists_auth_plugin($auth) {
3198     global $CFG;
3200     if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3201         return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3202     }
3203     return false;
3206 /**
3207  * Checks if a given plugin is in the list of enabled authentication plugins.
3208  *
3209  * @param string $auth Authentication plugin.
3210  * @return boolean Whether the plugin is enabled.
3211  */
3212 function is_enabled_auth($auth) {
3213     if (empty($auth)) {
3214         return false;
3215     }
3217     $enabled = get_enabled_auth_plugins();
3219     return in_array($auth, $enabled);
3222 /**
3223  * Returns an authentication plugin instance.
3224  *
3225  * @global object
3226  * @param string $auth name of authentication plugin
3227  * @return object An instance of the required authentication plugin.
3228  */
3229 function get_auth_plugin($auth) {
3230     global $CFG;
3232     // check the plugin exists first
3233     if (! exists_auth_plugin($auth)) {
3234         print_error('authpluginnotfound', 'debug', '', $auth);
3235     }
3237     // return auth plugin instance
3238     require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3239     $class = "auth_plugin_$auth";
3240     return new $class;
3243 /**
3244  * Returns array of active auth plugins.
3245  *
3246  * @param bool $fix fix $CFG->auth if needed
3247  * @return array
3248  */
3249 function get_enabled_auth_plugins($fix=false) {
3250     global $CFG;
3252     $default = array('manual', 'nologin');
3254     if (empty($CFG->auth)) {
3255         $auths = array();
3256     } else {
3257         $auths = explode(',', $CFG->auth);
3258     }
3260     if ($fix) {
3261         $auths = array_unique($auths);
3262         foreach($auths as $k=>$authname) {
3263             if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3264                 unset($auths[$k]);
3265             }
3266         }
3267         $newconfig = implode(',', $auths);
3268         if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3269             set_config('auth', $newconfig);
3270         }
3271     }
3273     return (array_merge($default, $auths));
3276 /**
3277  * Returns true if an internal authentication method is being used.
3278  * if method not specified then, global default is assumed
3279  *
3280  * @param string $auth Form of authentication required
3281  * @return bool
3282  */
3283 function is_internal_auth($auth) {
3284     $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3285     return $authplugin->is_internal();
3288 /**
3289  * Returns true if the user is a 'restored' one
3290  *
3291  * Used in the login process to inform the user
3292  * and allow him/her to reset the password
3293  *
3294  * @uses $CFG
3295  * @uses $DB
3296  * @param string $username username to be checked
3297  * @return bool
3298  */
3299 function is_restored_user($username) {
3300     global $CFG, $DB;
3302     return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3305 /**
3306  * Returns an array of user fields
3307  *
3308  * @return array User field/column names
3309  */
3310 function get_user_fieldnames() {
3311     global $DB;
3313     $fieldarray = $DB->get_columns('user');
3314     unset($fieldarray['id']);
3315     $fieldarray = array_keys($fieldarray);
3317     return $fieldarray;
3320 /**
3321  * Creates a bare-bones user record
3322  *
3323  * @todo Outline auth types and provide code example
3324  *
3325  * @global object
3326  * @global object
3327  * @param string $username New user's username to add to record
3328  * @param string $password New user's password to add to record
3329  * @param string $auth Form of authentication required
3330  * @return object A {@link $USER} object
3331  */
3332 function create_user_record($username, $password, $auth='manual') {
3333     global $CFG, $DB;
3335     //just in case check text case
3336     $username = trim(moodle_strtolower($username));
3338     $authplugin = get_auth_plugin($auth);
3340     $newuser = new object();
3342     if ($newinfo = $authplugin->get_userinfo($username)) {
3343         $newinfo = truncate_userinfo($newinfo);
3344         foreach ($newinfo as $key => $value){
3345             $newuser->$key = $value;
3346         }
3347     }
3349     if (!empty($newuser->email)) {
3350         if (email_is_not_allowed($newuser->email)) {
3351             unset($newuser->email);
3352         }
3353     }
3355     if (!isset($newuser->city)) {
3356         $newuser->city = '';
3357     }
3359     $newuser->auth = $auth;
3360     $newuser->username = $username;
3362     // fix for MDL-8480
3363     // user CFG lang for user if $newuser->lang is empty
3364     // or $user->lang is not an installed language
3365     $sitelangs = array_keys(get_list_of_languages());
3366     if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
3367         $newuser->lang = $CFG->lang;
3368     }
3369     $newuser->confirmed = 1;
3370     $newuser->lastip = getremoteaddr();
3371     $newuser->timemodified = time();
3372     $newuser->mnethostid = $CFG->mnet_localhost_id;
3374     $DB->insert_record('user', $newuser);
3375     $user = get_complete_user_data('username', $newuser->username);
3376     if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3377         set_user_preference('auth_forcepasswordchange', 1, $user->id);
3378     }
3379     update_internal_user_password($user, $password);
3380     return $user;
3383 /**
3384  * Will update a local user record from an external source
3385  *
3386  * @global object
3387  * @param string $username New user's username to add to record
3388  * @param string $authplugin Unused
3389  * @return user A {@link $USER} object
3390  */
3391 function update_user_record($username, $authplugin) {
3392     global $DB;
3394     $username = trim(moodle_strtolower($username)); /// just in case check text case
3396     $oldinfo = $DB->get_record('user', array('username'=>$username), 'username, auth');
3397     $userauth = get_auth_plugin($oldinfo->auth);
3399     if ($newinfo = $userauth->get_userinfo($username)) {
3400         $newinfo = truncate_userinfo($newinfo);
3401         foreach ($newinfo as $key => $value){
3402             if ($key === 'username') {
3403                 // 'username' is not a mapped updateable/lockable field, so skip it.
3404                 continue;
3405             }
3406             $confval = $userauth->config->{'field_updatelocal_' . $key};
3407             $lockval = $userauth->config->{'field_lock_' . $key};
3408             if (empty($confval) || empty($lockval)) {
3409                 continue;
3410             }
3411             if ($confval === 'onlogin') {
3412                 // MDL-4207 Don't overwrite modified user profile values with
3413                 // empty LDAP values when 'unlocked if empty' is set. The purpose
3414                 // of the setting 'unlocked if empty' is to allow the user to fill
3415                 // in a value for the selected field _if LDAP is giving
3416                 // nothing_ for this field. Thus it makes sense to let this value
3417                 // stand in until LDAP is giving a value for this field.
3418                 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3419                     $DB->set_field('user', $key, $value, array('username'=>$username));
3420                 }
3421             }
3422         }
3423     }
3425     return get_complete_user_data('username', $username);
3428 /**
3429  * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3430  * which may have large fields
3431  *
3432  * @todo Add vartype handling to ensure $info is an array
3433  *
3434  * @param array $info Array of user properties to truncate if needed
3435  * @return array The now truncated information that was passed in
3436  */
3437 function truncate_userinfo($info) {
3438     // define the limits
3439     $limit = array(
3440                     'username'    => 100,
3441                     'idnumber'    => 255,
3442                     'firstname'   => 100,
3443                     'lastname'    => 100,
3444                     'email'       => 100,
3445                     'icq'         =>  15,
3446                     'phone1'      =>  20,
3447                     'phone2'      =>  20,
3448                     'institution' =>  40,
3449                     'department'  =>  30,
3450                     'address'     =>  70,
3451                     'city'        =>  20,
3452                     'country'     =>   2,
3453                     'url'         => 255,
3454                     );
3456     // apply where needed
3457     foreach (array_keys($info) as $key) {
3458         if (!empty($limit[$key])) {
3459             $info[$key] = trim(substr($info[$key],0, $limit[$key]));
3460         }
3461     }
3463     return $info;
3466 /**
3467  * Marks user deleted in internal user database and notifies the auth plugin.
3468  * Also unenrols user from all roles and does other cleanup.
3469  *
3470  * @todo Decide if this transaction is really needed (look for internal TODO:)
3471  *
3472  * @global object
3473  * @global object
3474  * @param object $user Userobject before delete    (without system magic quotes)
3475  * @return boolean success
3476  */
3477 function delete_user($user) {
3478     global $CFG, $DB;
3479     require_once($CFG->libdir.'/grouplib.php');
3480     require_once($CFG->libdir.'/gradelib.php');
3481     require_once($CFG->dirroot.'/message/lib.php');
3483     // delete all grades - backup is kept in grade_grades_history table
3484     if ($grades = grade_grade::fetch_all(array('userid'=>$user->id))) {
3485         foreach ($grades as $grade) {
3486             $grade->delete('userdelete');
3487         }
3488     }
3490     //move unread messages from this user to read
3491     message_move_userfrom_unread2read($user->id);
3493     // remove from all groups
3494     $DB->delete_records('groups_members', array('userid'=>$user->id));
3496     // unenrol from all roles in all contexts
3497     role_unassign(0, $user->id); // this might be slow but it is really needed - modules might do some extra cleanup!
3499     // now do a final accesslib cleanup - removes all role assingments in user context and context itself
3500     delete_context(CONTEXT_USER, $user->id);
3502     require_once($CFG->dirroot.'/tag/lib.php');
3503     tag_set('user', $user->id, array());
3505     // workaround for bulk deletes of users with the same email address
3506     $delname = "$user->email.".time();
3507     while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3508         $delname++;
3509     }
3511     // mark internal user record as "deleted"
3512     $updateuser = new object();
3513     $updateuser->id           = $user->id;
3514     $updateuser->deleted      = 1;
3515     $updateuser->username     = $delname;            // Remember it just in case
3516     $updateuser->email        = md5($user->username);// Store hash of username, useful importing/restoring users
3517     $updateuser->idnumber     = '';                  // Clear this field to free it up
3518     $updateuser->timemodified = time();
3520     $DB->update_record('user', $updateuser);
3522     // notify auth plugin - do not block the delete even when plugin fails
3523     $authplugin = get_auth_plugin($user->auth);
3524     $authplugin->user_delete($user);
3526     events_trigger('user_deleted', $user);
3528     return true;
3531 /**
3532  * Retrieve the guest user object
3533  *
3534  * @global object
3535  * @global object
3536  * @return user A {@link $USER} object
3537  */
3538 function guest_user() {
3539     global $CFG, $DB;
3541     if ($newuser = $DB->get_record('user', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
3542         $newuser->confirmed = 1;
3543         $newuser->lang = $CFG->lang;
3544         $newuser->lastip = getremoteaddr();
3545     }
3547     return $newuser;
3550 /**
3551  * Authenticates a user against the chosen authentication mechanism
3552  *
3553  * Given a username and password, this function looks them
3554  * up using the currently selected authentication mechanism,
3555  * and if the authentication is successful, it returns a
3556  * valid $user object from the 'user' table.
3557  *
3558  * Uses auth_ functions from the currently active auth module
3559  *
3560  * After authenticate_user_login() returns success, you will need to
3561  * log that the user has logged in, and call complete_user_login() to set
3562  * the session up.
3563  *
3564  * @global object
3565  * @global object
3566  * @param string $username  User's username
3567  * @param string $password  User's password
3568  * @return user|flase A {@link $USER} object or false if error
3569  */
3570 function authenticate_user_login($username, $password) {
3571     global $CFG, $DB, $OUTPUT;
3573     $authsenabled = get_enabled_auth_plugins();
3575     if ($user = get_complete_user_data('username', $username)) {
3576         $auth = empty($user->auth) ? 'manual' : $user->auth;  // use manual if auth not set
3577         if ($auth=='nologin' or !is_enabled_auth($auth)) {
3578             add_to_log(0, 'login', 'error', 'index.php', $username);
3579             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Disabled Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3580             return false;
3581         }
3582         $auths = array($auth);
3584     } else {
3585         // check if there's a deleted record (cheaply)
3586         if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
3587             error_log('[client '.$_SERVER['REMOTE_ADDR']."]  $CFG->wwwroot  Deleted Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3588             return false;
3589         }
3591         $auths = $authsenabled;
3592         $user = new object();
3593         $user->id = 0;     // User does not exist
3594     }
3596     foreach ($auths as $auth) {
3597         $authplugin = get_auth_plugin($auth);
3599         // on auth fail fall through to the next plugin
3600         if (!$authplugin->user_login($username, $password)) {
3601             continue;
3602         }
3604         // successful authentication
3605         if ($user->id) {                          // User already exists in database
3606             if (empty($user->auth)) {             // For some reason auth isn't set yet
3607                 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
3608                 $user->auth = $auth;
3609             }
3610             if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3611                 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
3612                 $user->firstaccess = $user->timemodified;
3613             }
3615             update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3617             if (!$authplugin->is_internal()) {            // update user record from external DB
3618                 $user = update_user_record($username, get_auth_plugin($user->auth));
3619             }
3620         } else {
3621             // if user not found, create him
3622             $user = create_user_record($username, $password, $auth);
3623         }
3625         $authplugin->sync_roles($user);
3627         foreach ($authsenabled as $hau) {
3628             $hauth = get_auth_plugin($hau);
3629             $hauth->user_authenticated_hook($user, $username, $password);
3630         }
3632     /// Log in to a second system if necessary
3633     /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
3634         if (!empty($CFG->sso)) {
3635             include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
3636             if (function_exists('sso_user_login')) {
3637                 if (!sso_user_login($username, $password)) {   // Perform the signon process
3638                     echo $OUTPUT->notification('Second sign-on failed');
3639                 }
3640             }
3641         }
3643         if ($user->id===0) {
3644             return false;
3645         }
3646         return $user;
3647     }
3649     // failed if all the plugins have failed
3650     add_to_log(0, 'login', 'error', 'index.php', $username);
3651     if (debugging('', DEBUG_ALL)) {
3652         error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Failed Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3653     }
3654     return false;
3657 /**
3658  * Call to complete the user login process after authenticate_user_login()
3659  * has succeeded. It will setup the $USER variable and other required bits
3660  * and pieces.
3661  *
3662  * NOTE:
3663  * - It will NOT log anything -- up to the caller to decide what to log.
3664  *
3665  * @global object
3666  * @global object
3667  * @global object
3668  * @param object $user
3669  * @param bool $setcookie
3670  * @return object A {@link $USER} object - BC only, do not use
3671  */
3672 function complete_user_login($user, $setcookie=true) {
3673     global $CFG, $USER, $SESSION;
3675     // regenerate session id and delete old session,
3676     // this helps prevent session fixation attacks from the same domain
3677     session_regenerate_id(true);
3679     // check enrolments, load caps and setup $USER object
3680     session_set_user($user);
3682     update_user_login_times();
3683     set_login_session_preferences();
3685     if ($setcookie) {
3686         if (empty($CFG->nolastloggedin)) {
3687             set_moodle_cookie($USER->username);
3688         } else {
3689             // do not store last logged in user in cookie
3690             // auth plugins can temporarily override this from loginpage_hook()
3691             // do not save $CFG->nolastloggedin in database!
3692             set_moodle_cookie('nobody');
3693         }
3694     }
3696     /// Select password change url
3697     $userauth = get_auth_plugin($USER->auth);
3699     /// check whether the user should be changing password
3700     if (get_user_preferences('auth_forcepasswordchange', false)){
3701         if ($userauth->can_change_password()) {
3702             if ($changeurl = $userauth->change_password_url()) {
3703                 redirect($changeurl);
3704             } else {
3705                 redirect($CFG->httpswwwroot.'/login/change_password.php');
3706             }
3707         } else {
3708             print_error('nopasswordchangeforced', 'auth');
3709         }
3710     }
3711     return $USER;
3714 /**
3715  * Compare password against hash stored in internal user table.
3716  * If necessary it also updates the stored hash to new format.
3717  *
3718  * @global object
3719  * @param object $user
3720  * @param string $password plain text password
3721  * @return bool is password valid?
3722  */
3723 function validate_internal_user_password(&$user, $password) {
3724     global $CFG;
3726     if (!isset($CFG->passwordsaltmain)) {
3727         $CFG->passwordsaltmain = '';
3728     }
3730     $validated = false;
3732     // get password original encoding in case it was not updated to unicode yet