3 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
19 * moodlelib.php - Moodle main library
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
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
34 * Used by some scripts to check they are being called by Moodle
36 define('MOODLE_INTERNAL', true);
38 /// Date and time constants ///
40 * Time constant - the number of seconds in a year
42 define('YEARSECS', 31536000);
45 * Time constant - the number of seconds in a week
47 define('WEEKSECS', 604800);
50 * Time constant - the number of seconds in a day
52 define('DAYSECS', 86400);
55 * Time constant - the number of seconds in an hour
57 define('HOURSECS', 3600);
60 * Time constant - the number of seconds in a minute
62 define('MINSECS', 60);
65 * Time constant - the number of minutes in a day
67 define('DAYMINS', 1440);
70 * Time constant - the number of minutes in an hour
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. //////////////
80 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
82 define('PARAM_ALPHA', 'alpha');
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
88 define('PARAM_ALPHAEXT', 'alphaext');
91 * PARAM_ALPHANUM - expected numbers and letters only.
93 define('PARAM_ALPHANUM', 'alphanum');
96 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
98 define('PARAM_ALPHANUMEXT', 'alphanumext');
101 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
103 define('PARAM_AUTH', 'auth');
106 * PARAM_BASE64 - Base 64 encoded format
108 define('PARAM_BASE64', 'base64');
111 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
113 define('PARAM_BOOL', 'bool');
116 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
117 * checked against the list of capabilties in the database.
119 define('PARAM_CAPABILITY', 'capability');
122 * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes. It stays as HTML.
124 define('PARAM_CLEANHTML', 'cleanhtml');
127 * PARAM_EMAIL - an email address following the RFC
129 define('PARAM_EMAIL', 'email');
132 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
134 define('PARAM_FILE', 'file');
137 * PARAM_FLOAT - a real/floating point number.
139 define('PARAM_FLOAT', 'float');
142 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
144 define('PARAM_HOST', 'host');
147 * PARAM_INT - integers only, use when expecting only numbers.
149 define('PARAM_INT', 'int');
152 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
154 define('PARAM_LANG', 'lang');
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!)
159 define('PARAM_LOCALURL', 'localurl');
162 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
164 define('PARAM_NOTAGS', 'notags');
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
170 define('PARAM_PATH', 'path');
173 * PARAM_PEM - Privacy Enhanced Mail format
175 define('PARAM_PEM', 'pem');
178 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
180 define('PARAM_PERMISSION', 'permission');
183 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way
185 define('PARAM_RAW', 'raw');
188 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
190 define('PARAM_SAFEDIR', 'safedir');
193 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
195 define('PARAM_SAFEPATH', 'safepath');
198 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
200 define('PARAM_SEQUENCE', 'sequence');
203 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
205 define('PARAM_TAG', 'tag');
208 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
210 define('PARAM_TAGLIST', 'taglist');
213 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
215 define('PARAM_TEXT', 'text');
218 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
220 define('PARAM_THEME', 'theme');
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.
225 define('PARAM_URL', 'url');
228 * PARAM_USERNAME - Clean username to only contains specified characters.
230 define('PARAM_USERNAME', 'username');
233 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
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 ;-)
238 define('PARAM_CLEAN', 'clean');
241 * PARAM_INTEGER - deprecated alias for PARAM_INT
243 define('PARAM_INTEGER', 'int');
246 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
248 define('PARAM_NUMBER', 'float');
251 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in formas and urls
252 * NOTE: originally alias for PARAM_APLHA
254 define('PARAM_ACTION', 'alphanumext');
257 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
258 * NOTE: originally alias for PARAM_APLHA
260 define('PARAM_FORMAT', 'alphanumext');
263 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
265 define('PARAM_MULTILANG', 'text');
268 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
270 define('PARAM_CLEANFILE', 'file');
275 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
277 define('VALUE_REQUIRED', 1);
280 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
282 define('VALUE_OPTIONAL', 2);
285 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
287 define('VALUE_DEFAULT', 0);
290 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
292 define('NULL_NOT_ALLOWED', false);
295 * NULL_ALLOWED - the parameter can be set to null in the database
297 define('NULL_ALLOWED', true);
301 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
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);
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 ;-)
324 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
326 define('TAG_MAX_LENGTH', 50);
328 /// Password policy constants ///
329 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
330 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
331 define ('PASSWORD_DIGITS', '0123456789');
332 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
334 /// Feature constants ///
335 // Used for plugin_supports() to report features that are, or are not, supported by a module.
337 /** True if module can provide a grade */
338 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
339 /** True if module supports outcomes */
340 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
342 /** True if module has code to track whether somebody viewed it */
343 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
344 /** True if module has custom completion rules */
345 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
347 /** True if module supports outcomes */
348 define('FEATURE_IDNUMBER', 'idnumber');
349 /** True if module supports groups */
350 define('FEATURE_GROUPS', 'groups');
351 /** True if module supports groupings */
352 define('FEATURE_GROUPINGS', 'groupings');
353 /** True if module supports groupmembersonly */
354 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
356 /** Type of module */
357 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
358 /** True if module supports intro editor */
359 define('FEATURE_MOD_INTRO', 'mod_intro');
360 /** True if module supports subplugins */
361 define('FEATURE_MOD_SUBPLUGINS', 'mod_subplugins');
362 /** True if module has default completion */
363 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
365 define('FEATURE_COMMENT', 'comment');
367 /** 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);
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.
381 define('EXTERNAL_TOKEN_PERMANENT', 0);
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.
389 define('EXTERNAL_TOKEN_EMBEDDED', 1);
391 /// PARAMETER HANDLING ////////////////////////////////////////////////////
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.
398 * This function should be used to initialise all required values
399 * in a script that are based on parameters. Usually it will be
401 * $id = required_param('id', PARAM_INT);
403 * @param string $parname the name of the page parameter we want,
404 * default PARAM_CLEAN
405 * @param int $type expected type of parameter
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];
414 print_error('missingparam', '', '', $parname);
417 return clean_param($param, $type);
421 * Returns a particular value for the named variable, taken from
422 * POST or GET, otherwise returning a given default.
424 * This function should be used to initialise all optional values
425 * in a script that are based on parameters. Usually it will be
427 * $name = optional_param('name', 'Fred', PARAM_TEXT);
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
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];
443 return clean_param($param, $type);
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.
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
459 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
460 if (is_null($param)) {
461 if ($allownull == NULL_ALLOWED) {
464 throw new invalid_parameter_exception($debuginfo);
467 if (is_array($param) or is_object($param)) {
468 throw new invalid_parameter_exception($debuginfo);
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);
481 * Used by {@link optional_param()} and {@link required_param()} to
482 * clean the variables and/or cast to specific types, based on
485 * $course->format = clean_param($course->format, PARAM_ALPHA);
486 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
492 * @uses PARAM_CLEANHTML
497 * @uses PARAM_ALPHAEXT
498 * @uses PARAM_ALPHANUM
499 * @uses PARAM_ALPHANUMEXT
500 * @uses PARAM_SEQUENCE
504 * @uses PARAM_SAFEDIR
505 * @uses PARAM_SAFEPATH
510 * @uses PARAM_LOCALURL
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.
520 function clean_param($param, $type) {
524 if (is_array($param)) { // Let's loop
526 foreach ($param as $key => $value) {
527 $newparam[$key] = clean_param($value, $type);
533 case PARAM_RAW: // no cleaning at all
536 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
537 if (is_numeric($param)) {
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
547 return (int)$param; // Convert to integer
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') {
572 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
575 $param = empty($param) ? 0 : 1;
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 === '.') {
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
614 || $match[4] > 255 ) {
615 // hmmm, what kind of dotted quad is this?
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
622 // all is ok - $param is respected
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
634 $param =''; // not really ok
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
646 // relative - let's make sure there are no tricks
647 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
657 $param = trim($param);
658 // PEM formatted strings may contain letters/numbers and the symbols
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);
668 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
676 if (!empty($param)) {
677 // PEM formatted strings may contain letters/numbers and the symbols
681 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
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++) {
690 if (64 < strlen($lines[$i])) {
696 if (64 != strlen($lines[$i])) {
700 return implode("\n",$lines);
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);
719 $tags = explode(',', $param);
721 foreach ($tags as $tag) {
722 $res = clean_param($tag, PARAM_TAG);
728 return implode(',', $result);
733 case PARAM_CAPABILITY:
734 if (is_valid_capability($param)) {
740 case PARAM_PERMISSION:
741 $param = (int)$param;
742 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
749 $param = clean_param($param, PARAM_SAFEDIR);
750 if (exists_auth_plugin($param)) {
757 $param = clean_param($param, PARAM_SAFEDIR);
758 $langs = get_list_of_languages(false, true);
759 if (in_array($param, $langs)) {
762 return ''; // Specified language is not installed
766 $param = clean_param($param, PARAM_SAFEDIR);
767 if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
769 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
772 return ''; // Specified theme is not installed
776 $param = str_replace(" " , "", $param);
777 $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
778 if (empty($CFG->extendedusernamechars)) {
779 // regular expression, eliminate all chars EXCEPT:
780 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
781 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
786 if (validate_email($param)) {
792 default: // throw error, switched parameters in optional_param or another serious problem
793 print_error("unknownparamtype", '', '', $type);
798 * Return true if given value is integer or string with integer value
800 * @param mixed $value String or Int
801 * @return bool true if number, false if not
803 function is_number($value) {
804 if (is_int($value)) {
806 } else if (is_string($value)) {
807 return ((string)(int)$value) === $value;
814 * Returns host part from url
815 * @param string $url full url
816 * @return string host, null if not found
818 function get_host_from_url($url) {
819 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
827 * Tests whether anything was returned by text editor
829 * This function is useful for testing whether something you got back from
830 * the HTML editor actually contains anything. Sometimes the HTML editor
831 * appear to be empty, but actually you get back a <br> tag or something.
833 * @param string $string a string containing HTML.
834 * @return boolean does the string contain any actual content - that is text,
835 * images, objcts, etc.
837 function html_is_blank($string) {
838 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
842 * Set a key in global configuration
844 * Set a key/value pair in both this session's {@link $CFG} global variable
845 * and in the 'config' database table for future sessions.
847 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
848 * In that case it doesn't affect $CFG.
850 * A NULL value will delete the entry.
854 * @param string $name the key to set
855 * @param string $value the value to set (without magic quotes)
856 * @param string $plugin (optional) the plugin scope, default NULL
857 * @return bool true or exception
859 function set_config($name, $value, $plugin=NULL) {
862 if (empty($plugin)) {
863 if (!array_key_exists($name, $CFG->config_php_settings)) {
864 // So it's defined for this invocation at least
865 if (is_null($value)) {
868 $CFG->$name = (string)$value; // settings from db are always strings
872 if ($DB->get_field('config', 'name', array('name'=>$name))) {
873 if ($value === null) {
874 $DB->delete_records('config', array('name'=>$name));
876 $DB->set_field('config', 'value', $value, array('name'=>$name));
879 if ($value !== null) {
880 $config = new object();
881 $config->name = $name;
882 $config->value = $value;
883 $DB->insert_record('config', $config, false);
887 } else { // plugin scope
888 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
890 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
892 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
895 if ($value !== null) {
896 $config = new object();
897 $config->plugin = $plugin;
898 $config->name = $name;
899 $config->value = $value;
900 $DB->insert_record('config_plugins', $config, false);
909 * Get configuration values from the global config table
910 * or the config_plugins table.
912 * If called with no parameters it will do the right thing
913 * generating $CFG safely from the database without overwriting
916 * If called with one parameter, it will load all the config
917 * variables for one pugin, and return them as an object.
919 * If called with 2 parameters it will return a $string single
920 * value or false of the value is not found.
923 * @param string $plugin default NULL
924 * @param string $name default NULL
925 * @return mixed hash-like object or single value
927 function get_config($plugin=NULL, $name=NULL) {
930 if (!empty($name)) { // the user is asking for a specific value
931 if (!empty($plugin)) {
932 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
934 return $DB->get_field('config', 'value', array('name'=>$name));
938 // the user is after a recordset
939 if (!empty($plugin)) {
940 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
941 if (!empty($localcfg)) {
942 return (object)$localcfg;
947 // this was originally in setup.php
948 if ($configs = $DB->get_records('config')) {
949 $localcfg = (array)$CFG;
950 foreach ($configs as $config) {
951 if (!isset($localcfg[$config->name])) {
952 $localcfg[$config->name] = $config->value;
954 // do not complain anymore if config.php overrides settings from db
957 $localcfg = (object)$localcfg;
960 // preserve $CFG if DB returns nothing or error
968 * Removes a key from global configuration
970 * @param string $name the key to set
971 * @param string $plugin (optional) the plugin scope
973 * @return boolean whether the operation succeeded.
975 function unset_config($name, $plugin=NULL) {
978 if (empty($plugin)) {
980 $DB->delete_records('config', array('name'=>$name));
982 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
989 * Remove all the config variables for a given plugin.
991 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
992 * @return boolean whether the operation succeeded.
994 function unset_all_config_for_plugin($plugin) {
996 $DB->delete_records('config_plugins', array('plugin' => $plugin));
997 $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
1002 * Use this funciton to get a list of users from a config setting of type admin_setting_users_with_capability.
1003 * @param string $value the value of the config setting.
1004 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1005 * @return array of user objects.
1007 function get_users_from_config($value, $capability) {
1009 if ($value == '$@ALL@$') {
1010 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1012 list($where, $params) = $DB->get_in_or_equal(explode(',', $CFG->courserequestnotify));
1013 $params[] = $CFG->mnet_localhost_id;
1014 $users = $DB->get_records_select('user', 'username ' . $where . ' AND mnethostid = ?', $params);
1020 * Get volatile flags
1022 * @param string $type
1023 * @param int $changedsince default null
1024 * @return records array
1026 function get_cache_flags($type, $changedsince=NULL) {
1029 $params = array('type'=>$type, 'expiry'=>time());
1030 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1031 if ($changedsince !== NULL) {
1032 $params['changedsince'] = $changedsince;
1033 $sqlwhere .= " AND timemodified > :changedsince";
1037 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1038 foreach ($flags as $flag) {
1039 $cf[$flag->name] = $flag->value;
1046 * Get volatile flags
1048 * @param string $type
1049 * @param string $name
1050 * @param int $changedsince default null
1051 * @return records array
1053 function get_cache_flag($type, $name, $changedsince=NULL) {
1056 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1058 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1059 if ($changedsince !== NULL) {
1060 $params['changedsince'] = $changedsince;
1061 $sqlwhere .= " AND timemodified > :changedsince";
1064 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1068 * Set a volatile flag
1070 * @param string $type the "type" namespace for the key
1071 * @param string $name the key to set
1072 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1073 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1074 * @return bool Always returns true
1076 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1079 $timemodified = time();
1080 if ($expiry===NULL || $expiry < $timemodified) {
1081 $expiry = $timemodified + 24 * 60 * 60;
1083 $expiry = (int)$expiry;
1086 if ($value === NULL) {
1087 unset_cache_flag($type,$name);
1091 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potentail problem in DEBUG_DEVELOPER
1092 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1093 return true; //no need to update; helps rcache too
1096 $f->expiry = $expiry;
1097 $f->timemodified = $timemodified;
1098 $DB->update_record('cache_flags', $f);
1101 $f->flagtype = $type;
1104 $f->expiry = $expiry;
1105 $f->timemodified = $timemodified;
1106 $DB->insert_record('cache_flags', $f);
1112 * Removes a single volatile flag
1115 * @param string $type the "type" namespace for the key
1116 * @param string $name the key to set
1119 function unset_cache_flag($type, $name) {
1121 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1126 * Garbage-collect volatile flags
1128 * @return bool Always returns true
1130 function gc_cache_flags() {
1132 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1136 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1139 * Refresh current $USER session global variable with all their current preferences.
1142 * @param mixed $time default null
1145 function check_user_preferences_loaded($time = null) {
1147 static $timenow = null; // Static cache, so we only check up-to-dateness once per request.
1149 if (!empty($USER->preference) && isset($USER->preference['_lastloaded'])) {
1150 // Already loaded. Are we up to date?
1152 if (is_null($timenow) || (!is_null($time) && $time != $timenow)) {
1154 if (!get_cache_flag('userpreferenceschanged', $USER->id, $USER->preference['_lastloaded'])) {
1155 // We are up-to-date.
1159 // Already checked for up-to-date-ness.
1164 // OK, so we have to reload. Reset preference
1165 $USER->preference = array();
1167 if (!isloggedin() or isguestuser()) {
1168 // No permanent storage for not-logged-in user and guest
1170 } else if ($preferences = $DB->get_records('user_preferences', array('userid'=>$USER->id))) {
1171 foreach ($preferences as $preference) {
1172 $USER->preference[$preference->name] = $preference->value;
1176 $USER->preference['_lastloaded'] = $timenow;
1180 * Called from set/delete_user_preferences, so that the prefs can be correctly reloaded.
1184 * @param integer $userid the user whose prefs were changed.
1186 function mark_user_preferences_changed($userid) {
1188 if ($userid == $USER->id) {
1189 check_user_preferences_loaded(time());
1191 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1195 * Sets a preference for the current user
1197 * Optionally, can set a preference for a different user object
1199 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
1203 * @param string $name The key to set as preference for the specified user
1204 * @param string $value The value to set forthe $name key in the specified user's record
1205 * @param int $otheruserid A moodle user ID, default null
1208 function set_user_preference($name, $value, $otheruserid=NULL) {
1216 if (empty($otheruserid)){
1217 if (!isloggedin() or isguestuser()) {
1220 $userid = $USER->id;
1222 if (isguestuser($otheruserid)) {
1225 $userid = $otheruserid;
1229 // no permanent storage for not-logged-in user and guest
1231 } else if ($preference = $DB->get_record('user_preferences', array('userid'=>$userid, 'name'=>$name))) {
1232 if ($preference->value === $value) {
1235 $DB->set_field('user_preferences', 'value', (string)$value, array('id'=>$preference->id));
1238 $preference = new object();
1239 $preference->userid = $userid;
1240 $preference->name = $name;
1241 $preference->value = (string)$value;
1242 $DB->insert_record('user_preferences', $preference);
1245 mark_user_preferences_changed($userid);
1246 // update value in USER session if needed
1247 if ($userid == $USER->id) {
1248 $USER->preference[$name] = (string)$value;
1249 $USER->preference['_lastloaded'] = time();
1256 * Sets a whole array of preferences for the current user
1258 * @param array $prefarray An array of key/value pairs to be set
1259 * @param int $otheruserid A moodle user ID
1262 function set_user_preferences($prefarray, $otheruserid=NULL) {
1264 if (!is_array($prefarray) or empty($prefarray)) {
1268 foreach ($prefarray as $name => $value) {
1269 set_user_preference($name, $value, $otheruserid);
1275 * Unsets a preference completely by deleting it from the database
1277 * Optionally, can set a preference for a different user id
1280 * @param string $name The key to unset as preference for the specified user
1281 * @param int $otheruserid A moodle user ID
1283 function unset_user_preference($name, $otheruserid=NULL) {
1286 if (empty($otheruserid)){
1287 $userid = $USER->id;
1288 check_user_preferences_loaded();
1290 $userid = $otheruserid;
1294 $DB->delete_records('user_preferences', array('userid'=>$userid, 'name'=>$name));
1296 mark_user_preferences_changed($userid);
1297 //Delete the preference from $USER if needed
1298 if ($userid == $USER->id) {
1299 unset($USER->preference[$name]);
1300 $USER->preference['_lastloaded'] = time();
1307 * Used to fetch user preference(s)
1309 * If no arguments are supplied this function will return
1310 * all of the current user preferences as an array.
1312 * If a name is specified then this function
1313 * attempts to return that particular preference value. If
1314 * none is found, then the optional value $default is returned,
1319 * @param string $name Name of the key to use in finding a preference value
1320 * @param string $default Value to be returned if the $name key is not set in the user preferences
1321 * @param int $otheruserid A moodle user ID
1324 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
1327 if (empty($otheruserid) || (!empty($USER->id) && ($USER->id == $otheruserid))){
1328 check_user_preferences_loaded();
1331 return $USER->preference; // All values
1332 } else if (array_key_exists($name, $USER->preference)) {
1333 return $USER->preference[$name]; // The single value
1335 return $default; // Default value (or NULL)
1340 return $DB->get_records_menu('user_preferences', array('userid'=>$otheruserid), '', 'name,value'); // All values
1341 } else if ($value = $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>$name))) {
1342 return $value; // The single value
1344 return $default; // Default value (or NULL)
1349 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1352 * Given date parts in user time produce a GMT timestamp.
1354 * @todo Finish documenting this function
1355 * @param int $year The year part to create timestamp of
1356 * @param int $month The month part to create timestamp of
1357 * @param int $day The day part to create timestamp of
1358 * @param int $hour The hour part to create timestamp of
1359 * @param int $minute The minute part to create timestamp of
1360 * @param int $second The second part to create timestamp of
1361 * @param float $timezone Timezone modifier
1362 * @param bool $applydst Toggle Daylight Saving Time, default true
1363 * @return int timestamp
1365 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1367 $strtimezone = NULL;
1368 if (!is_numeric($timezone)) {
1369 $strtimezone = $timezone;
1372 $timezone = get_user_timezone_offset($timezone);
1374 if (abs($timezone) > 13) {
1375 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1377 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1378 $time = usertime($time, $timezone);
1380 $time -= dst_offset_on($time, $strtimezone);
1389 * Format a date/time (seconds) as weeks, days, hours etc as needed
1391 * Given an amount of time in seconds, returns string
1392 * formatted nicely as weeks, days, hours etc as needed
1398 * @param int $totalsecs Time in seconds
1399 * @param object $str Should be a time object
1400 * @return string A nicely formatted date/time string
1402 function format_time($totalsecs, $str=NULL) {
1404 $totalsecs = abs($totalsecs);
1406 if (!$str) { // Create the str structure the slow way
1407 $str->day = get_string('day');
1408 $str->days = get_string('days');
1409 $str->hour = get_string('hour');
1410 $str->hours = get_string('hours');
1411 $str->min = get_string('min');
1412 $str->mins = get_string('mins');
1413 $str->sec = get_string('sec');
1414 $str->secs = get_string('secs');
1415 $str->year = get_string('year');
1416 $str->years = get_string('years');
1420 $years = floor($totalsecs/YEARSECS);
1421 $remainder = $totalsecs - ($years*YEARSECS);
1422 $days = floor($remainder/DAYSECS);
1423 $remainder = $totalsecs - ($days*DAYSECS);
1424 $hours = floor($remainder/HOURSECS);
1425 $remainder = $remainder - ($hours*HOURSECS);
1426 $mins = floor($remainder/MINSECS);
1427 $secs = $remainder - ($mins*MINSECS);
1429 $ss = ($secs == 1) ? $str->sec : $str->secs;
1430 $sm = ($mins == 1) ? $str->min : $str->mins;
1431 $sh = ($hours == 1) ? $str->hour : $str->hours;
1432 $sd = ($days == 1) ? $str->day : $str->days;
1433 $sy = ($years == 1) ? $str->year : $str->years;
1441 if ($years) $oyears = $years .' '. $sy;
1442 if ($days) $odays = $days .' '. $sd;
1443 if ($hours) $ohours = $hours .' '. $sh;
1444 if ($mins) $omins = $mins .' '. $sm;
1445 if ($secs) $osecs = $secs .' '. $ss;
1447 if ($years) return trim($oyears .' '. $odays);
1448 if ($days) return trim($odays .' '. $ohours);
1449 if ($hours) return trim($ohours .' '. $omins);
1450 if ($mins) return trim($omins .' '. $osecs);
1451 if ($secs) return $osecs;
1452 return get_string('now');
1456 * Returns a formatted string that represents a date in user time
1458 * Returns a formatted string that represents a date in user time
1459 * <b>WARNING: note that the format is for strftime(), not date().</b>
1460 * Because of a bug in most Windows time libraries, we can't use
1461 * the nicer %e, so we have to use %d which has leading zeroes.
1462 * A lot of the fuss in the function is just getting rid of these leading
1463 * zeroes as efficiently as possible.
1465 * If parameter fixday = true (default), then take off leading
1466 * zero from %d, else mantain it.
1468 * @param int $date the timestamp in UTC, as obtained from the database.
1469 * @param string $format strftime format. You should probably get this using
1470 * get_string('strftime...', 'langconfig');
1471 * @param float $timezone by default, uses the user's time zone.
1472 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1473 * If false then the leading zero is mantained.
1474 * @return string the formatted date/time.
1476 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1480 $strtimezone = NULL;
1481 if (!is_numeric($timezone)) {
1482 $strtimezone = $timezone;
1485 if (empty($format)) {
1486 $format = get_string('strftimedaydatetime', 'langconfig');
1489 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1491 } else if ($fixday) {
1492 $formatnoday = str_replace('%d', 'DD', $format);
1493 $fixday = ($formatnoday != $format);
1496 $date += dst_offset_on($date, $strtimezone);
1498 $timezone = get_user_timezone_offset($timezone);
1500 if (abs($timezone) > 13) { /// Server time
1502 $datestring = strftime($formatnoday, $date);
1503 $daystring = str_replace(array(' 0', ' '), '', strftime(' %d', $date));
1504 $datestring = str_replace('DD', $daystring, $datestring);
1506 $datestring = strftime($format, $date);
1509 $date += (int)($timezone * 3600);
1511 $datestring = gmstrftime($formatnoday, $date);
1512 $daystring = str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date));
1513 $datestring = str_replace('DD', $daystring, $datestring);
1515 $datestring = gmstrftime($format, $date);
1519 /// If we are running under Windows convert from windows encoding to UTF-8
1520 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1522 if ($CFG->ostype == 'WINDOWS') {
1523 if ($localewincharset = get_string('localewincharset')) {
1524 $textlib = textlib_get_instance();
1525 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1533 * Given a $time timestamp in GMT (seconds since epoch),
1534 * returns an array that represents the date in user time
1536 * @todo Finish documenting this function
1538 * @param int $time Timestamp in GMT
1539 * @param float $timezone ?
1540 * @return array An array that represents the date in user time
1542 function usergetdate($time, $timezone=99) {
1544 $strtimezone = NULL;
1545 if (!is_numeric($timezone)) {
1546 $strtimezone = $timezone;
1549 $timezone = get_user_timezone_offset($timezone);
1551 if (abs($timezone) > 13) { // Server time
1552 return getdate($time);
1555 // There is no gmgetdate so we use gmdate instead
1556 $time += dst_offset_on($time, $strtimezone);
1557 $time += intval((float)$timezone * HOURSECS);
1559 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
1561 //be careful to ensure the returned array matches that produced by getdate() above
1564 $getdate['weekday'],
1571 $getdate['minutes'],
1573 ) = explode('_', $datestring);
1579 * Given a GMT timestamp (seconds since epoch), offsets it by
1580 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1583 * @param int $date Timestamp in GMT
1584 * @param float $timezone
1587 function usertime($date, $timezone=99) {
1589 $timezone = get_user_timezone_offset($timezone);
1591 if (abs($timezone) > 13) {
1594 return $date - (int)($timezone * HOURSECS);
1598 * Given a time, return the GMT timestamp of the most recent midnight
1599 * for the current user.
1601 * @param int $date Timestamp in GMT
1602 * @param float $timezone Defaults to user's timezone
1603 * @return int Returns a GMT timestamp
1605 function usergetmidnight($date, $timezone=99) {
1607 $userdate = usergetdate($date, $timezone);
1609 // Time of midnight of this user's day, in GMT
1610 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1615 * Returns a string that prints the user's timezone
1617 * @param float $timezone The user's timezone
1620 function usertimezone($timezone=99) {
1622 $tz = get_user_timezone($timezone);
1624 if (!is_float($tz)) {
1628 if(abs($tz) > 13) { // Server time
1629 return get_string('serverlocaltime');
1632 if($tz == intval($tz)) {
1633 // Don't show .0 for whole hours
1650 * Returns a float which represents the user's timezone difference from GMT in hours
1651 * Checks various settings and picks the most dominant of those which have a value
1655 * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
1658 function get_user_timezone_offset($tz = 99) {
1662 $tz = get_user_timezone($tz);
1664 if (is_float($tz)) {
1667 $tzrecord = get_timezone_record($tz);
1668 if (empty($tzrecord)) {
1671 return (float)$tzrecord->gmtoff / HOURMINS;
1676 * Returns an int which represents the systems's timezone difference from GMT in seconds
1679 * @param mixed $tz timezone
1680 * @return int if found, false is timezone 99 or error
1682 function get_timezone_offset($tz) {
1689 if (is_numeric($tz)) {
1690 return intval($tz * 60*60);
1693 if (!$tzrecord = get_timezone_record($tz)) {
1696 return intval($tzrecord->gmtoff * 60);
1700 * Returns a float or a string which denotes the user's timezone
1701 * 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)
1702 * means that for this timezone there are also DST rules to be taken into account
1703 * Checks various settings and picks the most dominant of those which have a value
1707 * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
1710 function get_user_timezone($tz = 99) {
1715 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1716 isset($USER->timezone) ? $USER->timezone : 99,
1717 isset($CFG->timezone) ? $CFG->timezone : 99,
1722 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
1723 $tz = $next['value'];
1726 return is_numeric($tz) ? (float) $tz : $tz;
1730 * Returns cached timezone record for given $timezonename
1734 * @param string $timezonename
1735 * @return mixed timezonerecord object or false
1737 function get_timezone_record($timezonename) {
1739 static $cache = NULL;
1741 if ($cache === NULL) {
1745 if (isset($cache[$timezonename])) {
1746 return $cache[$timezonename];
1749 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
1750 WHERE name = ? ORDER BY year DESC', array($timezonename), true);
1754 * Build and store the users Daylight Saving Time (DST) table
1759 * @param mixed $from_year Start year for the table, defaults to 1971
1760 * @param mixed $to_year End year for the table, defaults to 2035
1761 * @param mixed $strtimezone
1764 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
1765 global $CFG, $SESSION, $DB;
1767 $usertz = get_user_timezone($strtimezone);
1769 if (is_float($usertz)) {
1770 // Trivial timezone, no DST
1774 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1775 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1776 unset($SESSION->dst_offsets);
1777 unset($SESSION->dst_range);
1780 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1781 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1782 // This will be the return path most of the time, pretty light computationally
1786 // Reaching here means we either need to extend our table or create it from scratch
1788 // Remember which TZ we calculated these changes for
1789 $SESSION->dst_offsettz = $usertz;
1791 if(empty($SESSION->dst_offsets)) {
1792 // If we 're creating from scratch, put the two guard elements in there
1793 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1795 if(empty($SESSION->dst_range)) {
1796 // If creating from scratch
1797 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1798 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1800 // Fill in the array with the extra years we need to process
1801 $yearstoprocess = array();
1802 for($i = $from; $i <= $to; ++$i) {
1803 $yearstoprocess[] = $i;
1806 // Take note of which years we have processed for future calls
1807 $SESSION->dst_range = array($from, $to);
1810 // If needing to extend the table, do the same
1811 $yearstoprocess = array();
1813 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1814 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
1816 if($from < $SESSION->dst_range[0]) {
1817 // Take note of which years we need to process and then note that we have processed them for future calls
1818 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
1819 $yearstoprocess[] = $i;
1821 $SESSION->dst_range[0] = $from;
1823 if($to > $SESSION->dst_range[1]) {
1824 // Take note of which years we need to process and then note that we have processed them for future calls
1825 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
1826 $yearstoprocess[] = $i;
1828 $SESSION->dst_range[1] = $to;
1832 if(empty($yearstoprocess)) {
1833 // This means that there was a call requesting a SMALLER range than we have already calculated
1837 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1838 // Also, the array is sorted in descending timestamp order!
1842 static $presets_cache = array();
1843 if (!isset($presets_cache[$usertz])) {
1844 $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');
1846 if(empty($presets_cache[$usertz])) {
1850 // Remove ending guard (first element of the array)
1851 reset($SESSION->dst_offsets);
1852 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
1854 // Add all required change timestamps
1855 foreach($yearstoprocess as $y) {
1856 // Find the record which is in effect for the year $y
1857 foreach($presets_cache[$usertz] as $year => $preset) {
1863 $changes = dst_changes_for_year($y, $preset);
1865 if($changes === NULL) {
1868 if($changes['dst'] != 0) {
1869 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
1871 if($changes['std'] != 0) {
1872 $SESSION->dst_offsets[$changes['std']] = 0;
1876 // Put in a guard element at the top
1877 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1878 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1881 krsort($SESSION->dst_offsets);
1887 * Calculates the required DST change and returns a Timestamp Array
1891 * @param mixed $year Int or String Year to focus on
1892 * @param object $timezone Instatiated Timezone object
1893 * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
1895 function dst_changes_for_year($year, $timezone) {
1897 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1901 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1902 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1904 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1905 list($std_hour, $std_min) = explode(':', $timezone->std_time);
1907 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1908 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
1910 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1911 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1912 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1914 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1915 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
1917 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1921 * Calculates the Daylight Saving Offest for a given date/time (timestamp)
1924 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
1927 function dst_offset_on($time, $strtimezone = NULL) {
1930 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
1934 reset($SESSION->dst_offsets);
1935 while(list($from, $offset) = each($SESSION->dst_offsets)) {
1936 if($from <= $time) {
1941 // This is the normal return path
1942 if($offset !== NULL) {
1946 // Reaching this point means we haven't calculated far enough, do it now:
1947 // Calculate extra DST changes if needed and recurse. The recursion always
1948 // moves toward the stopping condition, so will always end.
1951 // We need a year smaller than $SESSION->dst_range[0]
1952 if($SESSION->dst_range[0] == 1971) {
1955 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
1956 return dst_offset_on($time, $strtimezone);
1959 // We need a year larger than $SESSION->dst_range[1]
1960 if($SESSION->dst_range[1] == 2035) {
1963 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
1964 return dst_offset_on($time, $strtimezone);
1971 * @todo Document what this function does
1972 * @param int $startday
1973 * @param int $weekday
1978 function find_day_in_month($startday, $weekday, $month, $year) {
1980 $daysinmonth = days_in_month($month, $year);
1982 if($weekday == -1) {
1983 // Don't care about weekday, so return:
1984 // abs($startday) if $startday != -1
1985 // $daysinmonth otherwise
1986 return ($startday == -1) ? $daysinmonth : abs($startday);
1989 // From now on we 're looking for a specific weekday
1991 // Give "end of month" its actual value, since we know it
1992 if($startday == -1) {
1993 $startday = -1 * $daysinmonth;
1996 // Starting from day $startday, the sign is the direction
2000 $startday = abs($startday);
2001 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2003 // This is the last such weekday of the month
2004 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2005 if($lastinmonth > $daysinmonth) {
2009 // Find the first such weekday <= $startday
2010 while($lastinmonth > $startday) {
2014 return $lastinmonth;
2019 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
2021 $diff = $weekday - $indexweekday;
2026 // This is the first such weekday of the month equal to or after $startday
2027 $firstfromindex = $startday + $diff;
2029 return $firstfromindex;
2035 * Calculate the number of days in a given month
2037 * @param int $month The month whose day count is sought
2038 * @param int $year The year of the month whose day count is sought
2041 function days_in_month($month, $year) {
2042 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
2046 * Calculate the position in the week of a specific calendar day
2048 * @param int $day The day of the date whose position in the week is sought
2049 * @param int $month The month of the date whose position in the week is sought
2050 * @param int $year The year of the date whose position in the week is sought
2053 function dayofweek($day, $month, $year) {
2054 // I wonder if this is any different from
2055 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2056 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
2059 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2062 * Returns full login url.
2065 * @param bool $loginguest add login guest param, return false
2066 * @return string login url
2068 function get_login_url($loginguest=false) {
2071 if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
2072 $loginguest = $loginguest ? '?loginguest=true' : '';
2073 $url = "$CFG->wwwroot/login/index.php$loginguest";
2076 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2077 $url = "$wwwroot/login/index.php";
2084 * This function checks that the current user is logged in and has the
2085 * required privileges
2087 * This function checks that the current user is logged in, and optionally
2088 * whether they are allowed to be in a particular course and view a particular
2090 * If they are not logged in, then it redirects them to the site login unless
2091 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2092 * case they are automatically logged in as guests.
2093 * If $courseid is given and the user is not enrolled in that course then the
2094 * user is redirected to the course enrolment page.
2095 * If $cm is given and the coursemodule is hidden and the user is not a teacher
2096 * in the course then the user is redirected to the course home page.
2098 * When $cm parameter specified, this function sets page layout to 'module'.
2099 * You need to change it manually later if some other layout needed.
2109 * @uses SITEID Define
2110 * @param mixed $courseorid id of the course or course object
2111 * @param bool $autologinguest default true
2112 * @param object $cm course module object
2113 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2114 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2115 * in order to keep redirects working properly. MDL-14495
2116 * @return mixed Void, exit, and die depending on path
2118 function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsurltome=true) {
2119 global $CFG, $SESSION, $USER, $COURSE, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2121 /// setup global $COURSE, themes, language and locale
2122 if (!empty($courseorid)) {
2123 if (is_object($courseorid)) {
2124 $course = $courseorid;
2125 } else if ($courseorid == SITEID) {
2126 $course = clone($SITE);
2128 $course = $DB->get_record('course', array('id' => $courseorid));
2130 throw new moodle_exception('invalidcourseid');
2134 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2135 $PAGE->set_pagelayout('incourse');
2137 $PAGE->set_course($course); // set's up global $COURSE
2140 // do not touch global $COURSE via $PAGE->set_course() !!
2143 /// If the user is not even logged in yet then make sure they are
2144 if (!isloggedin()) {
2145 //NOTE: $USER->site check was obsoleted by session test cookie,
2146 // $USER->confirmed test is in login/index.php
2147 if ($setwantsurltome) {
2148 $SESSION->wantsurl = $FULLME;
2150 if (!empty($_SERVER['HTTP_REFERER'])) {
2151 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2153 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
2156 $loginguest = false;
2158 redirect(get_login_url($loginguest));
2159 exit; // never reached
2162 /// loginas as redirection if needed
2163 if ($COURSE->id != SITEID and session_is_loggedinas()) {
2164 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2165 if ($USER->loginascontext->instanceid != $COURSE->id) {
2166 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2171 /// check whether the user should be changing password (but only if it is REALLY them)
2172 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2173 $userauth = get_auth_plugin($USER->auth);
2174 if ($userauth->can_change_password()) {
2175 $SESSION->wantsurl = $FULLME;
2176 if ($changeurl = $userauth->change_password_url()) {
2177 //use plugin custom url
2178 redirect($changeurl);
2180 //use moodle internal method
2181 if (empty($CFG->loginhttps)) {
2182 redirect($CFG->wwwroot .'/login/change_password.php');
2184 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2185 redirect($wwwroot .'/login/change_password.php');
2189 print_error('nopasswordchangeforced', 'auth');
2193 /// Check that the user account is properly set up
2194 if (user_not_fully_set_up($USER)) {
2195 $SESSION->wantsurl = $FULLME;
2196 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2199 /// Make sure the USER has a sesskey set up. Used for checking script parameters.
2202 // Check that the user has agreed to a site policy if there is one
2203 if (!empty($CFG->sitepolicy)) {
2204 if (!$USER->policyagreed) {
2205 $SESSION->wantsurl = $FULLME;
2206 redirect($CFG->wwwroot .'/user/policy.php');
2210 // Fetch the system context, we are going to use it a lot.
2211 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2213 /// If the site is currently under maintenance, then print a message
2214 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2215 print_maintenance_message();
2218 /// groupmembersonly access control
2219 if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2220 if (isguestuser() or !groups_has_membership($cm)) {
2221 print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
2225 // Fetch the course context, and prefetch its child contexts
2226 if (!isset($COURSE->context)) {
2227 if ( ! $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id) ) {
2228 print_error('nocontext');
2231 if (!empty($cm) && !isset($cm->context)) {
2232 if ( ! $cm->context = get_context_instance(CONTEXT_MODULE, $cm->id) ) {
2233 print_error('nocontext');
2237 // Conditional activity access control
2238 if(!empty($CFG->enableavailability) and $cm) {
2239 // We cache conditional access in session
2240 if(!isset($SESSION->conditionaccessok)) {
2241 $SESSION->conditionaccessok = array();
2243 // If you have been allowed into the module once then you are allowed
2244 // in for rest of session, no need to do conditional checks
2245 if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
2246 // Get condition info (does a query for the availability table)
2247 require_once($CFG->libdir.'/conditionlib.php');
2248 $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
2249 // Check condition for user (this will do a query if the availability
2250 // information depends on grade or completion information)
2251 if ($ci->is_available($junk) ||
2252 has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
2253 $SESSION->conditionaccessok[$cm->id] = true;
2255 print_error('activityiscurrentlyhidden');
2260 if ($COURSE->id == SITEID) {
2261 /// Eliminate hidden site activities straight away
2262 if (!empty($cm) && !$cm->visible
2263 && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
2264 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2266 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2271 /// Check if the user can be in a particular course
2272 if (empty($USER->access['rsw'][$COURSE->context->path])) {
2274 // MDL-13900 - If the course or the parent category are hidden
2275 // and the user hasn't the 'course:viewhiddencourses' capability, prevent access
2277 if ( !($COURSE->visible && course_parent_visible($COURSE)) &&
2278 !has_capability('moodle/course:viewhiddencourses', $COURSE->context)) {
2279 echo $OUTPUT->header();
2280 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2284 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
2286 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) {
2287 if ($COURSE->guest == 1) {
2288 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
2289 $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access);
2293 /// If the user is a guest then treat them according to the course policy about guests
2295 if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) {
2296 if (has_capability('moodle/site:doanything', $sysctx)) {
2297 // administrators must be able to access any course - even if somebody gives them guest access
2298 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2302 switch ($COURSE->guest) { /// Check course policy about guest access
2304 case 1: /// Guests always allowed
2305 if (!has_capability('moodle/course:view', $COURSE->context)) { // Prohibited by capability
2306 echo $OUTPUT->header();
2307 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url());
2309 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
2310 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
2311 get_string('activityiscurrentlyhidden'));
2314 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2315 return; // User is allowed to see this course
2319 case 2: /// Guests allowed with key
2320 if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
2321 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2324 // otherwise drop through to logic below (--> enrol.php)
2327 default: /// Guests not allowed
2328 $strloggedinasguest = get_string('loggedinasguest');
2329 $PAGE->navbar->add($strloggedinasguest);
2330 echo $OUTPUT->header();
2331 if (empty($USER->access['rsw'][$COURSE->context->path])) { // Normal guest
2332 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url());
2334 echo $OUTPUT->notification(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
2335 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
2336 echo $OUTPUT->footer();
2342 /// For non-guests, check if they have course view access
2344 } else if (has_capability('moodle/course:view', $COURSE->context)) {
2345 if (session_is_loggedinas()) { // Make sure the REAL person can also access this course
2346 $realuser = session_get_realuser();
2347 if (!has_capability('moodle/course:view', $COURSE->context, $realuser->id)) {
2348 echo $OUTPUT->header();
2349 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2353 /// Make sure they can read this activity too, if specified
2355 if (!empty($cm) && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
2356 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
2358 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2359 return; // User is allowed to see this course
2364 /// Currently not enrolled in the course, so see if they want to enrol
2365 $SESSION->wantsurl = $FULLME;
2366 redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
2373 * This function just makes sure a user is logged out.
2377 function require_logout() {
2381 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2383 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2384 foreach($authsequence as $authname) {
2385 $authplugin = get_auth_plugin($authname);
2386 $authplugin->prelogout_hook();
2390 session_get_instance()->terminate_current();
2394 * Weaker version of require_login()
2396 * This is a weaker version of {@link require_login()} which only requires login
2397 * when called from within a course rather than the site page, unless
2398 * the forcelogin option is turned on.
2399 * @see require_login()
2402 * @param mixed $courseorid The course object or id in question
2403 * @param bool $autologinguest Allow autologin guests if that is wanted
2404 * @param object $cm Course activity module if known
2405 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2406 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2407 * in order to keep redirects working properly. MDL-14495
2409 function require_course_login($courseorid, $autologinguest=true, $cm=null, $setwantsurltome=true) {
2410 global $CFG, $PAGE, $SITE;
2411 if (!empty($CFG->forcelogin)) {
2412 // login required for both SITE and courses
2413 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2415 } else if (!empty($cm) and !$cm->visible) {
2416 // always login for hidden activities
2417 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2419 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2420 or (!is_object($courseorid) and $courseorid == SITEID)) {
2421 //login for SITE not required
2422 if ($cm and empty($cm->visible)) {
2423 // hidden activities are not accessible without login
2424 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2425 } else if ($cm and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
2426 // not-logged-in users do not have any group membership
2427 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2429 // We still need to instatiate PAGE vars properly so that things
2430 // that rely on it like navigation function correctly.
2431 if (!empty($courseorid)) {
2432 if (is_object($courseorid)) {
2433 $course = $courseorid;
2435 $course = clone($SITE);
2438 $PAGE->set_cm($cm, $course);
2439 $PAGE->set_pagelayout('incourse');
2441 $PAGE->set_course($course);
2444 // If $PAGE->course, and hence $PAGE->context, have not already been set
2445 // up properly, set them up now.
2446 $PAGE->set_course($PAGE->course);
2448 //TODO: verify conditional activities here
2449 user_accesstime_log(SITEID);
2454 // course login always required
2455 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2460 * Require key login. Function terminates with error if key not found or incorrect.
2466 * @uses NO_MOODLE_COOKIES
2467 * @uses PARAM_ALPHANUM
2468 * @param string $script unique script identifier
2469 * @param int $instance optional instance id
2470 * @return int Instance ID
2472 function require_user_key_login($script, $instance=null) {
2473 global $USER, $SESSION, $CFG, $DB;
2475 if (!NO_MOODLE_COOKIES) {
2476 print_error('sessioncookiesdisable');
2480 @session_write_close();
2482 $keyvalue = required_param('key', PARAM_ALPHANUM);
2484 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2485 print_error('invalidkey');
2488 if (!empty($key->validuntil) and $key->validuntil < time()) {
2489 print_error('expiredkey');
2492 if ($key->iprestriction) {
2493 $remoteaddr = getremoteaddr();
2494 if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2495 print_error('ipmismatch');
2499 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2500 print_error('invaliduserid');
2503 /// emulate normal session
2504 session_set_user($user);
2506 /// note we are not using normal login
2507 if (!defined('USER_KEY_LOGIN')) {
2508 define('USER_KEY_LOGIN', true);
2511 /// return isntance id - it might be empty
2512 return $key->instance;
2516 * Creates a new private user access key.
2519 * @param string $script unique target identifier
2520 * @param int $userid
2521 * @param int $instance optional instance id
2522 * @param string $iprestriction optional ip restricted access
2523 * @param timestamp $validuntil key valid only until given data
2524 * @return string access key value
2526 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2529 $key = new object();
2530 $key->script = $script;
2531 $key->userid = $userid;
2532 $key->instance = $instance;
2533 $key->iprestriction = $iprestriction;
2534 $key->validuntil = $validuntil;
2535 $key->timecreated = time();
2537 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
2538 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
2540 $key->value = md5($userid.'_'.time().random_string(40));
2542 $DB->insert_record('user_private_key', $key);
2547 * Modify the user table by setting the currently logged in user's
2548 * last login to now.
2552 * @return bool Always returns true
2554 function update_user_login_times() {
2557 $user = new object();
2558 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2559 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2561 $user->id = $USER->id;
2563 $DB->update_record('user', $user);
2568 * Determines if a user has completed setting up their account.
2570 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
2573 function user_not_fully_set_up($user) {
2574 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
2578 * Check whether the user has exceeded the bounce threshold
2582 * @param user $user A {@link $USER} object
2583 * @return bool true=>User has exceeded bounce threshold
2585 function over_bounce_threshold($user) {
2588 if (empty($CFG->handlebounces)) {
2592 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2596 // set sensible defaults
2597 if (empty($CFG->minbounces)) {
2598 $CFG->minbounces = 10;
2600 if (empty($CFG->bounceratio)) {
2601 $CFG->bounceratio = .20;
2605 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2606 $bouncecount = $bounce->value;
2608 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2609 $sendcount = $send->value;
2611 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2615 * Used to increment or reset email sent count
2618 * @param user $user object containing an id
2619 * @param bool $reset will reset the count to 0
2622 function set_send_count($user,$reset=false) {
2625 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2629 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2630 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2631 $DB->update_record('user_preferences', $pref);
2633 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2635 $pref = new object();
2636 $pref->name = 'email_send_count';
2638 $pref->userid = $user->id;
2639 $DB->insert_record('user_preferences', $pref, false);
2644 * Increment or reset user's email bounce count
2647 * @param user $user object containing an id
2648 * @param bool $reset will reset the count to 0
2650 function set_bounce_count($user,$reset=false) {
2653 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2654 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2655 $DB->update_record('user_preferences', $pref);
2657 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2659 $pref = new object();
2660 $pref->name = 'email_bounce_count';
2662 $pref->userid = $user->id;
2663 $DB->insert_record('user_preferences', $pref, false);
2668 * Keeps track of login attempts
2672 function update_login_count() {
2677 if (empty($SESSION->logincount)) {
2678 $SESSION->logincount = 1;
2680 $SESSION->logincount++;
2683 if ($SESSION->logincount > $max_logins) {
2684 unset($SESSION->wantsurl);
2685 print_error('errortoomanylogins');
2690 * Resets login attempts
2694 function reset_login_count() {
2697 $SESSION->logincount = 0;
2701 * Sync all meta courses
2702 * Goes through all enrolment records for the courses inside all metacourses and syncs with them.
2703 * @see sync_metacourse()
2707 function sync_metacourses() {
2710 if (!$courses = $DB->get_records('course', array('metacourse'=>1))) {
2714 foreach ($courses as $course) {
2715 sync_metacourse($course);
2720 * Returns reference to full info about modules in course (including visibility).
2721 * Cached and as fast as possible (0 or 1 db query).
2726 * @uses CONTEXT_MODULE
2727 * @uses MAX_MODINFO_CACHE_SIZE
2728 * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
2729 * @param int $userid Defaults to current user id
2730 * @return mixed courseinfo object or nothing if resetting
2732 function &get_fast_modinfo(&$course, $userid=0) {
2733 global $CFG, $USER, $DB;
2734 require_once($CFG->dirroot.'/course/lib.php');
2736 if (!empty($CFG->enableavailability)) {
2737 require_once($CFG->libdir.'/conditionlib.php');
2740 static $cache = array();
2742 if ($course === 'reset') {
2745 return $nothing; // we must return some reference
2748 if (empty($userid)) {
2749 $userid = $USER->id;
2752 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
2753 return $cache[$course->id];
2756 if (empty($course->modinfo)) {
2757 // no modinfo yet - load it
2758 rebuild_course_cache($course->id);
2759 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2762 $modinfo = new object();
2763 $modinfo->courseid = $course->id;
2764 $modinfo->userid = $userid;
2765 $modinfo->sections = array();
2766 $modinfo->cms = array();
2767 $modinfo->instances = array();
2768 $modinfo->groups = null; // loaded only when really needed - the only one db query
2770 $info = unserialize($course->modinfo);
2771 if (!is_array($info)) {
2772 // hmm, something is wrong - lets try to fix it
2773 rebuild_course_cache($course->id);
2774 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2775 $info = unserialize($course->modinfo);
2776 if (!is_array($info)) {
2782 // detect if upgrade required
2783 $first = reset($info);
2784 if (!isset($first->id)) {
2785 rebuild_course_cache($course->id);
2786 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2787 $info = unserialize($course->modinfo);
2788 if (!is_array($info)) {
2794 $modlurals = array();
2796 // If we haven't already preloaded contexts for the course, do it now
2797 preload_course_contexts($course->id);
2799 foreach ($info as $mod) {
2800 if (empty($mod->name)) {
2801 // something is wrong here
2804 // reconstruct minimalistic $cm
2807 $cm->instance = $mod->id;
2808 $cm->course = $course->id;
2809 $cm->modname = $mod->mod;
2810 $cm->name = $mod->name;
2811 $cm->visible = $mod->visible;
2812 $cm->sectionnum = $mod->section;
2813 $cm->groupmode = $mod->groupmode;
2814 $cm->groupingid = $mod->groupingid;
2815 $cm->groupmembersonly = $mod->groupmembersonly;
2816 $cm->indent = $mod->indent;
2817 $cm->completion = $mod->completion;
2818 $cm->extra = isset($mod->extra) ? $mod->extra : '';
2819 $cm->icon = isset($mod->icon) ? $mod->icon : '';
2820 $cm->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
2821 $cm->uservisible = true;
2822 if(!empty($CFG->enableavailability)) {
2823 // We must have completion information from modinfo. If it's not
2824 // there, cache needs rebuilding
2825 if(!isset($mod->availablefrom)) {
2826 debugging('enableavailability option was changed; rebuilding '.
2827 'cache for course '.$course->id);
2828 rebuild_course_cache($course->id,true);
2829 // Re-enter this routine to do it all properly
2830 return get_fast_modinfo($course,$userid);
2832 $cm->availablefrom = $mod->availablefrom;
2833 $cm->availableuntil = $mod->availableuntil;
2834 $cm->showavailability = $mod->showavailability;
2835 $cm->conditionscompletion = $mod->conditionscompletion;
2836 $cm->conditionsgrade = $mod->conditionsgrade;
2839 // preload long names plurals and also check module is installed properly
2840 if (!isset($modlurals[$cm->modname])) {
2841 if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
2844 $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
2846 $cm->modplural = $modlurals[$cm->modname];
2847 $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id);
2849 if(!empty($CFG->enableavailability)) {
2850 // Unfortunately the next call really wants to call
2851 // get_fast_modinfo, but that would be recursive, so we fake up a
2852 // modinfo for it already
2853 if(empty($minimalmodinfo)) {
2854 $minimalmodinfo=new stdClass();
2855 $minimalmodinfo->cms=array();
2856 foreach($info as $mod) {
2857 $minimalcm = new stdClass();
2858 $minimalcm->id = $mod->cm;
2859 $minimalcm->name = $mod->name;
2860 $minimalmodinfo->cms[$minimalcm->id]=$minimalcm;
2864 // Get availability information
2865 $ci = new condition_info($cm);
2866 $cm->available=$ci->is_available($cm->availableinfo, true, $userid, $minimalmodinfo);
2868 $cm->available=true;
2870 if ((!$cm->visible or !$cm->available) and !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
2871 $cm->uservisible = false;
2873 } else if (!empty($CFG->enablegroupings) and !empty($cm->groupmembersonly)
2874 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
2875 if (is_null($modinfo->groups)) {
2876 $modinfo->groups = groups_get_user_groups($course->id, $userid);
2878 if (empty($modinfo->groups[$cm->groupingid])) {
2879 $cm->uservisible = false;
2883 if (!isset($modinfo->instances[$cm->modname])) {
2884 $modinfo->instances[$cm->modname] = array();
2886 $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
2887 $modinfo->cms[$cm->id] =& $cm;
2889 // reconstruct sections
2890 if (!isset($modinfo->sections[$cm->sectionnum])) {
2891 $modinfo->sections[$cm->sectionnum] = array();
2893 $modinfo->sections[$cm->sectionnum][] = $cm->id;
2898 unset($cache[$course->id]); // prevent potential reference problems when switching users
2899 $cache[$course->id] = $modinfo;
2901 // Ensure cache does not use too much RAM
2902 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
2905 unset($cache[$key]);
2908 return $cache[$course->id];
2912 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
2914 * @todo finish timeend and timestart maybe we could rely on cron
2915 * job to do the cleaning from time to time
2919 * @uses CONTEXT_COURSE
2920 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
2921 * @return bool Success
2923 function sync_metacourse($course) {
2926 // Check the course is valid.
2927 if (!is_object($course)) {
2928 if (!$course = $DB->get_record('course', array('id'=>$course))) {
2929 return false; // invalid course id
2933 // Check that we actually have a metacourse.
2934 if (empty($course->metacourse)) {
2938 // Get a list of roles that should not be synced.
2939 if (!empty($CFG->nonmetacoursesyncroleids)) {
2940 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
2942 $roleexclusions = '';
2945 // Get the context of the metacourse.
2946 $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
2948 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
2949 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
2950 $managers = array_keys($users);
2952 $managers = array();
2955 // Get assignments of a user to a role that exist in a child course, but
2956 // not in the meta coure. That is, get a list of the assignments that need to be made.
2957 if (!$assignments = $DB->get_records_sql("
2958 SELECT ra.id, ra.roleid, ra.userid, ra.hidden
2959 FROM {role_assignments} ra, {context} con, {course_meta} cm
2960 WHERE ra.contextid = con.id AND
2961 con.contextlevel = ".CONTEXT_COURSE." AND
2962 con.instanceid = cm.child_course AND
2963 cm.parent_course = ? AND
2967 FROM {role_assignments} ra2
2968 WHERE ra2.userid = ra.userid AND
2969 ra2.roleid = ra.roleid AND
2971 )", array($course->id, $context->id))) {
2972 $assignments = array();
2975 // Get assignments of a user to a role that exist in the meta course, but
2976 // not in any child courses. That is, get a list of the unassignments that need to be made.
2977 if (!$unassignments = $DB->get_records_sql("
2978 SELECT ra.id, ra.roleid, ra.userid
2979 FROM {role_assignments} ra
2980 WHERE ra.contextid = ? AND
2984 FROM {role_assignments} ra2, {context} con2, {course_meta} cm
2985 WHERE ra2.userid = ra.userid AND
2986 ra2.roleid = ra.roleid AND
2987 ra2.contextid = con2.id AND
2988 con2.contextlevel = " . CONTEXT_COURSE . " AND
2989 con2.instanceid = cm.child_course AND
2990 cm.parent_course = ?
2991 )", array($context->id, $course->id))) {
2992 $unassignments = array();
2997 // Make the unassignments, if they are not managers.
2998 foreach ($unassignments as $unassignment) {
2999 if (!in_array($unassignment->userid, $managers)) {
3000 $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
3004 // Make the assignments.
3005 foreach ($assignments as $assignment) {
3006 $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id, 0, 0, $assignment->hidden) && $success;
3011 // TODO: finish timeend and timestart
3012 // maybe we could rely on cron job to do the cleaning from time to time
3016 * Adds a record to the metacourse table and calls sync_metacoures
3019 * @param int $metacourseid The Metacourse ID for the metacourse to add to
3020 * @param int $courseid The Course ID of the course to add
3021 * @return bool Success
3023 function add_to_metacourse ($metacourseid, $courseid) {
3026 if (!$metacourse = $DB->get_record("course", array("id"=>$metacourseid))) {
3030 if (!$course = $DB->get_record("course", array("id"=>$courseid))) {
3034 if (!$record = $DB->get_record("course_meta", array("parent_course"=>$metacourseid, "child_course"=>$courseid))) {
3035 $rec = new object();
3036 $rec->parent_course = $metacourseid;
3037 $rec->child_course = $courseid;
3038 $DB->insert_record('course_meta', $rec);
3039 return sync_metacourse($metacourseid);
3046 * Removes the record from the metacourse table and calls sync_metacourse
3049 * @param int $metacourseid The Metacourse ID for the metacourse to remove from
3050 * @param int $courseid The Course ID of the course to remove
3051 * @return bool Success
3053 function remove_from_metacourse($metacourseid, $courseid) {
3056 if ($DB->delete_records('course_meta', array('parent_course'=>$metacourseid, 'child_course'=>$courseid))) {
3057 return sync_metacourse($metacourseid);
3064 * Determines if a user is currently logged in
3069 function isloggedin() {
3072 return (!empty($USER->id));
3076 * Determines if a user is logged in as real guest user with username 'guest'.
3077 * This function is similar to original isguest() in 1.6 and earlier.
3078 * Current isguest() is deprecated - do not use it anymore.
3082 * @param int $user mixed user object or id, $USER if not specified
3083 * @return bool true if user is the real guest user, false if not logged in or other user
3085 function isguestuser($user=NULL) {
3088 if ($user === NULL) {
3090 } else if (is_numeric($user)) {
3091 $user = $DB->get_record('user', array('id'=>$user), 'id, username');
3094 if (empty($user->id)) {
3095 return false; // not logged in, can not be guest
3098 return ($user->username == 'guest');
3102 * Determines if the currently logged in user is in editing mode.
3103 * Note: originally this function had $userid parameter - it was not usable anyway
3105 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3106 * @todo Deprecated function remove when ready
3109 * @uses DEBUG_DEVELOPER
3112 function isediting() {
3114 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3115 return $PAGE->user_is_editing();
3119 * Determines if the logged in user is currently moving an activity
3122 * @param int $courseid The id of the course being tested
3125 function ismoving($courseid) {
3128 if (!empty($USER->activitycopy)) {
3129 return ($USER->activitycopycourse == $courseid);
3135 * Returns a persons full name
3137 * Given an object containing firstname and lastname
3138 * values, this function returns a string with the
3139 * full name of the person.
3140 * The result may depend on system settings
3141 * or language. 'override' will force both names
3142 * to be used even if system settings specify one.
3146 * @param object $user A {@link $USER} object to get full name of
3147 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3150 function fullname($user, $override=false) {
3151 global $CFG, $SESSION;
3153 if (!isset($user->firstname) and !isset($user->lastname)) {
3158 if (!empty($CFG->forcefirstname)) {
3159 $user->firstname = $CFG->forcefirstname;
3161 if (!empty($CFG->forcelastname)) {
3162 $user->lastname = $CFG->forcelastname;
3166 if (!empty($SESSION->fullnamedisplay)) {
3167 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3170 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3171 return $user->firstname .' '. $user->lastname;
3173 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3174 return $user->lastname .' '. $user->firstname;
3176 } else if ($CFG->fullnamedisplay == 'firstname') {
3178 return get_string('fullnamedisplay', '', $user);
3180 return $user->firstname;
3184 return get_string('fullnamedisplay', '', $user);
3188 * Returns whether a given authentication plugin exists.
3191 * @param string $auth Form of authentication to check for. Defaults to the
3192 * global setting in {@link $CFG}.
3193 * @return boolean Whether the plugin is available.
3195 function exists_auth_plugin($auth) {
3198 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3199 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3205 * Checks if a given plugin is in the list of enabled authentication plugins.
3207 * @param string $auth Authentication plugin.
3208 * @return boolean Whether the plugin is enabled.
3210 function is_enabled_auth($auth) {
3215 $enabled = get_enabled_auth_plugins();
3217 return in_array($auth, $enabled);
3221 * Returns an authentication plugin instance.
3224 * @param string $auth name of authentication plugin
3225 * @return object An instance of the required authentication plugin.
3227 function get_auth_plugin($auth) {
3230 // check the plugin exists first
3231 if (! exists_auth_plugin($auth)) {
3232 print_error('authpluginnotfound', 'debug', '', $auth);
3235 // return auth plugin instance
3236 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3237 $class = "auth_plugin_$auth";
3242 * Returns array of active auth plugins.
3244 * @param bool $fix fix $CFG->auth if needed
3247 function get_enabled_auth_plugins($fix=false) {
3250 $default = array('manual', 'nologin');
3252 if (empty($CFG->auth)) {
3255 $auths = explode(',', $CFG->auth);
3259 $auths = array_unique($auths);
3260 foreach($auths as $k=>$authname) {
3261 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3265 $newconfig = implode(',', $auths);
3266 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3267 set_config('auth', $newconfig);
3271 return (array_merge($default, $auths));
3275 * Returns true if an internal authentication method is being used.
3276 * if method not specified then, global default is assumed
3278 * @param string $auth Form of authentication required
3281 function is_internal_auth($auth) {
3282 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3283 return $authplugin->is_internal();
3287 * Returns true if the user is a 'restored' one
3289 * Used in the login process to inform the user
3290 * and allow him/her to reset the password
3294 * @param string $username username to be checked
3297 function is_restored_user($username) {
3300 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3304 * Returns an array of user fields
3306 * @return array User field/column names
3308 function get_user_fieldnames() {
3311 $fieldarray = $DB->get_columns('user');
3312 unset($fieldarray['id']);
3313 $fieldarray = array_keys($fieldarray);
3319 * Creates a bare-bones user record
3321 * @todo Outline auth types and provide code example
3325 * @param string $username New user's username to add to record
3326 * @param string $password New user's password to add to record
3327 * @param string $auth Form of authentication required
3328 * @return object A {@link $USER} object
3330 function create_user_record($username, $password, $auth='manual') {
3333 //just in case check text case
3334 $username = trim(moodle_strtolower($username));
3336 $authplugin = get_auth_plugin($auth);
3338 $newuser = new object();
3340 if ($newinfo = $authplugin->get_userinfo($username)) {
3341 $newinfo = truncate_userinfo($newinfo);
3342 foreach ($newinfo as $key => $value){
3343 $newuser->$key = $value;
3347 if (!empty($newuser->email)) {
3348 if (email_is_not_allowed($newuser->email)) {
3349 unset($newuser->email);
3353 if (!isset($newuser->city)) {
3354 $newuser->city = '';
3357 $newuser->auth = $auth;
3358 $newuser->username = $username;
3361 // user CFG lang for user if $newuser->lang is empty
3362 // or $user->lang is not an installed language
3363 $sitelangs = array_keys(get_list_of_languages());
3364 if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
3365 $newuser->lang = $CFG->lang;
3367 $newuser->confirmed = 1;
3368 $newuser->lastip = getremoteaddr();
3369 $newuser->timemodified = time();
3370 $newuser->mnethostid = $CFG->mnet_localhost_id;
3372 $DB->insert_record('user', $newuser);
3373 $user = get_complete_user_data('username', $newuser->username);
3374 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3375 set_user_preference('auth_forcepasswordchange', 1, $user->id);
3377 update_internal_user_password($user, $password);
3382 * Will update a local user record from an external source
3385 * @param string $username New user's username to add to record
3386 * @param string $authplugin Unused
3387 * @return user A {@link $USER} object
3389 function update_user_record($username, $authplugin) {
3392 $username = trim(moodle_strtolower($username)); /// just in case check text case
3394 $oldinfo = $DB->get_record('user', array('username'=>$username), 'username, auth');
3395 $userauth = get_auth_plugin($oldinfo->auth);
3397 if ($newinfo = $userauth->get_userinfo($username)) {
3398 $newinfo = truncate_userinfo($newinfo);
3399 foreach ($newinfo as $key => $value){
3400 if ($key === 'username') {
3401 // 'username' is not a mapped updateable/lockable field, so skip it.
3404 $confval = $userauth->config->{'field_updatelocal_' . $key};
3405 $lockval = $userauth->config->{'field_lock_' . $key};
3406 if (empty($confval) || empty($lockval)) {
3409 if ($confval === 'onlogin') {
3410 // MDL-4207 Don't overwrite modified user profile values with
3411 // empty LDAP values when 'unlocked if empty' is set. The purpose
3412 // of the setting 'unlocked if empty' is to allow the user to fill
3413 // in a value for the selected field _if LDAP is giving
3414 // nothing_ for this field. Thus it makes sense to let this value
3415 // stand in until LDAP is giving a value for this field.
3416 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3417 $DB->set_field('user', $key, $value, array('username'=>$username));
3423 return get_complete_user_data('username', $username);
3427 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3428 * which may have large fields
3430 * @todo Add vartype handling to ensure $info is an array
3432 * @param array $info Array of user properties to truncate if needed
3433 * @return array The now truncated information that was passed in
3435 function truncate_userinfo($info) {
3436 // define the limits
3446 'institution' => 40,
3454 // apply where needed
3455 foreach (array_keys($info) as $key) {
3456 if (!empty($limit[$key])) {
3457 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
3465 * Marks user deleted in internal user database and notifies the auth plugin.
3466 * Also unenrols user from all roles and does other cleanup.
3468 * @todo Decide if this transaction is really needed (look for internal TODO:)
3472 * @param object $user Userobject before delete (without system magic quotes)
3473 * @return boolean success
3475 function delete_user($user) {
3477 require_once($CFG->libdir.'/grouplib.php');
3478 require_once($CFG->libdir.'/gradelib.php');
3479 require_once($CFG->dirroot.'/message/lib.php');
3481 // delete all grades - backup is kept in grade_grades_history table
3482 if ($grades = grade_grade::fetch_all(array('userid'=>$user->id))) {
3483 foreach ($grades as $grade) {
3484 $grade->delete('userdelete');
3488 //move unread messages from this user to read
3489 message_move_userfrom_unread2read($user->id);
3491 // remove from all groups
3492 $DB->delete_records('groups_members', array('userid'=>$user->id));
3494 // unenrol from all roles in all contexts
3495 role_unassign(0, $user->id); // this might be slow but it is really needed - modules might do some extra cleanup!
3497 // now do a final accesslib cleanup - removes all role assingments in user context and context itself
3498 delete_context(CONTEXT_USER, $user->id);
3500 require_once($CFG->dirroot.'/tag/lib.php');
3501 tag_set('user', $user->id, array());
3503 // workaround for bulk deletes of users with the same email address
3504 $delname = "$user->email.".time();
3505 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3509 // mark internal user record as "deleted"
3510 $updateuser = new object();
3511 $updateuser->id = $user->id;
3512 $updateuser->deleted = 1;
3513 $updateuser->username = $delname; // Remember it just in case
3514 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
3515 $updateuser->idnumber = ''; // Clear this field to free it up
3516 $updateuser->timemodified = time();
3518 $DB->update_record('user', $updateuser);
3520 // notify auth plugin - do not block the delete even when plugin fails
3521 $authplugin = get_auth_plugin($user->auth);
3522 $authplugin->user_delete($user);
3524 events_trigger('user_deleted', $user);
3530 * Retrieve the guest user object
3534 * @return user A {@link $USER} object
3536 function guest_user() {
3539 if ($newuser = $DB->get_record('user', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
3540 $newuser->confirmed = 1;
3541 $newuser->lang = $CFG->lang;
3542 $newuser->lastip = getremoteaddr();
3549 * Authenticates a user against the chosen authentication mechanism
3551 * Given a username and password, this function looks them
3552 * up using the currently selected authentication mechanism,
3553 * and if the authentication is successful, it returns a
3554 * valid $user object from the 'user' table.
3556 * Uses auth_ functions from the currently active auth module
3558 * After authenticate_user_login() returns success, you will need to
3559 * log that the user has logged in, and call complete_user_login() to set
3564 * @param string $username User's username
3565 * @param string $password User's password
3566 * @return user|flase A {@link $USER} object or false if error
3568 function authenticate_user_login($username, $password) {
3569 global $CFG, $DB, $OUTPUT;
3571 $authsenabled = get_enabled_auth_plugins();
3573 if ($user = get_complete_user_data('username', $username)) {
3574 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
3575 if ($auth=='nologin' or !is_enabled_auth($auth)) {
3576 add_to_log(0, 'login', 'error', 'index.php', $username);
3577 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3580 $auths = array($auth);
3583 // check if there's a deleted record (cheaply)
3584 if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
3585 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3589 $auths = $authsenabled;
3590 $user = new object();
3591 $user->id = 0; // User does not exist
3594 foreach ($auths as $auth) {
3595 $authplugin = get_auth_plugin($auth);
3597 // on auth fail fall through to the next plugin
3598 if (!$authplugin->user_login($username, $password)) {
3602 // successful authentication
3603 if ($user->id) { // User already exists in database
3604 if (empty($user->auth)) { // For some reason auth isn't set yet
3605 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
3606 $user->auth = $auth;
3608 if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3609 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
3610 $user->firstaccess = $user->timemodified;
3613 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3615 if (!$authplugin->is_internal()) { // update user record from external DB
3616 $user = update_user_record($username, get_auth_plugin($user->auth));
3619 // if user not found, create him
3620 $user = create_user_record($username, $password, $auth);
3623 $authplugin->sync_roles($user);
3625 foreach ($authsenabled as $hau) {
3626 $hauth = get_auth_plugin($hau);
3627 $hauth->user_authenticated_hook($user, $username, $password);
3630 /// Log in to a second system if necessary
3631 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
3632 if (!empty($CFG->sso)) {
3633 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
3634 if (function_exists('sso_user_login')) {
3635 if (!sso_user_login($username, $password)) { // Perform the signon process
3636 echo $OUTPUT->notification('Second sign-on failed');
3641 if ($user->id===0) {
3647 // failed if all the plugins have failed
3648 add_to_log(0, 'login', 'error', 'index.php', $username);
3649 if (debugging('', DEBUG_ALL)) {
3650 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3656 * Call to complete the user login process after authenticate_user_login()
3657 * has succeeded. It will setup the $USER variable and other required bits
3661 * - It will NOT log anything -- up to the caller to decide what to log.
3666 * @param object $user
3667 * @param bool $setcookie
3668 * @return object A {@link $USER} object - BC only, do not use
3670 function complete_user_login($user, $setcookie=true) {
3671 global $CFG, $USER, $SESSION;
3673 // regenerate session id and delete old session,
3674 // this helps prevent session fixation attacks from the same domain
3675 session_regenerate_id(true);
3677 // check enrolments, load caps and setup $USER object
3678 session_set_user($user);
3680 update_user_login_times();
3681 set_login_session_preferences();
3684 if (empty($CFG->nolastloggedin)) {
3685 set_moodle_cookie($USER->username);
3687 // do not store last logged in user in cookie
3688 // auth plugins can temporarily override this from loginpage_hook()
3689 // do not save $CFG->nolastloggedin in database!
3690 set_moodle_cookie('nobody');
3694 /// Select password change url
3695 $userauth = get_auth_plugin($USER->auth);
3697 /// check whether the user should be changing password
3698 if (get_user_preferences('auth_forcepasswordchange', false)){
3699 if ($userauth->can_change_password()) {
3700 if ($changeurl = $userauth->change_password_url()) {
3701 redirect($changeurl);
3703 redirect($CFG->httpswwwroot.'/login/change_password.php');
3706 print_error('nopasswordchangeforced', 'auth');
3713 * Compare password against hash stored in internal user table.
3714 * If necessary it also updates the stored hash to new format.
3717 * @param object $user
3718 * @param string $password plain text password
3719 * @return bool is password valid?
3721 function validate_internal_user_password(&$user, $password) {
3724 if (!isset($CFG->passwordsaltmain)) {
3725 $CFG->passwordsaltmain = '';
3730 // get password original encoding in case it was not updated to unicode yet
3731 $textlib = textlib_get_instance();
3732 $convpassword = $textlib->convert($password, 'utf-8',