4466a9922c49d2551833731340244304488fc2af
[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 has default completion */
361 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
363 define('FEATURE_COMMENT', 'comment');
365 define('FEATURE_RATE', 'rate');
367 /** Unspecified module archetype */
368 define('MOD_ARCHETYPE_OTHER', 0);
369 /** Resource-like type module */
370 define('MOD_ARCHETYPE_RESOURCE', 1);
371 /** Assignemnt module archetype */
372 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
374 /**
375  * Security token used for allowing access
376  * from external application such as web services.
377  * Scripts do not use any session, performance is relatively
378  * low because we need to load access info in each request.
379  * Scrits are executed in parallel.
380  */
381 define('EXTERNAL_TOKEN_PERMANENT', 0);
383 /**
384  * Security token used for allowing access
385  * of embedded applications, the code is executed in the
386  * active user session. Token is invalidated after user logs out.
387  * Scripts are executed serially - normal session locking is used.
388  */
389 define('EXTERNAL_TOKEN_EMBEDDED', 1);
391 /// PARAMETER HANDLING ////////////////////////////////////////////////////
393 /**
394  * Returns a particular value for the named variable, taken from
395  * POST or GET.  If the parameter doesn't exist then an error is
396  * thrown because we require this variable.
397  *
398  * This function should be used to initialise all required values
399  * in a script that are based on parameters.  Usually it will be
400  * used like this:
401  *    $id = required_param('id', PARAM_INT);
402  *
403  * @param string $parname the name of the page parameter we want,
404  *                        default PARAM_CLEAN
405  * @param int $type expected type of parameter
406  * @return mixed
407  */
408 function required_param($parname, $type=PARAM_CLEAN) {
409     if (isset($_POST[$parname])) {       // POST has precedence
410         $param = $_POST[$parname];
411     } else if (isset($_GET[$parname])) {
412         $param = $_GET[$parname];
413     } else {
414         print_error('missingparam', '', '', $parname);
415     }
417     return clean_param($param, $type);
420 /**
421  * Returns a particular value for the named variable, taken from
422  * POST or GET, otherwise returning a given default.
423  *
424  * This function should be used to initialise all optional values
425  * in a script that are based on parameters.  Usually it will be
426  * used like this:
427  *    $name = optional_param('name', 'Fred', PARAM_TEXT);
428  *
429  * @param string $parname the name of the page parameter we want
430  * @param mixed  $default the default value to return if nothing is found
431  * @param int $type expected type of parameter, default PARAM_CLEAN
432  * @return mixed
433  */
434 function optional_param($parname, $default=NULL, $type=PARAM_CLEAN) {
435     if (isset($_POST[$parname])) {       // POST has precedence
436         $param = $_POST[$parname];
437     } else if (isset($_GET[$parname])) {
438         $param = $_GET[$parname];
439     } else {
440         return $default;
441     }
443     return clean_param($param, $type);
446 /**
447  * Strict validation of parameter values, the values are only converted
448  * to requested PHP type. Internally it is using clean_param, the values
449  * before and after cleaning must be equal - otherwise
450  * an invalid_parameter_exception is thrown.
451  * Onjects and classes are not accepted.
452  *
453  * @param mixed $param
454  * @param int $type PARAM_ constant
455  * @param bool $allownull are nulls valid value?
456  * @param string $debuginfo optional debug information
457  * @return mixed the $param value converted to PHP type or invalid_parameter_exception
458  */
459 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
460     if (is_null($param)) {
461         if ($allownull == NULL_ALLOWED) {
462             return null;
463         } else {
464             throw new invalid_parameter_exception($debuginfo);
465         }
466     }
467     if (is_array($param) or is_object($param)) {
468         throw new invalid_parameter_exception($debuginfo);
469     }
471     $cleaned = clean_param($param, $type);
472     if ((string)$param !== (string)$cleaned) {
473         // conversion to string is usually lossless
474         throw new invalid_parameter_exception($debuginfo);
475     }
477     return $cleaned;
480 /**
481  * Used by {@link optional_param()} and {@link required_param()} to
482  * clean the variables and/or cast to specific types, based on
483  * an options field.
484  * <code>
485  * $course->format = clean_param($course->format, PARAM_ALPHA);
486  * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
487  * </code>
488  *
489  * @global object
490  * @uses PARAM_RAW
491  * @uses PARAM_CLEAN
492  * @uses PARAM_CLEANHTML
493  * @uses PARAM_INT
494  * @uses PARAM_FLOAT
495  * @uses PARAM_NUMBER
496  * @uses PARAM_ALPHA
497  * @uses PARAM_ALPHAEXT
498  * @uses PARAM_ALPHANUM
499  * @uses PARAM_ALPHANUMEXT
500  * @uses PARAM_SEQUENCE
501  * @uses PARAM_BOOL
502  * @uses PARAM_NOTAGS
503  * @uses PARAM_TEXT
504  * @uses PARAM_SAFEDIR
505  * @uses PARAM_SAFEPATH
506  * @uses PARAM_FILE
507  * @uses PARAM_PATH
508  * @uses PARAM_HOST
509  * @uses PARAM_URL
510  * @uses PARAM_LOCALURL
511  * @uses PARAM_PEM
512  * @uses PARAM_BASE64
513  * @uses PARAM_TAG
514  * @uses PARAM_SEQUENCE
515  * @uses PARAM_USERNAME
516  * @param mixed $param the variable we are cleaning
517  * @param int $type expected format of param after cleaning.
518  * @return mixed
519  */
520 function clean_param($param, $type) {
522     global $CFG;
524     if (is_array($param)) {              // Let's loop
525         $newparam = array();
526         foreach ($param as $key => $value) {
527             $newparam[$key] = clean_param($value, $type);
528         }
529         return $newparam;
530     }
532     switch ($type) {
533         case PARAM_RAW:          // no cleaning at all
534             return $param;
536         case PARAM_CLEAN:        // General HTML cleaning, try to use more specific type if possible
537             if (is_numeric($param)) {
538                 return $param;
539             }
540             return clean_text($param);     // Sweep for scripts, etc
542         case PARAM_CLEANHTML:    // prepare html fragment for display, do not store it into db!!
543             $param = clean_text($param);     // Sweep for scripts, etc
544             return trim($param);
546         case PARAM_INT:
547             return (int)$param;  // Convert to integer
549         case PARAM_FLOAT:
550         case PARAM_NUMBER:
551             return (float)$param;  // Convert to float
553         case PARAM_ALPHA:        // Remove everything not a-z
554             return preg_replace('/[^a-zA-Z]/i', '', $param);
556         case PARAM_ALPHAEXT:     // Remove everything not a-zA-Z_- (originally allowed "/" too)
557             return preg_replace('/[^a-zA-Z_-]/i', '', $param);
559         case PARAM_ALPHANUM:     // Remove everything not a-zA-Z0-9
560             return preg_replace('/[^A-Za-z0-9]/i', '', $param);
562         case PARAM_ALPHANUMEXT:     // Remove everything not a-zA-Z0-9_-
563             return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
565         case PARAM_SEQUENCE:     // Remove everything not 0-9,
566             return preg_replace('/[^0-9,]/i', '', $param);
568         case PARAM_BOOL:         // Convert to 1 or 0
569             $tempstr = strtolower($param);
570             if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
571                 $param = 1;
572             } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
573                 $param = 0;
574             } else {
575                 $param = empty($param) ? 0 : 1;
576             }
577             return $param;
579         case PARAM_NOTAGS:       // Strip all tags
580             return strip_tags($param);
582         case PARAM_TEXT:    // leave only tags needed for multilang
583             return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);
585         case PARAM_SAFEDIR:      // Remove everything not a-zA-Z0-9_-
586             return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
588         case PARAM_SAFEPATH:     // Remove everything not a-zA-Z0-9/_-
589             return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
591         case PARAM_FILE:         // Strip all suspicious characters from filename
592             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\/]~u', '', $param);
593             $param = preg_replace('~\.\.+~', '', $param);
594             if ($param === '.') {
595                 $param = '';
596             }
597             return $param;
599         case PARAM_PATH:         // Strip all suspicious characters from file path
600             $param = str_replace('\\', '/', $param);
601             $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
602             $param = preg_replace('~\.\.+~', '', $param);
603             $param = preg_replace('~//+~', '/', $param);
604             return preg_replace('~/(\./)+~', '/', $param);
606         case PARAM_HOST:         // allow FQDN or IPv4 dotted quad
607             $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
608             // match ipv4 dotted quad
609             if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
610                 // confirm values are ok
611                 if ( $match[0] > 255
612                      || $match[1] > 255
613                      || $match[3] > 255
614                      || $match[4] > 255 ) {
615                     // hmmm, what kind of dotted quad is this?
616                     $param = '';
617                 }
618             } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
619                        && !preg_match('/^[\.-]/',  $param) // no leading dots/hyphens
620                        && !preg_match('/[\.-]$/',  $param) // no trailing dots/hyphens
621                        ) {
622                 // all is ok - $param is respected
623             } else {
624                 // all is not ok...
625                 $param='';
626             }
627             return $param;
629         case PARAM_URL:          // allow safe ftp, http, mailto urls
630             include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
631             if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
632                 // all is ok, param is respected
633             } else {
634                 $param =''; // not really ok
635             }
636             return $param;
638         case PARAM_LOCALURL:     // allow http absolute, root relative and relative URLs within wwwroot
639             $param = clean_param($param, PARAM_URL);
640             if (!empty($param)) {
641                 if (preg_match(':^/:', $param)) {
642                     // root-relative, ok!
643                 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
644                     // absolute, and matches our wwwroot
645                 } else {
646                     // relative - let's make sure there are no tricks
647                     if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
648                         // looks ok.
649                     } else {
650                         $param = '';
651                     }
652                 }
653             }
654             return $param;
656         case PARAM_PEM:
657             $param = trim($param);
658             // PEM formatted strings may contain letters/numbers and the symbols
659             // forward slash: /
660             // plus sign:     +
661             // equal sign:    =
662             // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
663             if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
664                 list($wholething, $body) = $matches;
665                 unset($wholething, $matches);
666                 $b64 = clean_param($body, PARAM_BASE64);
667                 if (!empty($b64)) {
668                     return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
669                 } else {
670                     return '';
671                 }
672             }
673             return '';
675         case PARAM_BASE64:
676             if (!empty($param)) {
677                 // PEM formatted strings may contain letters/numbers and the symbols
678                 // forward slash: /
679                 // plus sign:     +
680                 // equal sign:    =
681                 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
682                     return '';
683                 }
684                 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
685                 // Each line of base64 encoded data must be 64 characters in
686                 // length, except for the last line which may be less than (or
687                 // equal to) 64 characters long.
688                 for ($i=0, $j=count($lines); $i < $j; $i++) {
689                     if ($i + 1 == $j) {
690                         if (64 < strlen($lines[$i])) {
691                             return '';
692                         }
693                         continue;
694                     }
696                     if (64 != strlen($lines[$i])) {
697                         return '';
698                     }
699                 }
700                 return implode("\n",$lines);
701             } else {
702                 return '';
703             }
705         case PARAM_TAG:
706             //as long as magic_quotes_gpc is used, a backslash will be a
707             //problem, so remove *all* backslash.
708             //$param = str_replace('\\', '', $param);
709             //remove some nasties
710             $param = preg_replace('~[[:cntrl:]]|[<>`]~', '', $param);
711             //convert many whitespace chars into one
712             $param = preg_replace('/\s+/', ' ', $param);
713             $textlib = textlib_get_instance();
714             $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
715             return $param;
718         case PARAM_TAGLIST:
719             $tags = explode(',', $param);
720             $result = array();
721             foreach ($tags as $tag) {
722                 $res = clean_param($tag, PARAM_TAG);
723                 if ($res !== '') {
724                     $result[] = $res;
725                 }
726             }
727             if ($result) {
728                 return implode(',', $result);
729             } else {
730                 return '';
731             }
733         case PARAM_CAPABILITY:
734             if (get_capability_info($param)) {
735                 return $param;
736             } else {
737                 return '';
738             }
740         case PARAM_PERMISSION:
741             $param = (int)$param;
742             if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
743                 return $param;
744             } else {
745                 return CAP_INHERIT;
746             }
748         case PARAM_AUTH:
749             $param = clean_param($param, PARAM_SAFEDIR);
750             if (exists_auth_plugin($param)) {
751                 return $param;
752             } else {
753                 return '';
754             }
756         case PARAM_LANG:
757             $param = clean_param($param, PARAM_SAFEDIR);
758             if (get_string_manager()->translation_exists($param)) {
759                 return $param;
760             } else {
761                 return ''; // Specified language is not installed or param malformed
762             }
764         case PARAM_THEME:
765             $param = clean_param($param, PARAM_SAFEDIR);
766             if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
767                 return $param;
768             } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
769                 return $param;
770             } else {
771                 return '';  // Specified theme is not installed
772             }
774         case PARAM_USERNAME:
775             $param = str_replace(" " , "", $param);
776             $param = moodle_strtolower($param);  // Convert uppercase to lowercase MDL-16919
777             if (empty($CFG->extendedusernamechars)) {
778                 // regular expression, eliminate all chars EXCEPT:
779                 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
780                 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
781             }
782             return $param;
784         case PARAM_EMAIL:
785             if (validate_email($param)) {
786                 return $param;
787             } else {
788                 return '';
789             }
791         default:                 // throw error, switched parameters in optional_param or another serious problem
792             print_error("unknownparamtype", '', '', $type);
793     }
796 /**
797  * Return true if given value is integer or string with integer value
798  *
799  * @param mixed $value String or Int
800  * @return bool true if number, false if not
801  */
802 function is_number($value) {
803     if (is_int($value)) {
804         return true;
805     } else if (is_string($value)) {
806         return ((string)(int)$value) === $value;
807     } else {
808         return false;
809     }
812 /**
813  * Returns host part from url
814  * @param string $url full url
815  * @return string host, null if not found
816  */
817 function get_host_from_url($url) {
818     preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
819     if ($matches) {
820         return $matches[1];
821     }
822     return null;
825 /**
826  * Tests whether anything was returned by text editor
827  *
828  * This function is useful for testing whether something you got back from
829  * the HTML editor actually contains anything. Sometimes the HTML editor
830  * appear to be empty, but actually you get back a <br> tag or something.
831  *
832  * @param string $string a string containing HTML.
833  * @return boolean does the string contain any actual content - that is text,
834  * images, objcts, etc.
835  */
836 function html_is_blank($string) {
837     return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
840 /**
841  * Set a key in global configuration
842  *
843  * Set a key/value pair in both this session's {@link $CFG} global variable
844  * and in the 'config' database table for future sessions.
845  *
846  * Can also be used to update keys for plugin-scoped configs in config_plugin table.
847  * In that case it doesn't affect $CFG.
848  *
849  * A NULL value will delete the entry.
850  *
851  * @global object
852  * @global object
853  * @param string $name the key to set
854  * @param string $value the value to set (without magic quotes)
855  * @param string $plugin (optional) the plugin scope, default NULL
856  * @return bool true or exception
857  */
858 function set_config($name, $value, $plugin=NULL) {
859     global $CFG, $DB;
861     if (empty($plugin)) {
862         if (!array_key_exists($name, $CFG->config_php_settings)) {
863             // So it's defined for this invocation at least
864             if (is_null($value)) {
865                 unset($CFG->$name);
866             } else {
867                 $CFG->$name = (string)$value; // settings from db are always strings
868             }
869         }
871         if ($DB->get_field('config', 'name', array('name'=>$name))) {
872             if ($value === null) {
873                 $DB->delete_records('config', array('name'=>$name));
874             } else {
875                 $DB->set_field('config', 'value', $value, array('name'=>$name));
876             }
877         } else {
878             if ($value !== null) {
879                 $config = new object();
880                 $config->name  = $name;
881                 $config->value = $value;
882                 $DB->insert_record('config', $config, false);
883             }
884         }
886     } else { // plugin scope
887         if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
888             if ($value===null) {
889                 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
890             } else {
891                 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
892             }
893         } else {
894             if ($value !== null) {
895                 $config = new object();
896                 $config->plugin = $plugin;
897                 $config->name   = $name;
898                 $config->value  = $value;
899                 $DB->insert_record('config_plugins', $config, false);
900             }
901         }
902     }
904     return true;
907 /**
908  * Get configuration values from the global config table
909  * or the config_plugins table.
910  *
911  * If called with no parameters it will do the right thing
912  * generating $CFG safely from the database without overwriting
913  * existing values.
914  *
915  * If called with one parameter, it will load all the config
916  * variables for one pugin, and return them as an object.
917  *
918  * If called with 2 parameters it will return a $string single
919  * value or false of the value is not found.
920  *
921  * @global object
922  * @param string $plugin default NULL
923  * @param string $name default NULL
924  * @return mixed hash-like object or single value
925  */
926 function get_config($plugin=NULL, $name=NULL) {
927     global $CFG, $DB;
929     if (!empty($name)) { // the user is asking for a specific value
930         if (!empty($plugin)) {
931             return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
932         } else {
933             return $DB->get_field('config', 'value', array('name'=>$name));
934         }
935     }
937     // the user is after a recordset
938     if (!empty($plugin)) {
939         $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
940         if (!empty($localcfg)) {
941             return (object)$localcfg;
942         } else {
943             return false;
944         }
945     } else {
946         // this was originally in setup.php
947         if ($configs = $DB->get_records('config')) {
948             $localcfg = (array)$CFG;
949             foreach ($configs as $config) {
950                 if (!isset($localcfg[$config->name])) {
951                     $localcfg[$config->name] = $config->value;
952                 }
953                 // do not complain anymore if config.php overrides settings from db
954             }
956             $localcfg = (object)$localcfg;
957             return $localcfg;
958         } else {
959             // preserve $CFG if DB returns nothing or error
960             return $CFG;
961         }
963     }
966 /**
967  * Removes a key from global configuration
968  *
969  * @param string $name the key to set
970  * @param string $plugin (optional) the plugin scope
971  * @global object
972  * @return boolean whether the operation succeeded.
973  */
974 function unset_config($name, $plugin=NULL) {
975     global $CFG, $DB;
977     if (empty($plugin)) {
978         unset($CFG->$name);
979         $DB->delete_records('config', array('name'=>$name));
980     } else {
981         $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
982     }
984     return true;
987 /**
988  * Remove all the config variables for a given plugin.
989  *
990  * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
991  * @return boolean whether the operation succeeded.
992  */
993 function unset_all_config_for_plugin($plugin) {
994     global $DB;
995     $DB->delete_records('config_plugins', array('plugin' => $plugin));
996     $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
997     return true;
1000 /**
1001  * Use this funciton to get a list of users from a config setting of type admin_setting_users_with_capability.
1002  * @param string $value the value of the config setting.
1003  * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1004  * @return array of user objects.
1005  */
1006 function get_users_from_config($value, $capability) {
1007     global $CFG;
1008     if ($value == '$@ALL@$') {
1009         $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1010     } else {
1011         list($where, $params) = $DB->get_in_or_equal(explode(',', $CFG->courserequestnotify));
1012         $params[] = $CFG->mnet_localhost_id;
1013         $users = $DB->get_records_select('user', 'username ' . $where . ' AND mnethostid = ?', $params);
1014     }
1015     return $users;
1018 /**
1019  * Get volatile flags
1020  *
1021  * @param string $type
1022  * @param int    $changedsince default null
1023  * @return records array
1024  */
1025 function get_cache_flags($type, $changedsince=NULL) {
1026     global $DB;
1028     $params = array('type'=>$type, 'expiry'=>time());
1029     $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1030     if ($changedsince !== NULL) {
1031         $params['changedsince'] = $changedsince;
1032         $sqlwhere .= " AND timemodified > :changedsince";
1033     }
1034     $cf = array();
1036     if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1037         foreach ($flags as $flag) {
1038             $cf[$flag->name] = $flag->value;
1039         }
1040     }
1041     return $cf;
1044 /**
1045  * Get volatile flags
1046  *
1047  * @param string $type
1048  * @param string $name
1049  * @param int    $changedsince default null
1050  * @return records array
1051  */
1052 function get_cache_flag($type, $name, $changedsince=NULL) {
1053     global $DB;
1055     $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1057     $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1058     if ($changedsince !== NULL) {
1059         $params['changedsince'] = $changedsince;
1060         $sqlwhere .= " AND timemodified > :changedsince";
1061     }
1063     return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1066 /**
1067  * Set a volatile flag
1068  *
1069  * @param string $type the "type" namespace for the key
1070  * @param string $name the key to set
1071  * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1072  * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1073  * @return bool Always returns true
1074  */
1075 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1076     global $DB;
1078     $timemodified = time();
1079     if ($expiry===NULL || $expiry < $timemodified) {
1080         $expiry = $timemodified + 24 * 60 * 60;
1081     } else {
1082         $expiry = (int)$expiry;
1083     }
1085     if ($value === NULL) {
1086         unset_cache_flag($type,$name);
1087         return true;
1088     }
1090     if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potentail problem in DEBUG_DEVELOPER
1091         if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1092             return true; //no need to update; helps rcache too
1093         }
1094         $f->value        = $value;
1095         $f->expiry       = $expiry;
1096         $f->timemodified = $timemodified;
1097         $DB->update_record('cache_flags', $f);
1098     } else {
1099         $f = new object();
1100         $f->flagtype     = $type;
1101         $f->name         = $name;
1102         $f->value        = $value;
1103         $f->expiry       = $expiry;
1104         $f->timemodified = $timemodified;
1105         $DB->insert_record('cache_flags', $f);
1106     }
1107     return true;
1110 /**
1111  * Removes a single volatile flag
1112  *
1113  * @global object
1114  * @param string $type the "type" namespace for the key
1115  * @param string $name the key to set
1116  * @return bool
1117  */
1118 function unset_cache_flag($type, $name) {
1119     global $DB;
1120     $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1121     return true;
1124 /**
1125  * Garbage-collect volatile flags
1126  *
1127  * @return bool Always returns true
1128  */
1129 function gc_cache_flags() {
1130     global $DB;
1131     $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1132     return true;
1135 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1137 /**
1138  * Refresh current $USER session global variable with all their current preferences.
1139  *
1140  * @global object
1141  * @param mixed $time default null
1142  * @return void
1143  */
1144 function check_user_preferences_loaded($time = null) {
1145     global $USER, $DB;
1146     static $timenow = null; // Static cache, so we only check up-to-dateness once per request.
1148     if (!empty($USER->preference) && isset($USER->preference['_lastloaded'])) {
1149         // Already loaded. Are we up to date?
1151         if (is_null($timenow) || (!is_null($time) && $time != $timenow)) {
1152             $timenow = time();
1153             if (!get_cache_flag('userpreferenceschanged', $USER->id, $USER->preference['_lastloaded'])) {
1154                 // We are up-to-date.
1155                 return;
1156             }
1157         } else {
1158             // Already checked for up-to-date-ness.
1159             return;
1160         }
1161     }
1163     // OK, so we have to reload. Reset preference
1164     $USER->preference = array();
1166     if (!isloggedin() or isguestuser()) {
1167         // No permanent storage for not-logged-in user and guest
1169     } else if ($preferences = $DB->get_records('user_preferences', array('userid'=>$USER->id))) {
1170         foreach ($preferences as $preference) {
1171             $USER->preference[$preference->name] = $preference->value;
1172         }
1173     }
1175     $USER->preference['_lastloaded'] = $timenow;
1178 /**
1179  * Called from set/delete_user_preferences, so that the prefs can be correctly reloaded.
1180  *
1181  * @global object
1182  * @global object
1183  * @param integer $userid the user whose prefs were changed.
1184  */
1185 function mark_user_preferences_changed($userid) {
1186     global $CFG, $USER;
1187     if ($userid == $USER->id) {
1188         check_user_preferences_loaded(time());
1189     }
1190     set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1193 /**
1194  * Sets a preference for the current user
1195  *
1196  * Optionally, can set a preference for a different user object
1197  *
1198  * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
1199  *
1200  * @global object
1201  * @global object
1202  * @param string $name The key to set as preference for the specified user
1203  * @param string $value The value to set forthe $name key in the specified user's record
1204  * @param int $otheruserid A moodle user ID, default null
1205  * @return bool
1206  */
1207 function set_user_preference($name, $value, $otheruserid=NULL) {
1208     global $USER, $DB;
1210     if (empty($name)) {
1211         return false;
1212     }
1214     $nostore = false;
1215     if (empty($otheruserid)){
1216         if (!isloggedin() or isguestuser()) {
1217             $nostore = true;
1218         }
1219         $userid = $USER->id;
1220     } else {
1221         if (isguestuser($otheruserid)) {
1222             $nostore = true;
1223         }
1224         $userid = $otheruserid;
1225     }
1227     if ($nostore) {
1228         // no permanent storage for not-logged-in user and guest
1230     } else if ($preference = $DB->get_record('user_preferences', array('userid'=>$userid, 'name'=>$name))) {
1231         if ($preference->value === $value) {
1232             return true;
1233         }
1234         $DB->set_field('user_preferences', 'value', (string)$value, array('id'=>$preference->id));
1236     } else {
1237         $preference = new object();
1238         $preference->userid = $userid;
1239         $preference->name   = $name;
1240         $preference->value  = (string)$value;
1241         $DB->insert_record('user_preferences', $preference);
1242     }
1244     mark_user_preferences_changed($userid);
1245     // update value in USER session if needed
1246     if ($userid == $USER->id) {
1247         $USER->preference[$name] = (string)$value;
1248         $USER->preference['_lastloaded'] = time();
1249     }
1251     return true;
1254 /**
1255  * Sets a whole array of preferences for the current user
1256  *
1257  * @param array $prefarray An array of key/value pairs to be set
1258  * @param int $otheruserid A moodle user ID
1259  * @return bool
1260  */
1261 function set_user_preferences($prefarray, $otheruserid=NULL) {
1263     if (!is_array($prefarray) or empty($prefarray)) {
1264         return false;
1265     }
1267     foreach ($prefarray as $name => $value) {
1268         set_user_preference($name, $value, $otheruserid);
1269     }
1270     return true;
1273 /**
1274  * Unsets a preference completely by deleting it from the database
1275  *
1276  * Optionally, can set a preference for a different user id
1277  *
1278  * @global object
1279  * @param string  $name The key to unset as preference for the specified user
1280  * @param int $otheruserid A moodle user ID
1281  */
1282 function unset_user_preference($name, $otheruserid=NULL) {
1283     global $USER, $DB;
1285     if (empty($otheruserid)){
1286         $userid = $USER->id;
1287         check_user_preferences_loaded();
1288     } else {
1289         $userid = $otheruserid;
1290     }
1292     //Then from DB
1293     $DB->delete_records('user_preferences', array('userid'=>$userid, 'name'=>$name));
1295     mark_user_preferences_changed($userid);
1296     //Delete the preference from $USER if needed
1297     if ($userid == $USER->id) {
1298         unset($USER->preference[$name]);
1299         $USER->preference['_lastloaded'] = time();
1300     }
1302     return true;
1305 /**
1306  * Used to fetch user preference(s)
1307  *
1308  * If no arguments are supplied this function will return
1309  * all of the current user preferences as an array.
1310  *
1311  * If a name is specified then this function
1312  * attempts to return that particular preference value.  If
1313  * none is found, then the optional value $default is returned,
1314  * otherwise NULL.
1315  *
1316  * @global object
1317  * @global object
1318  * @param string $name Name of the key to use in finding a preference value
1319  * @param string $default Value to be returned if the $name key is not set in the user preferences
1320  * @param int $otheruserid A moodle user ID
1321  * @return string
1322  */
1323 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
1324     global $USER, $DB;
1326     if (empty($otheruserid) || (isloggedin() && ($USER->id == $otheruserid))){
1327         check_user_preferences_loaded();
1329         if (empty($name)) {
1330             return $USER->preference; // All values
1331         } else if (array_key_exists($name, $USER->preference)) {
1332             return $USER->preference[$name]; // The single value
1333         } else {
1334             return $default; // Default value (or NULL)
1335         }
1337     } else {
1338         if (empty($name)) {
1339             return $DB->get_records_menu('user_preferences', array('userid'=>$otheruserid), '', 'name,value'); // All values
1340         } else if ($value = $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>$name))) {
1341             return $value; // The single value
1342         } else {
1343             return $default; // Default value (or NULL)
1344         }
1345     }
1348 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1350 /**
1351  * Given date parts in user time produce a GMT timestamp.
1352  *
1353  * @todo Finish documenting this function
1354  * @param int $year The year part to create timestamp of
1355  * @param int $month The month part to create timestamp of
1356  * @param int $day The day part to create timestamp of
1357  * @param int $hour The hour part to create timestamp of
1358  * @param int $minute The minute part to create timestamp of
1359  * @param int $second The second part to create timestamp of
1360  * @param float $timezone Timezone modifier
1361  * @param bool $applydst Toggle Daylight Saving Time, default true
1362  * @return int timestamp
1363  */
1364 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1366     $strtimezone = NULL;
1367     if (!is_numeric($timezone)) {
1368         $strtimezone = $timezone;
1369     }
1371     $timezone = get_user_timezone_offset($timezone);
1373     if (abs($timezone) > 13) {
1374         $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1375     } else {
1376         $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1377         $time = usertime($time, $timezone);
1378         if($applydst) {
1379             $time -= dst_offset_on($time, $strtimezone);
1380         }
1381     }
1383     return $time;
1387 /**
1388  * Format a date/time (seconds) as weeks, days, hours etc as needed
1389  *
1390  * Given an amount of time in seconds, returns string
1391  * formatted nicely as weeks, days, hours etc as needed
1392  *
1393  * @uses MINSECS
1394  * @uses HOURSECS
1395  * @uses DAYSECS
1396  * @uses YEARSECS
1397  * @param int $totalsecs Time in seconds
1398  * @param object $str Should be a time object
1399  * @return string A nicely formatted date/time string
1400  */
1401  function format_time($totalsecs, $str=NULL) {
1403     $totalsecs = abs($totalsecs);
1405     if (!$str) {  // Create the str structure the slow way
1406         $str->day   = get_string('day');
1407         $str->days  = get_string('days');
1408         $str->hour  = get_string('hour');
1409         $str->hours = get_string('hours');
1410         $str->min   = get_string('min');
1411         $str->mins  = get_string('mins');
1412         $str->sec   = get_string('sec');
1413         $str->secs  = get_string('secs');
1414         $str->year  = get_string('year');
1415         $str->years = get_string('years');
1416     }
1419     $years     = floor($totalsecs/YEARSECS);
1420     $remainder = $totalsecs - ($years*YEARSECS);
1421     $days      = floor($remainder/DAYSECS);
1422     $remainder = $totalsecs - ($days*DAYSECS);
1423     $hours     = floor($remainder/HOURSECS);
1424     $remainder = $remainder - ($hours*HOURSECS);
1425     $mins      = floor($remainder/MINSECS);
1426     $secs      = $remainder - ($mins*MINSECS);
1428     $ss = ($secs == 1)  ? $str->sec  : $str->secs;
1429     $sm = ($mins == 1)  ? $str->min  : $str->mins;
1430     $sh = ($hours == 1) ? $str->hour : $str->hours;
1431     $sd = ($days == 1)  ? $str->day  : $str->days;
1432     $sy = ($years == 1)  ? $str->year  : $str->years;
1434     $oyears = '';
1435     $odays = '';
1436     $ohours = '';
1437     $omins = '';
1438     $osecs = '';
1440     if ($years)  $oyears  = $years .' '. $sy;
1441     if ($days)  $odays  = $days .' '. $sd;
1442     if ($hours) $ohours = $hours .' '. $sh;
1443     if ($mins)  $omins  = $mins .' '. $sm;
1444     if ($secs)  $osecs  = $secs .' '. $ss;
1446     if ($years) return trim($oyears .' '. $odays);
1447     if ($days)  return trim($odays .' '. $ohours);
1448     if ($hours) return trim($ohours .' '. $omins);
1449     if ($mins)  return trim($omins .' '. $osecs);
1450     if ($secs)  return $osecs;
1451     return get_string('now');
1454 /**
1455  * Returns a formatted string that represents a date in user time
1456  *
1457  * Returns a formatted string that represents a date in user time
1458  * <b>WARNING: note that the format is for strftime(), not date().</b>
1459  * Because of a bug in most Windows time libraries, we can't use
1460  * the nicer %e, so we have to use %d which has leading zeroes.
1461  * A lot of the fuss in the function is just getting rid of these leading
1462  * zeroes as efficiently as possible.
1463  *
1464  * If parameter fixday = true (default), then take off leading
1465  * zero from %d, else mantain it.
1466  *
1467  * @param int $date the timestamp in UTC, as obtained from the database.
1468  * @param string $format strftime format. You should probably get this using
1469  *      get_string('strftime...', 'langconfig');
1470  * @param float $timezone by default, uses the user's time zone.
1471  * @param bool $fixday If true (default) then the leading zero from %d is removed.
1472  *      If false then the leading zero is mantained.
1473  * @return string the formatted date/time.
1474  */
1475 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1477     global $CFG;
1479     $strtimezone = NULL;
1480     if (!is_numeric($timezone)) {
1481         $strtimezone = $timezone;
1482     }
1484     if (empty($format)) {
1485         $format = get_string('strftimedaydatetime', 'langconfig');
1486     }
1488     if (!empty($CFG->nofixday)) {  // Config.php can force %d not to be fixed.
1489         $fixday = false;
1490     } else if ($fixday) {
1491         $formatnoday = str_replace('%d', 'DD', $format);
1492         $fixday = ($formatnoday != $format);
1493     }
1495     $date += dst_offset_on($date, $strtimezone);
1497     $timezone = get_user_timezone_offset($timezone);
1499     if (abs($timezone) > 13) {   /// Server time
1500         if ($fixday) {
1501             $datestring = strftime($formatnoday, $date);
1502             $daystring  = str_replace(array(' 0', ' '), '', strftime(' %d', $date));
1503             $datestring = str_replace('DD', $daystring, $datestring);
1504         } else {
1505             $datestring = strftime($format, $date);
1506         }
1507     } else {
1508         $date += (int)($timezone * 3600);
1509         if ($fixday) {
1510             $datestring = gmstrftime($formatnoday, $date);
1511             $daystring  = str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date));
1512             $datestring = str_replace('DD', $daystring, $datestring);
1513         } else {
1514             $datestring = gmstrftime($format, $date);
1515         }
1516     }
1518 /// If we are running under Windows convert from windows encoding to UTF-8
1519 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1521    if ($CFG->ostype == 'WINDOWS') {
1522        if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1523            $textlib = textlib_get_instance();
1524            $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1525        }
1526    }
1528     return $datestring;
1531 /**
1532  * Given a $time timestamp in GMT (seconds since epoch),
1533  * returns an array that represents the date in user time
1534  *
1535  * @todo Finish documenting this function
1536  * @uses HOURSECS
1537  * @param int $time Timestamp in GMT
1538  * @param float $timezone ?
1539  * @return array An array that represents the date in user time
1540  */
1541 function usergetdate($time, $timezone=99) {
1543     $strtimezone = NULL;
1544     if (!is_numeric($timezone)) {
1545         $strtimezone = $timezone;
1546     }
1548     $timezone = get_user_timezone_offset($timezone);
1550     if (abs($timezone) > 13) {    // Server time
1551         return getdate($time);
1552     }
1554     // There is no gmgetdate so we use gmdate instead
1555     $time += dst_offset_on($time, $strtimezone);
1556     $time += intval((float)$timezone * HOURSECS);
1558     $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
1560     //be careful to ensure the returned array matches that produced by getdate() above
1561     list(
1562         $getdate['month'],
1563         $getdate['weekday'],
1564         $getdate['yday'],
1565         $getdate['year'],
1566         $getdate['mon'],
1567         $getdate['wday'],
1568         $getdate['mday'],
1569         $getdate['hours'],
1570         $getdate['minutes'],
1571         $getdate['seconds']
1572     ) = explode('_', $datestring);
1574     return $getdate;
1577 /**
1578  * Given a GMT timestamp (seconds since epoch), offsets it by
1579  * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1580  *
1581  * @uses HOURSECS
1582  * @param  int $date Timestamp in GMT
1583  * @param float $timezone
1584  * @return int
1585  */
1586 function usertime($date, $timezone=99) {
1588     $timezone = get_user_timezone_offset($timezone);
1590     if (abs($timezone) > 13) {
1591         return $date;
1592     }
1593     return $date - (int)($timezone * HOURSECS);
1596 /**
1597  * Given a time, return the GMT timestamp of the most recent midnight
1598  * for the current user.
1599  *
1600  * @param int $date Timestamp in GMT
1601  * @param float $timezone Defaults to user's timezone
1602  * @return int Returns a GMT timestamp
1603  */
1604 function usergetmidnight($date, $timezone=99) {
1606     $userdate = usergetdate($date, $timezone);
1608     // Time of midnight of this user's day, in GMT
1609     return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1613 /**
1614  * Returns a string that prints the user's timezone
1615  *
1616  * @param float $timezone The user's timezone
1617  * @return string
1618  */
1619 function usertimezone($timezone=99) {
1621     $tz = get_user_timezone($timezone);
1623     if (!is_float($tz)) {
1624         return $tz;
1625     }
1627     if(abs($tz) > 13) { // Server time
1628         return get_string('serverlocaltime');
1629     }
1631     if($tz == intval($tz)) {
1632         // Don't show .0 for whole hours
1633         $tz = intval($tz);
1634     }
1636     if($tz == 0) {
1637         return 'UTC';
1638     }
1639     else if($tz > 0) {
1640         return 'UTC+'.$tz;
1641     }
1642     else {
1643         return 'UTC'.$tz;
1644     }
1648 /**
1649  * Returns a float which represents the user's timezone difference from GMT in hours
1650  * Checks various settings and picks the most dominant of those which have a value
1651  *
1652  * @global object
1653  * @global object
1654  * @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
1655  * @return float
1656  */
1657 function get_user_timezone_offset($tz = 99) {
1659     global $USER, $CFG;
1661     $tz = get_user_timezone($tz);
1663     if (is_float($tz)) {
1664         return $tz;
1665     } else {
1666         $tzrecord = get_timezone_record($tz);
1667         if (empty($tzrecord)) {
1668             return 99.0;
1669         }
1670         return (float)$tzrecord->gmtoff / HOURMINS;
1671     }
1674 /**
1675  * Returns an int which represents the systems's timezone difference from GMT in seconds
1676  *
1677  * @global object
1678  * @param mixed $tz timezone
1679  * @return int if found, false is timezone 99 or error
1680  */
1681 function get_timezone_offset($tz) {
1682     global $CFG;
1684     if ($tz == 99) {
1685         return false;
1686     }
1688     if (is_numeric($tz)) {
1689         return intval($tz * 60*60);
1690     }
1692     if (!$tzrecord = get_timezone_record($tz)) {
1693         return false;
1694     }
1695     return intval($tzrecord->gmtoff * 60);
1698 /**
1699  * Returns a float or a string which denotes the user's timezone
1700  * 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)
1701  * means that for this timezone there are also DST rules to be taken into account
1702  * Checks various settings and picks the most dominant of those which have a value
1703  *
1704  * @global object
1705  * @global object
1706  * @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
1707  * @return mixed
1708  */
1709 function get_user_timezone($tz = 99) {
1710     global $USER, $CFG;
1712     $timezones = array(
1713         $tz,
1714         isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1715         isset($USER->timezone) ? $USER->timezone : 99,
1716         isset($CFG->timezone) ? $CFG->timezone : 99,
1717         );
1719     $tz = 99;
1721     while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
1722         $tz = $next['value'];
1723     }
1725     return is_numeric($tz) ? (float) $tz : $tz;
1728 /**
1729  * Returns cached timezone record for given $timezonename
1730  *
1731  * @global object
1732  * @global object
1733  * @param string $timezonename
1734  * @return mixed timezonerecord object or false
1735  */
1736 function get_timezone_record($timezonename) {
1737     global $CFG, $DB;
1738     static $cache = NULL;
1740     if ($cache === NULL) {
1741         $cache = array();
1742     }
1744     if (isset($cache[$timezonename])) {
1745         return $cache[$timezonename];
1746     }
1748     return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
1749                                                         WHERE name = ? ORDER BY year DESC', array($timezonename), true);
1752 /**
1753  * Build and store the users Daylight Saving Time (DST) table
1754  *
1755  * @global object
1756  * @global object
1757  * @global object
1758  * @param mixed $from_year Start year for the table, defaults to 1971
1759  * @param mixed $to_year End year for the table, defaults to 2035
1760  * @param mixed $strtimezone
1761  * @return bool
1762  */
1763 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
1764     global $CFG, $SESSION, $DB;
1766     $usertz = get_user_timezone($strtimezone);
1768     if (is_float($usertz)) {
1769         // Trivial timezone, no DST
1770         return false;
1771     }
1773     if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1774         // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1775         unset($SESSION->dst_offsets);
1776         unset($SESSION->dst_range);
1777     }
1779     if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1780         // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1781         // This will be the return path most of the time, pretty light computationally
1782         return true;
1783     }
1785     // Reaching here means we either need to extend our table or create it from scratch
1787     // Remember which TZ we calculated these changes for
1788     $SESSION->dst_offsettz = $usertz;
1790     if(empty($SESSION->dst_offsets)) {
1791         // If we 're creating from scratch, put the two guard elements in there
1792         $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1793     }
1794     if(empty($SESSION->dst_range)) {
1795         // If creating from scratch
1796         $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1797         $to   = min((empty($to_year)   ? intval(date('Y')) + 3 : $to_year),   2035);
1799         // Fill in the array with the extra years we need to process
1800         $yearstoprocess = array();
1801         for($i = $from; $i <= $to; ++$i) {
1802             $yearstoprocess[] = $i;
1803         }
1805         // Take note of which years we have processed for future calls
1806         $SESSION->dst_range = array($from, $to);
1807     }
1808     else {
1809         // If needing to extend the table, do the same
1810         $yearstoprocess = array();
1812         $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1813         $to   = min((empty($to_year)   ? $SESSION->dst_range[1] : $to_year),   2035);
1815         if($from < $SESSION->dst_range[0]) {
1816             // Take note of which years we need to process and then note that we have processed them for future calls
1817             for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
1818                 $yearstoprocess[] = $i;
1819             }
1820             $SESSION->dst_range[0] = $from;
1821         }
1822         if($to > $SESSION->dst_range[1]) {
1823             // Take note of which years we need to process and then note that we have processed them for future calls
1824             for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
1825                 $yearstoprocess[] = $i;
1826             }
1827             $SESSION->dst_range[1] = $to;
1828         }
1829     }
1831     if(empty($yearstoprocess)) {
1832         // This means that there was a call requesting a SMALLER range than we have already calculated
1833         return true;
1834     }
1836     // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1837     // Also, the array is sorted in descending timestamp order!
1839     // Get DB data
1841     static $presets_cache = array();
1842     if (!isset($presets_cache[$usertz])) {
1843         $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');
1844     }
1845     if(empty($presets_cache[$usertz])) {
1846         return false;
1847     }
1849     // Remove ending guard (first element of the array)
1850     reset($SESSION->dst_offsets);
1851     unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
1853     // Add all required change timestamps
1854     foreach($yearstoprocess as $y) {
1855         // Find the record which is in effect for the year $y
1856         foreach($presets_cache[$usertz] as $year => $preset) {
1857             if($year <= $y) {
1858                 break;
1859             }
1860         }
1862         $changes = dst_changes_for_year($y, $preset);
1864         if($changes === NULL) {
1865             continue;
1866         }
1867         if($changes['dst'] != 0) {
1868             $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
1869         }
1870         if($changes['std'] != 0) {
1871             $SESSION->dst_offsets[$changes['std']] = 0;
1872         }
1873     }
1875     // Put in a guard element at the top
1876     $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1877     $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1879     // Sort again
1880     krsort($SESSION->dst_offsets);
1882     return true;
1885 /**
1886  * Calculates the required DST change and returns a Timestamp Array
1887  *
1888  * @uses HOURSECS
1889  * @uses MINSECS
1890  * @param mixed $year Int or String Year to focus on
1891  * @param object $timezone Instatiated Timezone object
1892  * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
1893  */
1894 function dst_changes_for_year($year, $timezone) {
1896     if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1897         return NULL;
1898     }
1900     $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1901     $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1903     list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1904     list($std_hour, $std_min) = explode(':', $timezone->std_time);
1906     $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1907     $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
1909     // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1910     // This has the advantage of being able to have negative values for hour, i.e. for timezones
1911     // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1913     $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1914     $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
1916     return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1919 /**
1920  * Calculates the Daylight Saving Offest for a given date/time (timestamp)
1921  *
1922  * @global object
1923  * @param int $time must NOT be compensated at all, it has to be a pure timestamp
1924  * @return int
1925  */
1926 function dst_offset_on($time, $strtimezone = NULL) {
1927     global $SESSION;
1929     if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
1930         return 0;
1931     }
1933     reset($SESSION->dst_offsets);
1934     while(list($from, $offset) = each($SESSION->dst_offsets)) {
1935         if($from <= $time) {
1936             break;
1937         }
1938     }
1940     // This is the normal return path
1941     if($offset !== NULL) {
1942         return $offset;
1943     }
1945     // Reaching this point means we haven't calculated far enough, do it now:
1946     // Calculate extra DST changes if needed and recurse. The recursion always
1947     // moves toward the stopping condition, so will always end.
1949     if($from == 0) {
1950         // We need a year smaller than $SESSION->dst_range[0]
1951         if($SESSION->dst_range[0] == 1971) {
1952             return 0;
1953         }
1954         calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
1955         return dst_offset_on($time, $strtimezone);
1956     }
1957     else {
1958         // We need a year larger than $SESSION->dst_range[1]
1959         if($SESSION->dst_range[1] == 2035) {
1960             return 0;
1961         }
1962         calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
1963         return dst_offset_on($time, $strtimezone);
1964     }
1967 /**
1968  * ?
1969  *
1970  * @todo Document what this function does
1971  * @param int $startday
1972  * @param int $weekday
1973  * @param int $month
1974  * @param int $year
1975  * @return int
1976  */
1977 function find_day_in_month($startday, $weekday, $month, $year) {
1979     $daysinmonth = days_in_month($month, $year);
1981     if($weekday == -1) {
1982         // Don't care about weekday, so return:
1983         //    abs($startday) if $startday != -1
1984         //    $daysinmonth otherwise
1985         return ($startday == -1) ? $daysinmonth : abs($startday);
1986     }
1988     // From now on we 're looking for a specific weekday
1990     // Give "end of month" its actual value, since we know it
1991     if($startday == -1) {
1992         $startday = -1 * $daysinmonth;
1993     }
1995     // Starting from day $startday, the sign is the direction
1997     if($startday < 1) {
1999         $startday = abs($startday);
2000         $lastmonthweekday  = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2002         // This is the last such weekday of the month
2003         $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2004         if($lastinmonth > $daysinmonth) {
2005             $lastinmonth -= 7;
2006         }
2008         // Find the first such weekday <= $startday
2009         while($lastinmonth > $startday) {
2010             $lastinmonth -= 7;
2011         }
2013         return $lastinmonth;
2015     }
2016     else {
2018         $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
2020         $diff = $weekday - $indexweekday;
2021         if($diff < 0) {
2022             $diff += 7;
2023         }
2025         // This is the first such weekday of the month equal to or after $startday
2026         $firstfromindex = $startday + $diff;
2028         return $firstfromindex;
2030     }
2033 /**
2034  * Calculate the number of days in a given month
2035  *
2036  * @param int $month The month whose day count is sought
2037  * @param int $year The year of the month whose day count is sought
2038  * @return int
2039  */
2040 function days_in_month($month, $year) {
2041    return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
2044 /**
2045  * Calculate the position in the week of a specific calendar day
2046  *
2047  * @param int $day The day of the date whose position in the week is sought
2048  * @param int $month The month of the date whose position in the week is sought
2049  * @param int $year The year of the date whose position in the week is sought
2050  * @return int
2051  */
2052 function dayofweek($day, $month, $year) {
2053     // I wonder if this is any different from
2054     // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2055     return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
2058 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2060 /**
2061  * Returns full login url.
2062  *
2063  * @global object
2064  * @param bool $loginguest add login guest param, return false
2065  * @return string login url
2066  */
2067 function get_login_url($loginguest=false) {
2068     global $CFG;
2070     if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
2071         $loginguest = $loginguest ? '?loginguest=true' : '';
2072         $url = "$CFG->wwwroot/login/index.php$loginguest";
2074     } else {
2075         $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2076         $url = "$wwwroot/login/index.php";
2077     }
2079     return $url;
2082 /**
2083  * This function checks that the current user is logged in and has the
2084  * required privileges
2085  *
2086  * This function checks that the current user is logged in, and optionally
2087  * whether they are allowed to be in a particular course and view a particular
2088  * course module.
2089  * If they are not logged in, then it redirects them to the site login unless
2090  * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2091  * case they are automatically logged in as guests.
2092  * If $courseid is given and the user is not enrolled in that course then the
2093  * user is redirected to the course enrolment page.
2094  * If $cm is given and the coursemodule is hidden and the user is not a teacher
2095  * in the course then the user is redirected to the course home page.
2096  *
2097  * When $cm parameter specified, this function sets page layout to 'module'.
2098  * You need to change it manually later if some other layout needed.
2099  *
2100  * @global object
2101  * @global object
2102  * @global object
2103  * @global object
2104  * @global string
2105  * @global object
2106  * @global object
2107  * @global object
2108  * @uses SITEID Define
2109  * @param mixed $courseorid id of the course or course object
2110  * @param bool $autologinguest default true
2111  * @param object $cm course module object
2112  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2113  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2114  *             in order to keep redirects working properly. MDL-14495
2115  * @return mixed Void, exit, and die depending on path
2116  */
2117 function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsurltome=true) {
2118     global $CFG, $SESSION, $USER, $COURSE, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2120 /// setup global $COURSE, themes, language and locale
2121     if (!empty($courseorid)) {
2122         if (is_object($courseorid)) {
2123             $course = $courseorid;
2124         } else if ($courseorid == SITEID) {
2125             $course = clone($SITE);
2126         } else {
2127             $course = $DB->get_record('course', array('id' => $courseorid));
2128             if (!$course) {
2129                 throw new moodle_exception('invalidcourseid');
2130             }
2131         }
2132         if ($cm) {
2133             $PAGE->set_cm($cm, $course); // set's up global $COURSE
2134             $PAGE->set_pagelayout('incourse');
2135         } else {
2136             $PAGE->set_course($course); // set's up global $COURSE
2137         }
2138     } else {
2139         // do not touch global $COURSE via $PAGE->set_course() !!
2140     }
2142 /// If the user is not even logged in yet then make sure they are
2143     if (!isloggedin()) {
2144         //NOTE: $USER->site check was obsoleted by session test cookie,
2145         //      $USER->confirmed test is in login/index.php
2146         if ($setwantsurltome) {
2147             $SESSION->wantsurl = $FULLME;
2148         }
2149         if (!empty($_SERVER['HTTP_REFERER'])) {
2150             $SESSION->fromurl  = $_SERVER['HTTP_REFERER'];
2151         }
2152         if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
2153             $loginguest = true;
2154         } else {
2155             $loginguest = false;
2156         }
2157         redirect(get_login_url($loginguest));
2158         exit; // never reached
2159     }
2161 /// loginas as redirection if needed
2162     if ($COURSE->id != SITEID and session_is_loggedinas()) {
2163         if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2164             if ($USER->loginascontext->instanceid != $COURSE->id) {
2165                 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2166             }
2167         }
2168     }
2170 /// check whether the user should be changing password (but only if it is REALLY them)
2171     if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2172         $userauth = get_auth_plugin($USER->auth);
2173         if ($userauth->can_change_password()) {
2174             $SESSION->wantsurl = $FULLME;
2175             if ($changeurl = $userauth->change_password_url()) {
2176                 //use plugin custom url
2177                 redirect($changeurl);
2178             } else {
2179                 //use moodle internal method
2180                 if (empty($CFG->loginhttps)) {
2181                     redirect($CFG->wwwroot .'/login/change_password.php');
2182                 } else {
2183                     $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2184                     redirect($wwwroot .'/login/change_password.php');
2185                 }
2186             }
2187         } else {
2188             print_error('nopasswordchangeforced', 'auth');
2189         }
2190     }
2192 /// Check that the user account is properly set up
2193     if (user_not_fully_set_up($USER)) {
2194         $SESSION->wantsurl = $FULLME;
2195         redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2196     }
2198 /// Make sure the USER has a sesskey set up.  Used for checking script parameters.
2199     sesskey();
2201     // Check that the user has agreed to a site policy if there is one
2202     if (!empty($CFG->sitepolicy)) {
2203         if (!$USER->policyagreed) {
2204             $SESSION->wantsurl = $FULLME;
2205             redirect($CFG->wwwroot .'/user/policy.php');
2206         }
2207     }
2209     // Fetch the system context, we are going to use it a lot.
2210     $sysctx = get_context_instance(CONTEXT_SYSTEM);
2212 /// If the site is currently under maintenance, then print a message
2213     if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2214         print_maintenance_message();
2215     }
2217 /// groupmembersonly access control
2218     if (!empty($CFG->enablegroupmembersonly) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2219         if (isguestuser() or !groups_has_membership($cm)) {
2220             print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
2221         }
2222     }
2224     // Fetch the course context, and prefetch its child contexts
2225     $coursecontext = get_context_instance(CONTEXT_COURSE, $COURSE->id, MUST_EXIST);
2226     if ($cm) {
2227         $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2228     }
2230     // Conditional activity access control
2231     if (!empty($CFG->enableavailability) and $cm) {
2232         // We cache conditional access in session
2233         if (!isset($SESSION->conditionaccessok)) {
2234             $SESSION->conditionaccessok = array();
2235         }
2236         // If you have been allowed into the module once then you are allowed
2237         // in for rest of session, no need to do conditional checks
2238         if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
2239             // Get condition info (does a query for the availability table)
2240             require_once($CFG->libdir.'/conditionlib.php');
2241             $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
2242             // Check condition for user (this will do a query if the availability
2243             // information depends on grade or completion information)
2244             if ($ci->is_available($junk) || has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2245                 $SESSION->conditionaccessok[$cm->id] = true;
2246             } else {
2247                 print_error('activityiscurrentlyhidden');
2248             }
2249         }
2250     }
2252     if ($COURSE->id == SITEID) {
2253         /// Eliminate hidden site activities straight away
2254         if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2255             redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2256         }
2257         user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2258         return;
2260     } else {
2262         /// Check if the user can be in a particular course
2263         if (empty($USER->access['rsw'][$coursecontext->path])) {
2264             //
2265             // MDL-13900 - If the course or the parent category are hidden
2266             // and the user hasn't the 'course:viewhiddencourses' capability, prevent access
2267             //
2268             if ( !($COURSE->visible && course_parent_visible($COURSE)) && !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2269                 echo $OUTPUT->header();
2270                 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2271             }
2272         }
2274         if (is_enrolled($coursecontext) or is_viewing($coursecontext)) {
2275             // Enrolled user or allowed to visit course (managers, inspectors, etc.)
2276             if (session_is_loggedinas()) {   // Make sure the REAL person can also access this course
2277                 $realuser = session_get_realuser();
2278                 if (!is_enrolled($coursecontext, $realuser->id) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2279                     echo $OUTPUT->header();
2280                     notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2281                 }
2282             }
2284             // Make sure they can read this activity too, if specified
2285             if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2286                 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
2287             }
2288             user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2289             return;   // User is allowed to see this course
2291         } else {
2292             // guest access
2293             switch ($COURSE->guest) {    /// Check course policy about guest access
2295                 case 1:    /// Guests always allowed
2296                     if ($cm and !$cm->visible) { // Not allowed to see module, send to course page
2297                         redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
2298                                  get_string('activityiscurrentlyhidden'));
2299                     }
2301                     if ($USER->username != 'guest' and !empty($CFG->guestroleid)) {
2302                         // Non-guests who don't currently have access, check if they can be allowed in as a guest
2303                         // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
2304                         $USER->access = load_temp_role($coursecontext, $CFG->guestroleid, $USER->access);
2305                     }
2307                     user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2308                     return;   // User is allowed to see this course
2310                 case 2:    /// Guests allowed with key
2311                     if (!empty($USER->enrolkey[$COURSE->id])) {   // Set by enrol/manual/enrol.php
2312                         user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2313                         return true;
2314                     }
2315                     //  otherwise drop through to logic below (--> enrol.php)
2316                     break;
2318                 default:    /// Guests not allowed
2319                     $strloggedinasguest = get_string('loggedinasguest');
2320                     $PAGE->navbar->add($strloggedinasguest);
2321                     echo $OUTPUT->header();
2322                     if (empty($USER->access['rsw'][$coursecontext->path])) {  // Normal guest
2323                         notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url());
2324                     } else {
2325                         echo $OUTPUT->notification(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
2326                         echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
2327                         echo $OUTPUT->footer();
2328                         exit;
2329                     }
2330                     break;
2331             }
2332         }
2334         // Currently not enrolled in the course, so see if they want to enrol
2335         $SESSION->wantsurl = $FULLME;
2336         redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
2337         die;
2338     }
2342 /**
2343  * This function just makes sure a user is logged out.
2344  *
2345  * @global object
2346  */
2347 function require_logout() {
2348     global $USER;
2350     if (isloggedin()) {
2351         add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2353         $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2354         foreach($authsequence as $authname) {
2355             $authplugin = get_auth_plugin($authname);
2356             $authplugin->prelogout_hook();
2357         }
2358     }
2360     session_get_instance()->terminate_current();
2363 /**
2364  * Weaker version of require_login()
2365  *
2366  * This is a weaker version of {@link require_login()} which only requires login
2367  * when called from within a course rather than the site page, unless
2368  * the forcelogin option is turned on.
2369  * @see require_login()
2370  *
2371  * @global object
2372  * @param mixed $courseorid The course object or id in question
2373  * @param bool $autologinguest Allow autologin guests if that is wanted
2374  * @param object $cm Course activity module if known
2375  * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2376  *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2377  *             in order to keep redirects working properly. MDL-14495
2378  */
2379 function require_course_login($courseorid, $autologinguest=true, $cm=null, $setwantsurltome=true) {
2380     global $CFG, $PAGE, $SITE;
2381     if (!empty($CFG->forcelogin)) {
2382         // login required for both SITE and courses
2383         require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2385     } else if (!empty($cm) and !$cm->visible) {
2386         // always login for hidden activities
2387         require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2389     } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2390           or (!is_object($courseorid) and $courseorid == SITEID)) {
2391               //login for SITE not required
2392         if ($cm and empty($cm->visible)) {
2393             // hidden activities are not accessible without login
2394             require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2395         } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2396             // not-logged-in users do not have any group membership
2397             require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2398         } else {
2399             // We still need to instatiate PAGE vars properly so that things
2400             // that rely on it like navigation function correctly.
2401             if (!empty($courseorid)) {
2402                 if (is_object($courseorid)) {
2403                     $course = $courseorid;
2404                 } else {
2405                     $course = clone($SITE);
2406                 }
2407                 if ($cm) {
2408                     $PAGE->set_cm($cm, $course);
2409                     $PAGE->set_pagelayout('incourse');
2410                 } else {
2411                     $PAGE->set_course($course);
2412                 }
2413             } else {
2414                 // If $PAGE->course, and hence $PAGE->context, have not already been set
2415                 // up properly, set them up now.
2416                 $PAGE->set_course($PAGE->course);
2417             }
2418             //TODO: verify conditional activities here
2419             user_accesstime_log(SITEID);
2420             return;
2421         }
2423     } else {
2424         // course login always required
2425         require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2426     }
2429 /**
2430  * Require key login. Function terminates with error if key not found or incorrect.
2431  *
2432  * @global object
2433  * @global object
2434  * @global object
2435  * @global object
2436  * @uses NO_MOODLE_COOKIES
2437  * @uses PARAM_ALPHANUM
2438  * @param string $script unique script identifier
2439  * @param int $instance optional instance id
2440  * @return int Instance ID
2441  */
2442 function require_user_key_login($script, $instance=null) {
2443     global $USER, $SESSION, $CFG, $DB;
2445     if (!NO_MOODLE_COOKIES) {
2446         print_error('sessioncookiesdisable');
2447     }
2449 /// extra safety
2450     @session_write_close();
2452     $keyvalue = required_param('key', PARAM_ALPHANUM);
2454     if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2455         print_error('invalidkey');
2456     }
2458     if (!empty($key->validuntil) and $key->validuntil < time()) {
2459         print_error('expiredkey');
2460     }
2462     if ($key->iprestriction) {
2463         $remoteaddr = getremoteaddr();
2464         if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2465             print_error('ipmismatch');
2466         }
2467     }
2469     if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2470         print_error('invaliduserid');
2471     }
2473 /// emulate normal session
2474     session_set_user($user);
2476 /// note we are not using normal login
2477     if (!defined('USER_KEY_LOGIN')) {
2478         define('USER_KEY_LOGIN', true);
2479     }
2481 /// return isntance id - it might be empty
2482     return $key->instance;
2485 /**
2486  * Creates a new private user access key.
2487  *
2488  * @global object
2489  * @param string $script unique target identifier
2490  * @param int $userid
2491  * @param int $instance optional instance id
2492  * @param string $iprestriction optional ip restricted access
2493  * @param timestamp $validuntil key valid only until given data
2494  * @return string access key value
2495  */
2496 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2497     global $DB;
2499     $key = new object();
2500     $key->script        = $script;
2501     $key->userid        = $userid;
2502     $key->instance      = $instance;
2503     $key->iprestriction = $iprestriction;
2504     $key->validuntil    = $validuntil;
2505     $key->timecreated   = time();
2507     $key->value         = md5($userid.'_'.time().random_string(40)); // something long and unique
2508     while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
2509         // must be unique
2510         $key->value     = md5($userid.'_'.time().random_string(40));
2511     }
2512     $DB->insert_record('user_private_key', $key);
2513     return $key->value;
2516 /**
2517  * Modify the user table by setting the currently logged in user's
2518  * last login to now.
2519  *
2520  * @global object
2521  * @global object
2522  * @return bool Always returns true
2523  */
2524 function update_user_login_times() {
2525     global $USER, $DB;
2527     $user = new object();
2528     $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2529     $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2531     $user->id = $USER->id;
2533     $DB->update_record('user', $user);
2534     return true;
2537 /**
2538  * Determines if a user has completed setting up their account.
2539  *
2540  * @param user $user A {@link $USER} object to test for the existance of a valid name and email
2541  * @return bool
2542  */
2543 function user_not_fully_set_up($user) {
2544     return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
2547 /**
2548  * Check whether the user has exceeded the bounce threshold
2549  *
2550  * @global object
2551  * @global object
2552  * @param user $user A {@link $USER} object
2553  * @return bool true=>User has exceeded bounce threshold
2554  */
2555 function over_bounce_threshold($user) {
2556     global $CFG, $DB;
2558     if (empty($CFG->handlebounces)) {
2559         return false;
2560     }
2562     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2563         return false;
2564     }
2566     // set sensible defaults
2567     if (empty($CFG->minbounces)) {
2568         $CFG->minbounces = 10;
2569     }
2570     if (empty($CFG->bounceratio)) {
2571         $CFG->bounceratio = .20;
2572     }
2573     $bouncecount = 0;
2574     $sendcount = 0;
2575     if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2576         $bouncecount = $bounce->value;
2577     }
2578     if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2579         $sendcount = $send->value;
2580     }
2581     return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2584 /**
2585  * Used to increment or reset email sent count
2586  *
2587  * @global object
2588  * @param user $user object containing an id
2589  * @param bool $reset will reset the count to 0
2590  * @return void
2591  */
2592 function set_send_count($user,$reset=false) {
2593     global $DB;
2595     if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2596         return;
2597     }
2599     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2600         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2601         $DB->update_record('user_preferences', $pref);
2602     }
2603     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2604         // make a new one
2605         $pref = new object();
2606         $pref->name   = 'email_send_count';
2607         $pref->value  = 1;
2608         $pref->userid = $user->id;
2609         $DB->insert_record('user_preferences', $pref, false);
2610     }
2613 /**
2614  * Increment or reset user's email bounce count
2615  *
2616  * @global object
2617  * @param user $user object containing an id
2618  * @param bool $reset will reset the count to 0
2619  */
2620 function set_bounce_count($user,$reset=false) {
2621     global $DB;
2623     if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2624         $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2625         $DB->update_record('user_preferences', $pref);
2626     }
2627     else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2628         // make a new one
2629         $pref = new object();
2630         $pref->name   = 'email_bounce_count';
2631         $pref->value  = 1;
2632         $pref->userid = $user->id;
2633         $DB->insert_record('user_preferences', $pref, false);
2634     }
2637 /**
2638  * Keeps track of login attempts
2639  *
2640  * @global object
2641  */
2642 function update_login_count() {
2643     global $SESSION;
2645     $max_logins = 10;
2647     if (empty($SESSION->logincount)) {
2648         $SESSION->logincount = 1;
2649     } else {
2650         $SESSION->logincount++;
2651     }
2653     if ($SESSION->logincount > $max_logins) {
2654         unset($SESSION->wantsurl);
2655         print_error('errortoomanylogins');
2656     }
2659 /**
2660  * Resets login attempts
2661  *
2662  * @global object
2663  */
2664 function reset_login_count() {
2665     global $SESSION;
2667     $SESSION->logincount = 0;
2670 /**
2671  * Sync all meta courses
2672  * Goes through all enrolment records for the courses inside all metacourses and syncs with them.
2673  * @see sync_metacourse()
2674  *
2675  * @global object
2676  */
2677 function sync_metacourses() {
2678     global $DB;
2680     if (!$courses = $DB->get_records('course', array('metacourse'=>1))) {
2681         return;
2682     }
2684     foreach ($courses as $course) {
2685         sync_metacourse($course);
2686     }
2689 /**
2690  * Returns reference to full info about modules in course (including visibility).
2691  * Cached and as fast as possible (0 or 1 db query).
2692  *
2693  * @global object
2694  * @global object
2695  * @global object
2696  * @uses CONTEXT_MODULE
2697  * @uses MAX_MODINFO_CACHE_SIZE
2698  * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
2699  * @param int $userid Defaults to current user id
2700  * @return mixed courseinfo object or nothing if resetting
2701  */
2702 function &get_fast_modinfo(&$course, $userid=0) {
2703     global $CFG, $USER, $DB;
2704     require_once($CFG->dirroot.'/course/lib.php');
2706     if (!empty($CFG->enableavailability)) {
2707         require_once($CFG->libdir.'/conditionlib.php');
2708     }
2710     static $cache = array();
2712     if ($course === 'reset') {
2713         $cache = array();
2714         $nothing = null;
2715         return $nothing; // we must return some reference
2716     }
2718     if (empty($userid)) {
2719         $userid = $USER->id;
2720     }
2722     if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
2723         return $cache[$course->id];
2724     }
2726     if (empty($course->modinfo)) {
2727         // no modinfo yet - load it
2728         rebuild_course_cache($course->id);
2729         $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2730     }
2732     $modinfo = new object();
2733     $modinfo->courseid  = $course->id;
2734     $modinfo->userid    = $userid;
2735     $modinfo->sections  = array();
2736     $modinfo->cms       = array();
2737     $modinfo->instances = array();
2738     $modinfo->groups    = null; // loaded only when really needed - the only one db query
2740     $info = unserialize($course->modinfo);
2741     if (!is_array($info)) {
2742         // hmm, something is wrong - lets try to fix it
2743         rebuild_course_cache($course->id);
2744         $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2745         $info = unserialize($course->modinfo);
2746         if (!is_array($info)) {
2747             return $modinfo;
2748         }
2749     }
2751     if ($info) {
2752         // detect if upgrade required
2753         $first = reset($info);
2754         if (!isset($first->id)) {
2755             rebuild_course_cache($course->id);
2756             $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2757             $info = unserialize($course->modinfo);
2758             if (!is_array($info)) {
2759                 return $modinfo;
2760             }
2761         }
2762     }
2764     $modlurals = array();
2766     // If we haven't already preloaded contexts for the course, do it now
2767     preload_course_contexts($course->id);
2769     foreach ($info as $mod) {
2770         if (empty($mod->name)) {
2771             // something is wrong here
2772             continue;
2773         }
2774         // reconstruct minimalistic $cm
2775         $cm = new object();
2776         $cm->id               = $mod->cm;
2777         $cm->instance         = $mod->id;
2778         $cm->course           = $course->id;
2779         $cm->modname          = $mod->mod;
2780         $cm->name             = $mod->name;
2781         $cm->visible          = $mod->visible;
2782         $cm->sectionnum       = $mod->section;
2783         $cm->groupmode        = $mod->groupmode;
2784         $cm->groupingid       = $mod->groupingid;
2785         $cm->groupmembersonly = $mod->groupmembersonly;
2786         $cm->indent           = $mod->indent;
2787         $cm->completion       = $mod->completion;
2788         $cm->extra            = isset($mod->extra) ? $mod->extra : '';
2789         $cm->icon             = isset($mod->icon) ? $mod->icon : '';
2790         $cm->iconcomponent    = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
2791         $cm->uservisible      = true;
2792         if(!empty($CFG->enableavailability)) {
2793             // We must have completion information from modinfo. If it's not
2794             // there, cache needs rebuilding
2795             if(!isset($mod->availablefrom)) {
2796                 debugging('enableavailability option was changed; rebuilding '.
2797                     'cache for course '.$course->id);
2798                 rebuild_course_cache($course->id,true);
2799                 // Re-enter this routine to do it all properly
2800                 return get_fast_modinfo($course,$userid);
2801             }
2802             $cm->availablefrom    = $mod->availablefrom;
2803             $cm->availableuntil   = $mod->availableuntil;
2804             $cm->showavailability = $mod->showavailability;
2805             $cm->conditionscompletion = $mod->conditionscompletion;
2806             $cm->conditionsgrade  = $mod->conditionsgrade;
2807         }
2809         // preload long names plurals and also check module is installed properly
2810         if (!isset($modlurals[$cm->modname])) {
2811             if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
2812                 continue;
2813             }
2814             $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
2815         }
2816         $cm->modplural = $modlurals[$cm->modname];
2817         $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id);
2819         if(!empty($CFG->enableavailability)) {
2820             // Unfortunately the next call really wants to call
2821             // get_fast_modinfo, but that would be recursive, so we fake up a
2822             // modinfo for it already
2823             if(empty($minimalmodinfo)) {
2824                 $minimalmodinfo=new stdClass();
2825                 $minimalmodinfo->cms=array();
2826                 foreach($info as $mod) {
2827                     if (empty($mod->name)) {
2828                         // something is wrong here
2829                         continue;
2830                     }
2831                     $minimalcm = new stdClass();
2832                     $minimalcm->id = $mod->cm;
2833                     $minimalcm->name = $mod->name;
2834                     $minimalmodinfo->cms[$minimalcm->id]=$minimalcm;
2835                 }
2836             }
2838             // Get availability information
2839             $ci = new condition_info($cm);
2840             $cm->available=$ci->is_available($cm->availableinfo, true, $userid, $minimalmodinfo);
2841         } else {
2842             $cm->available=true;
2843         }
2844         if ((!$cm->visible or !$cm->available) and !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
2845             $cm->uservisible = false;
2847         } else if (!empty($CFG->enablegroupmembersonly) and !empty($cm->groupmembersonly)
2848                 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
2849             if (is_null($modinfo->groups)) {
2850                 $modinfo->groups = groups_get_user_groups($course->id, $userid);
2851             }
2852             if (empty($modinfo->groups[$cm->groupingid])) {
2853                 $cm->uservisible = false;
2854             }
2855         }
2857         if (!isset($modinfo->instances[$cm->modname])) {
2858             $modinfo->instances[$cm->modname] = array();
2859         }
2860         $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
2861         $modinfo->cms[$cm->id] =& $cm;
2863         // reconstruct sections
2864         if (!isset($modinfo->sections[$cm->sectionnum])) {
2865             $modinfo->sections[$cm->sectionnum] = array();
2866         }
2867         $modinfo->sections[$cm->sectionnum][] = $cm->id;
2869         unset($cm);
2870     }
2872     unset($cache[$course->id]); // prevent potential reference problems when switching users
2873     $cache[$course->id] = $modinfo;
2875     // Ensure cache does not use too much RAM
2876     if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
2877         reset($cache);
2878         $key = key($cache);
2879         unset($cache[$key]);
2880     }
2882     return $cache[$course->id];
2885 /**
2886  * Goes through all enrolment records for the courses inside the metacourse and sync with them.
2887  *
2888  * @todo finish timeend and timestart maybe we could rely on cron
2889  *       job to do the cleaning from time to time
2890  *
2891  * @global object
2892  * @global object
2893  * @uses CONTEXT_COURSE
2894  * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
2895  * @return bool Success
2896  */
2897 function sync_metacourse($course) {
2898     global $CFG, $DB;
2900     // Check the course is valid.
2901     if (!is_object($course)) {
2902         if (!$course = $DB->get_record('course', array('id'=>$course))) {
2903             return false; // invalid course id
2904         }
2905     }
2907     // Check that we actually have a metacourse.
2908     if (empty($course->metacourse)) {
2909         return false;
2910     }
2912     // Get a list of roles that should not be synced.
2913     if (!empty($CFG->nonmetacoursesyncroleids)) {
2914         $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
2915     } else {
2916         $roleexclusions = '';
2917     }
2919     // Get the context of the metacourse.
2920     $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
2922     // We do not ever want to unassign the list of metacourse manager, so get a list of them.
2923     if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
2924         $managers = array_keys($users);
2925     } else {
2926         $managers = array();
2927     }
2929     // Get assignments of a user to a role that exist in a child course, but
2930     // not in the meta coure. That is, get a list of the assignments that need to be made.
2931     if (!$assignments = $DB->get_records_sql("
2932             SELECT ra.id, ra.roleid, ra.userid
2933               FROM {role_assignments} ra, {context} con, {course_meta} cm
2934              WHERE ra.contextid = con.id AND
2935                    con.contextlevel = ".CONTEXT_COURSE." AND
2936                    con.instanceid = cm.child_course AND
2937                    cm.parent_course = ? AND
2938                    $roleexclusions
2939                    NOT EXISTS (
2940                      SELECT 1
2941                        FROM {role_assignments} ra2
2942                       WHERE ra2.userid = ra.userid AND
2943                             ra2.roleid = ra.roleid AND
2944                             ra2.contextid = ?
2945                   )", array($course->id, $context->id))) {
2946         $assignments = array();
2947     }
2949     // Get assignments of a user to a role that exist in the meta course, but
2950     // not in any child courses. That is, get a list of the unassignments that need to be made.
2951     if (!$unassignments = $DB->get_records_sql("
2952             SELECT ra.id, ra.roleid, ra.userid
2953               FROM {role_assignments} ra
2954              WHERE ra.contextid = ? AND
2955                    $roleexclusions
2956                    NOT EXISTS (
2957                     SELECT 1
2958                       FROM {role_assignments} ra2, {context} con2, {course_meta} cm
2959                     WHERE ra2.userid = ra.userid AND
2960                           ra2.roleid = ra.roleid AND
2961                           ra2.contextid = con2.id AND
2962                           con2.contextlevel = " . CONTEXT_COURSE . " AND
2963                           con2.instanceid = cm.child_course AND
2964                           cm.parent_course = ?
2965                   )", array($context->id, $course->id))) {
2966         $unassignments = array();
2967     }
2969     $success = true;
2971     // Make the unassignments, if they are not managers.
2972     foreach ($unassignments as $unassignment) {
2973         if (!in_array($unassignment->userid, $managers)) {
2974             $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
2975         }
2976     }
2978     // Make the assignments.
2979     foreach ($assignments as $assignment) {
2980         $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id, 0, 0) && $success;
2981     }
2983     return $success;
2985 // TODO: finish timeend and timestart
2986 // maybe we could rely on cron job to do the cleaning from time to time
2989 /**
2990  * Adds a record to the metacourse table and calls sync_metacoures
2991  *
2992  * @global object
2993  * @param int $metacourseid The Metacourse ID for the metacourse to add to
2994  * @param int $courseid The Course ID of the course to add
2995  * @return bool Success
2996  */
2997 function add_to_metacourse ($metacourseid, $courseid) {
2998     global $DB;
3000     if (!$metacourse = $DB->get_record("course", array("id"=>$metacourseid))) {
3001         return false;
3002     }
3004     if (!$course = $DB->get_record("course", array("id"=>$courseid))) {
3005         return false;
3006     }
3008     if (!$record = $DB->get_record("course_meta", array("parent_course"=>$metacourseid, "child_course"=>$courseid))) {
3009         $rec = new object();
3010         $rec->parent_course = $metacourseid;
3011         $rec->child_course  = $courseid;
3012         $DB->insert_record('course_meta', $rec);
3013         return sync_metacourse($metacourseid);
3014     }
3015     return true;
3019 /**
3020  * Removes the record from the metacourse table and calls sync_metacourse
3021  *
3022  * @global object
3023  * @param int $metacourseid The Metacourse ID for the metacourse to remove from
3024  * @param int $courseid The Course ID of the course to remove
3025  * @return bool Success
3026  */
3027 function remove_from_metacourse($metacourseid, $courseid) {
3028     global $DB;
3030     if ($DB->delete_records('course_meta', array('parent_course'=>$metacourseid, 'child_course'=>$courseid))) {
3031         return sync_metacourse($metacourseid);
3032     }
3033     return false;
3036 /**
3037  * Determines if the currently logged in user is in editing mode.
3038  * Note: originally this function had $userid parameter - it was not usable anyway
3039  *
3040  * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3041  * @todo Deprecated function remove when ready
3042  *
3043  * @global object
3044  * @uses DEBUG_DEVELOPER
3045  * @return bool
3046  */
3047 function isediting() {
3048     global $PAGE;
3049     debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3050     return $PAGE->user_is_editing();
3053 /**
3054  * Determines if the logged in user is currently moving an activity
3055  *
3056  * @global object
3057  * @param int $courseid The id of the course being tested
3058  * @return bool
3059  */
3060 function ismoving($courseid) {
3061     global $USER;
3063     if (!empty($USER->activitycopy)) {
3064         return ($USER->activitycopycourse == $courseid);
3065     }
3066     return false;
3069 /**
3070  * Returns a persons full name
3071  *
3072  * Given an object containing firstname and lastname
3073  * values, this function returns a string with the
3074  * full name of the person.
3075  * The result may depend on system settings
3076  * or language.  'override' will force both names
3077  * to be used even if system settings specify one.
3078  *
3079  * @global object
3080  * @global object
3081  * @param object $user A {@link $USER} object to get full name of
3082  * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3083  * @return string
3084  */
3085 function fullname($user, $override=false) {
3086     global $CFG, $SESSION;
3088     if (!isset($user->firstname) and !isset($user->lastname)) {
3089         return '';
3090     }
3092     if (!$override) {
3093         if (!empty($CFG->forcefirstname)) {
3094             $user->firstname = $CFG->forcefirstname;
3095         }
3096         if (!empty($CFG->forcelastname)) {
3097             $user->lastname = $CFG->forcelastname;
3098         }
3099     }
3101     if (!empty($SESSION->fullnamedisplay)) {
3102         $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3103     }
3105     if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3106         return $user->firstname .' '. $user->lastname;
3108     } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3109         return $user->lastname .' '. $user->firstname;
3111     } else if ($CFG->fullnamedisplay == 'firstname') {
3112         if ($override) {
3113             return get_string('fullnamedisplay', '', $user);
3114         } else {
3115             return $user->firstname;
3116         }
3117     }
3119     return get_string('fullnamedisplay', '', $user);
3122 /**
3123  * Returns whether a given authentication plugin exists.
3124  *
3125  * @global object
3126  * @param string $auth Form of authentication to check for. Defaults to the
3127  *        global setting in {@link $CFG}.
3128  * @return boolean Whether the plugin is available.
3129  */
3130 function exists_auth_plugin($auth) {
3131     global $CFG;
3133     if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3134         return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3135     }
3136     return false;
3139 /**
3140  * Checks if a given plugin is in the list of enabled authentication plugins.
3141  *
3142  * @param string $auth Authentication plugin.
3143  * @return boolean Whether the plugin is enabled.
3144  */
3145 function is_enabled_auth($auth) {
3146     if (empty($auth)) {
3147         return false;
3148     }
3150     $enabled = get_enabled_auth_plugins();
3152     return in_array($auth, $enabled);
3155 /**
3156  * Returns an authentication plugin instance.
3157  *
3158  * @global object
3159  * @param string $auth name of authentication plugin
3160  * @return auth_plugin_base An instance of the required authentication plugin.
3161  */
3162 function get_auth_plugin($auth) {
3163     global $CFG;
3165     // check the plugin exists first
3166     if (! exists_auth_plugin($auth)) {
3167         print_error('authpluginnotfound', 'debug', '', $auth);
3168     }
3170     // return auth plugin instance
3171     require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3172     $class = "auth_plugin_$auth";
3173     return new $class;
3176 /**
3177  * Returns array of active auth plugins.
3178  *
3179  * @param bool $fix fix $CFG->auth if needed
3180  * @return array
3181  */
3182 function get_enabled_auth_plugins($fix=false) {
3183     global $CFG;
3185     $default = array('manual', 'nologin');
3187     if (empty($CFG->auth)) {
3188         $auths = array();
3189     } else {
3190         $auths = explode(',', $CFG->auth);
3191     }
3193     if ($fix) {
3194         $auths = array_unique($auths);
3195         foreach($auths as $k=>$authname) {
3196             if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3197                 unset($auths[$k]);
3198             }
3199         }
3200         $newconfig = implode(',', $auths);
3201         if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3202             set_config('auth', $newconfig);
3203         }
3204     }
3206     return (array_merge($default, $auths));
3209 /**
3210  * Returns true if an internal authentication method is being used.
3211  * if method not specified then, global default is assumed
3212  *
3213  * @param string $auth Form of authentication required
3214  * @return bool
3215  */
3216 function is_internal_auth($auth) {
3217     $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3218     return $authplugin->is_internal();
3221 /**
3222  * Returns true if the user is a 'restored' one
3223  *
3224  * Used in the login process to inform the user
3225  * and allow him/her to reset the password
3226  *
3227  * @uses $CFG
3228  * @uses $DB
3229  * @param string $username username to be checked
3230  * @return bool
3231  */
3232 function is_restored_user($username) {
3233     global $CFG, $DB;
3235     return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3238 /**
3239  * Returns an array of user fields
3240  *
3241  * @return array User field/column names
3242  */
3243 function get_user_fieldnames() {
3244     global $DB;
3246     $fieldarray = $DB->get_columns('user');
3247     unset($fieldarray['id']);
3248     $fieldarray = array_keys($fieldarray);
3250     return $fieldarray;
3253 /**
3254  * Creates a bare-bones user record
3255  *
3256  * @todo Outline auth types and provide code example
3257  *
3258  * @global object
3259  * @global object
3260  * @param string $username New user's username to add to record
3261  * @param string $password New user's password to add to record
3262  * @param string $auth Form of authentication required
3263  * @return object A {@link $USER} object
3264  */
3265 function create_user_record($username, $password, $auth='manual') {
3266     global $CFG, $DB;
3268     //just in case check text case
3269     $username = trim(moodle_strtolower($username));
3271     $authplugin = get_auth_plugin($auth);
3273     $newuser = new object();
3275     if ($newinfo = $authplugin->get_userinfo($username)) {
3276         $newinfo = truncate_userinfo($newinfo);
3277         foreach ($newinfo as $key => $value){
3278             $newuser->$key = $value;
3279         }
3280     }
3282     if (!empty($newuser->email)) {
3283         if (email_is_not_allowed($newuser->email)) {
3284             unset($newuser->email);
3285         }
3286     }
3288     if (!isset($newuser->city)) {
3289         $newuser->city = '';
3290     }
3292     $newuser->auth = $auth;
3293     $newuser->username = $username;
3295     // fix for MDL-8480
3296     // user CFG lang for user if $newuser->lang is empty
3297     // or $user->lang is not an installed language
3298     if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3299         $newuser->lang = $CFG->lang;
3300     }
3301     $newuser->confirmed = 1;
3302     $newuser->lastip = getremoteaddr();
3303     $newuser->timemodified = time();
3304     $newuser->mnethostid = $CFG->mnet_localhost_id;
3306     $DB->insert_record('user', $newuser);
3307     $user = get_complete_user_data('username', $newuser->username);
3308     if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3309         set_user_preference('auth_forcepasswordchange', 1, $user->id);
3310     }
3311     update_internal_user_password($user, $password);
3312     return $user;
3315 /**
3316  * Will update a local user record from an external source
3317  *
3318  * @global object
3319  * @param string $username New user's username to add to record
3320  * @param string $authplugin Unused
3321  * @return user A {@link $USER} object
3322  */
3323 function update_user_record($username, $authplugin) {
3324     global $DB;
3326     $username = trim(moodle_strtolower($username)); /// just in case check text case
3328     $oldinfo = $DB->get_record('user', array('username'=>$username), 'username, auth');
3329     $userauth = get_auth_plugin($oldinfo->auth);
3331     if ($newinfo = $userauth->get_userinfo($username)) {
3332         $newinfo = truncate_userinfo($newinfo);
3333         foreach ($newinfo as $key => $value){
3334             if ($key === 'username') {
3335                 // 'username' is not a mapped updateable/lockable field, so skip it.
3336                 continue;
3337             }
3338             $confval = $userauth->config->{'field_updatelocal_' . $key};
3339             $lockval = $userauth->config->{'field_lock_' . $key};
3340             if (empty($confval) || empty($lockval)) {
3341                 continue;
3342             }
3343             if ($confval === 'onlogin') {
3344                 // MDL-4207 Don't overwrite modified user profile values with
3345                 // empty LDAP values when 'unlocked if empty' is set. The purpose
3346                 // of the setting 'unlocked if empty' is to allow the user to fill
3347                 // in a value for the selected field _if LDAP is giving
3348                 // nothing_ for this field. Thus it makes sense to let this value
3349                 // stand in until LDAP is giving a value for this field.
3350                 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3351                     $DB->set_field('user', $key, $value, array('username'=>$username));
3352                 }
3353             }
3354         }
3355     }
3357     return get_complete_user_data('username', $username);
3360 /**
3361  * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3362  * which may have large fields
3363  *
3364  * @todo Add vartype handling to ensure $info is an array
3365  *
3366  * @param array $info Array of user properties to truncate if needed
3367  * @return array The now truncated information that was passed in
3368  */
3369 function truncate_userinfo($info) {
3370     // define the limits
3371     $limit = array(
3372                     'username'    => 100,
3373                     'idnumber'    => 255,
3374                     'firstname'   => 100,
3375                     'lastname'    => 100,
3376                     'email'       => 100,
3377                     'icq'         =>  15,
3378                     'phone1'      =>  20,
3379                     'phone2'      =>  20,
3380                     'institution' =>  40,
3381                     'department'  =>  30,
3382                     'address'     =>  70,
3383                     'city'        =>  20,
3384                     'country'     =>   2,
3385                     'url'         => 255,
3386                     );
3388     // apply where needed
3389     foreach (array_keys($info) as $key) {
3390         if (!empty($limit[$key])) {
3391             $info[$key] = trim(substr($info[$key],0, $limit[$key]));
3392         }
3393     }
3395     return $info;
3398 /**
3399  * Marks user deleted in internal user database and notifies the auth plugin.
3400  * Also unenrols user from all roles and does other cleanup.
3401  *
3402  * @todo Decide if this transaction is really needed (look for internal TODO:)
3403  *
3404  * @global object
3405  * @global object
3406  * @param object $user Userobject before delete    (without system magic quotes)
3407  * @return boolean success
3408  */
3409 function delete_user($user) {
3410     global $CFG, $DB;
3411     require_once($CFG->libdir.'/grouplib.php');
3412     require_once($CFG->libdir.'/gradelib.php');
3413     require_once($CFG->dirroot.'/message/lib.php');
3415     // delete all grades - backup is kept in grade_grades_history table
3416     if ($grades = grade_grade::fetch_all(array('userid'=>$user->id))) {
3417         foreach ($grades as $grade) {
3418             $grade->delete('userdelete');
3419         }
3420     }
3422     //move unread messages from this user to read
3423     message_move_userfrom_unread2read($user->id);
3425     // remove from all groups
3426     $DB->delete_records('groups_members', array('userid'=>$user->id));
3428     // unenrol from all roles in all contexts
3429     role_unassign(0, $user->id); // this might be slow but it is really needed - modules might do some extra cleanup!
3431     // now do a final accesslib cleanup - removes all role assingments in user context and context itself
3432     delete_context(CONTEXT_USER, $user->id);
3434     require_once($CFG->dirroot.'/tag/lib.php');
3435     tag_set('user', $user->id, array());
3437     // workaround for bulk deletes of users with the same email address
3438     $delname = "$user->email.".time();
3439     while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3440         $delname++;
3441     }
3443     // mark internal user record as "deleted"
3444     $updateuser = new object();
3445     $updateuser->id           = $user->id;
3446     $updateuser->deleted      = 1;
3447     $updateuser->username     = $delname;            // Remember it just in case
3448     $updateuser->email        = md5($user->username);// Store hash of username, useful importing/restoring users
3449     $updateuser->idnumber     = '';                  // Clear this field to free it up
3450     $updateuser->timemodified = time();
3452     $DB->update_record('user', $updateuser);
3454     // notify auth plugin - do not block the delete even when plugin fails
3455     $authplugin = get_auth_plugin($user->auth);
3456     $authplugin->user_delete($user);
3458     events_trigger('user_deleted', $user);
3460     return true;
3463 /**
3464  * Retrieve the guest user object
3465  *
3466  * @global object
3467  * @global object
3468  * @return user A {@link $USER} object
3469  */
3470 function guest_user() {
3471     global $CFG, $DB;
3473     if ($newuser = $DB->get_record('user', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
3474         $newuser->confirmed = 1;
3475         $newuser->lang = $CFG->lang;
3476         $newuser->lastip = getremoteaddr();
3477     }
3479     return $newuser;
3482 /**
3483  * Authenticates a user against the chosen authentication mechanism
3484  *
3485  * Given a username and password, this function looks them
3486  * up using the currently selected authentication mechanism,
3487  * and if the authentication is successful, it returns a
3488  * valid $user object from the 'user' table.
3489  *
3490  * Uses auth_ functions from the currently active auth module
3491  *
3492  * After authenticate_user_login() returns success, you will need to
3493  * log that the user has logged in, and call complete_user_login() to set
3494  * the session up.
3495  *
3496  * @global object
3497  * @global object
3498  * @param string $username  User's username
3499  * @param string $password  User's password
3500  * @return user|flase A {@link $USER} object or false if error
3501  */
3502 function authenticate_user_login($username, $password) {
3503     global $CFG, $DB, $OUTPUT;
3505     $authsenabled = get_enabled_auth_plugins();
3507     if ($user = get_complete_user_data('username', $username)) {
3508         $auth = empty($user->auth) ? 'manual' : $user->auth;  // use manual if auth not set
3509         if ($auth=='nologin' or !is_enabled_auth($auth)) {
3510             add_to_log(0, 'login', 'error', 'index.php', $username);
3511             error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Disabled Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3512             return false;
3513         }
3514         $auths = array($auth);
3516     } else {
3517         // check if there's a deleted record (cheaply)
3518         if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
3519             error_log('[client '.$_SERVER['REMOTE_ADDR']."]  $CFG->wwwroot  Deleted Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3520             return false;
3521         }
3523         $auths = $authsenabled;
3524         $user = new object();
3525         $user->id = 0;     // User does not exist
3526     }
3528     foreach ($auths as $auth) {
3529         $authplugin = get_auth_plugin($auth);
3531         // on auth fail fall through to the next plugin
3532         if (!$authplugin->user_login($username, $password)) {
3533             continue;
3534         }
3536         // successful authentication
3537         if ($user->id) {                          // User already exists in database
3538             if (empty($user->auth)) {             // For some reason auth isn't set yet
3539                 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
3540                 $user->auth = $auth;
3541             }
3542             if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3543                 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
3544                 $user->firstaccess = $user->timemodified;
3545             }
3547             update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3549             if (!$authplugin->is_internal()) {            // update user record from external DB
3550                 $user = update_user_record($username, get_auth_plugin($user->auth));
3551             }
3552         } else {
3553             // if user not found, create him
3554             $user = create_user_record($username, $password, $auth);
3555         }
3557         $authplugin->sync_roles($user);
3559         foreach ($authsenabled as $hau) {
3560             $hauth = get_auth_plugin($hau);
3561             $hauth->user_authenticated_hook($user, $username, $password);
3562         }
3564     /// Log in to a second system if necessary
3565     /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
3566         if (!empty($CFG->sso)) {
3567             include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
3568             if (function_exists('sso_user_login')) {
3569                 if (!sso_user_login($username, $password)) {   // Perform the signon process
3570                     echo $OUTPUT->notification('Second sign-on failed');
3571                 }
3572             }
3573         }
3575         if ($user->id===0) {
3576             return false;
3577         }
3578         return $user;
3579     }
3581     // failed if all the plugins have failed
3582     add_to_log(0, 'login', 'error', 'index.php', $username);
3583     if (debugging('', DEBUG_ALL)) {
3584         error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Failed Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3585     }
3586     return false;
3589 /**
3590  * Call to complete the user login process after authenticate_user_login()
3591  * has succeeded. It will setup the $USER variable and other required bits
3592  * and pieces.
3593  *
3594  * NOTE:
3595  * - It will NOT log anything -- up to the caller to decide what to log.
3596  *
3597  * @global object
3598  * @global object
3599  * @global object
3600  * @param object $user
3601  * @param bool $setcookie
3602  * @return object A {@link $USER} object - BC only, do not use
3603  */
3604 function complete_user_login($user, $setcookie=true) {
3605     global $CFG, $USER, $SESSION;
3607     // regenerate session id and delete old session,
3608     // this helps prevent session fixation attacks from the same domain
3609     session_regenerate_id(true);
3611     // check enrolments, load caps and setup $USER object
3612     session_set_user($user);
3614     update_user_login_times();
3615     set_login_session_preferences();
3617     if ($setcookie) {
3618         if (empty($CFG->nolastloggedin)) {
3619             set_moodle_cookie($USER->username);
3620         } else {
3621             // do not store last logged in user in cookie
3622             // auth plugins can temporarily override this from loginpage_hook()
3623             // do not save $CFG->nolastloggedin in database!
3624             set_moodle_cookie('nobody');
3625         }
3626     }
3628     /// Select password change url
3629     $userauth = get_auth_plugin($USER->auth);
3631     /// check whether the user should be changing password
3632     if (get_user_preferences('auth_forcepasswordchange', false)){
3633         if ($userauth->can_change_password()) {
3634             if ($changeurl = $userauth->change_password_url()) {
3635                 redirect($changeurl);
3636             } else {
3637                 redirect($CFG->httpswwwroot.'/login/change_password.php');
3638             }
3639         } else {
3640             print_error('nopasswordchangeforced', 'auth');
3641         }
3642     }
3643     return $USER;
3646 /**
3647  * Compare password against hash stored in internal user table.
3648  * If necessary it also updates the stored hash to new format.
3649  *
3650  * @global object
3651  * @param object $user
3652  * @param string $password plain text password
3653  * @return bool is password valid?
3654  */
3655 function validate_internal_user_password(&$user, $password) {
3656     global $CFG;
3658     if (!isset($CFG->passwordsaltmain)) {
3659         $CFG->passwordsaltmain = '';
3660     }
3662     $validated = false;
3664     // get password original encoding in case it was not updated to unicode yet
3665     $textlib = textlib_get_instance();
3666     $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset', 'langconfig'));
3668     if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
3669         or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
3670         $validated = true;
3671     } else {
3672         for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
3673             $alt = 'passwordsaltalt'.$i;
3674             if (!empty($CFG->$alt)) {
3675                 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
3676                     $validated = true;
3677                     break;
3678                 }
3679             }
3680         }
3681     }
3683     if ($validated) {
3684         // force update of password hash using latest main password salt and encoding if needed
3685         update_internal_user_password($user, $password);
3686     }
3688     return $validated;
3691 /**
3692  * Calculate hashed value from password using current hash mechanism.
3693  *
3694  * @global object
3695  * @param string $password
3696  * @return string password hash
3697  */
3698 function hash_internal_user_password($password) {
3699     global $CFG;
3701     if (isset($CFG->passwordsaltmain)) {
3702         return md5($password.$CFG->passwordsaltmain);
3703     } else {
3704         return md5($password);
3705     }
3708 /**
3709  * Update pssword hash in user object.
3710  *
3711  * @global object
3712  * @global object
3713  * @param object $user
3714  * @param string $password plain text password
3715  * @return bool true if hash changed
3716  */
3717 function update_internal_user_password(&$user, $password) {
3718     global $CFG, $DB;
3720     $authplugin = get_auth_plugin($user->auth);
3721     if ($authplugin->prevent_local_passwords()) {
3722         $hashedpassword = 'not cached';
3723     } else {
3724         $hashedpassword = hash_internal_user_password($password);
3725     }
3727     $DB->set_field('user', 'password',  $hashedpassword, array('id'=>$user->id));
3728     return true;
3731 /**
3732  * Get a complete user record, which includes all the info
3733  * in the user record.
3734  *
3735  * Intended for setting as $USER session variable
3736  *