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
28 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32 defined('MOODLE_INTERNAL') || die();
34 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
36 /// Date and time constants ///
38 * Time constant - the number of seconds in a year
40 define('YEARSECS', 31536000);
43 * Time constant - the number of seconds in a week
45 define('WEEKSECS', 604800);
48 * Time constant - the number of seconds in a day
50 define('DAYSECS', 86400);
53 * Time constant - the number of seconds in an hour
55 define('HOURSECS', 3600);
58 * Time constant - the number of seconds in a minute
60 define('MINSECS', 60);
63 * Time constant - the number of minutes in a day
65 define('DAYMINS', 1440);
68 * Time constant - the number of minutes in an hour
70 define('HOURMINS', 60);
72 /// Parameter constants - every call to optional_param(), required_param() ///
73 /// or clean_param() should have a specified type of parameter. //////////////
78 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
80 define('PARAM_ALPHA', 'alpha');
83 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
84 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
86 define('PARAM_ALPHAEXT', 'alphaext');
89 * PARAM_ALPHANUM - expected numbers and letters only.
91 define('PARAM_ALPHANUM', 'alphanum');
94 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
96 define('PARAM_ALPHANUMEXT', 'alphanumext');
99 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
101 define('PARAM_AUTH', 'auth');
104 * PARAM_BASE64 - Base 64 encoded format
106 define('PARAM_BASE64', 'base64');
109 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
111 define('PARAM_BOOL', 'bool');
114 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
115 * checked against the list of capabilities in the database.
117 define('PARAM_CAPABILITY', 'capability');
120 * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes. It stays as HTML.
122 define('PARAM_CLEANHTML', 'cleanhtml');
125 * PARAM_EMAIL - an email address following the RFC
127 define('PARAM_EMAIL', 'email');
130 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
132 define('PARAM_FILE', 'file');
135 * PARAM_FLOAT - a real/floating point number.
137 define('PARAM_FLOAT', 'float');
140 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
142 define('PARAM_HOST', 'host');
145 * PARAM_INT - integers only, use when expecting only numbers.
147 define('PARAM_INT', 'int');
150 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
152 define('PARAM_LANG', 'lang');
155 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
157 define('PARAM_LOCALURL', 'localurl');
160 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
162 define('PARAM_NOTAGS', 'notags');
165 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
166 * note: the leading slash is not removed, window drive letter is not allowed
168 define('PARAM_PATH', 'path');
171 * PARAM_PEM - Privacy Enhanced Mail format
173 define('PARAM_PEM', 'pem');
176 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
178 define('PARAM_PERMISSION', 'permission');
181 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way
183 define('PARAM_RAW', 'raw');
186 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
188 define('PARAM_SAFEDIR', 'safedir');
191 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
193 define('PARAM_SAFEPATH', 'safepath');
196 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
198 define('PARAM_SEQUENCE', 'sequence');
201 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
203 define('PARAM_TAG', 'tag');
206 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
208 define('PARAM_TAGLIST', 'taglist');
211 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
213 define('PARAM_TEXT', 'text');
216 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
218 define('PARAM_THEME', 'theme');
221 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
223 define('PARAM_URL', 'url');
226 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user accounts, do NOT use when syncing with external systems!!
228 define('PARAM_USERNAME', 'username');
231 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
233 define('PARAM_STRINGID', 'stringid');
235 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
237 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
238 * It was one of the first types, that is why it is abused so much ;-)
240 define('PARAM_CLEAN', 'clean');
243 * PARAM_INTEGER - deprecated alias for PARAM_INT
245 define('PARAM_INTEGER', 'int');
248 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
250 define('PARAM_NUMBER', 'float');
253 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
254 * NOTE: originally alias for PARAM_APLHA
256 define('PARAM_ACTION', 'alphanumext');
259 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
260 * NOTE: originally alias for PARAM_APLHA
262 define('PARAM_FORMAT', 'alphanumext');
265 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
267 define('PARAM_MULTILANG', 'text');
270 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
272 define('PARAM_CLEANFILE', 'file');
277 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
279 define('VALUE_REQUIRED', 1);
282 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
284 define('VALUE_OPTIONAL', 2);
287 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
289 define('VALUE_DEFAULT', 0);
292 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
294 define('NULL_NOT_ALLOWED', false);
297 * NULL_ALLOWED - the parameter can be set to null in the database
299 define('NULL_ALLOWED', true);
303 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
305 define('PAGE_COURSE_VIEW', 'course-view');
307 /** Get remote addr constant */
308 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
309 /** Get remote addr constant */
310 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
312 /// Blog access level constant declaration ///
313 define ('BLOG_USER_LEVEL', 1);
314 define ('BLOG_GROUP_LEVEL', 2);
315 define ('BLOG_COURSE_LEVEL', 3);
316 define ('BLOG_SITE_LEVEL', 4);
317 define ('BLOG_GLOBAL_LEVEL', 5);
322 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
323 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
324 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
326 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
328 define('TAG_MAX_LENGTH', 50);
330 /// Password policy constants ///
331 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
332 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
333 define ('PASSWORD_DIGITS', '0123456789');
334 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
336 /// Feature constants ///
337 // Used for plugin_supports() to report features that are, or are not, supported by a module.
339 /** True if module can provide a grade */
340 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
341 /** True if module supports outcomes */
342 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
344 /** True if module has code to track whether somebody viewed it */
345 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
346 /** True if module has custom completion rules */
347 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
349 /** True if module supports outcomes */
350 define('FEATURE_IDNUMBER', 'idnumber');
351 /** True if module supports groups */
352 define('FEATURE_GROUPS', 'groups');
353 /** True if module supports groupings */
354 define('FEATURE_GROUPINGS', 'groupings');
355 /** True if module supports groupmembersonly */
356 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
358 /** Type of module */
359 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
360 /** True if module supports intro editor */
361 define('FEATURE_MOD_INTRO', 'mod_intro');
362 /** True if module has default completion */
363 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
365 define('FEATURE_COMMENT', 'comment');
367 define('FEATURE_RATE', 'rate');
368 /** True if module supports backup/restore of moodle2 format */
369 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
371 /** Unspecified module archetype */
372 define('MOD_ARCHETYPE_OTHER', 0);
373 /** Resource-like type module */
374 define('MOD_ARCHETYPE_RESOURCE', 1);
375 /** Assignment module archetype */
376 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
379 * Security token used for allowing access
380 * from external application such as web services.
381 * Scripts do not use any session, performance is relatively
382 * low because we need to load access info in each request.
383 * Scripts are executed in parallel.
385 define('EXTERNAL_TOKEN_PERMANENT', 0);
388 * Security token used for allowing access
389 * of embedded applications, the code is executed in the
390 * active user session. Token is invalidated after user logs out.
391 * Scripts are executed serially - normal session locking is used.
393 define('EXTERNAL_TOKEN_EMBEDDED', 1);
396 * The home page should be the site home
398 define('HOMEPAGE_SITE', 0);
400 * The home page should be the users my page
402 define('HOMEPAGE_MY', 1);
404 * The home page can be chosen by the user
406 define('HOMEPAGE_USER', 2);
409 * Hub directory url (should be moodle.org)
411 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
415 * Moodle.org url (should be moodle.org)
417 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
420 /// PARAMETER HANDLING ////////////////////////////////////////////////////
423 * Returns a particular value for the named variable, taken from
424 * POST or GET. If the parameter doesn't exist then an error is
425 * thrown because we require this variable.
427 * This function should be used to initialise all required values
428 * in a script that are based on parameters. Usually it will be
430 * $id = required_param('id', PARAM_INT);
432 * @param string $parname the name of the page parameter we want,
433 * default PARAM_CLEAN
434 * @param int $type expected type of parameter
437 function required_param($parname, $type=PARAM_CLEAN) {
438 if (isset($_POST[$parname])) { // POST has precedence
439 $param = $_POST[$parname];
440 } else if (isset($_GET[$parname])) {
441 $param = $_GET[$parname];
443 print_error('missingparam', '', '', $parname);
446 return clean_param($param, $type);
450 * Returns a particular value for the named variable, taken from
451 * POST or GET, otherwise returning a given default.
453 * This function should be used to initialise all optional values
454 * in a script that are based on parameters. Usually it will be
456 * $name = optional_param('name', 'Fred', PARAM_TEXT);
458 * @param string $parname the name of the page parameter we want
459 * @param mixed $default the default value to return if nothing is found
460 * @param int $type expected type of parameter, default PARAM_CLEAN
463 function optional_param($parname, $default=NULL, $type=PARAM_CLEAN) {
464 if (isset($_POST[$parname])) { // POST has precedence
465 $param = $_POST[$parname];
466 } else if (isset($_GET[$parname])) {
467 $param = $_GET[$parname];
472 return clean_param($param, $type);
476 * Strict validation of parameter values, the values are only converted
477 * to requested PHP type. Internally it is using clean_param, the values
478 * before and after cleaning must be equal - otherwise
479 * an invalid_parameter_exception is thrown.
480 * Objects and classes are not accepted.
482 * @param mixed $param
483 * @param int $type PARAM_ constant
484 * @param bool $allownull are nulls valid value?
485 * @param string $debuginfo optional debug information
486 * @return mixed the $param value converted to PHP type or invalid_parameter_exception
488 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
489 if (is_null($param)) {
490 if ($allownull == NULL_ALLOWED) {
493 throw new invalid_parameter_exception($debuginfo);
496 if (is_array($param) or is_object($param)) {
497 throw new invalid_parameter_exception($debuginfo);
500 $cleaned = clean_param($param, $type);
501 if ((string)$param !== (string)$cleaned) {
502 // conversion to string is usually lossless
503 throw new invalid_parameter_exception($debuginfo);
510 * Used by {@link optional_param()} and {@link required_param()} to
511 * clean the variables and/or cast to specific types, based on
514 * $course->format = clean_param($course->format, PARAM_ALPHA);
515 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
518 * @param mixed $param the variable we are cleaning
519 * @param int $type expected format of param after cleaning.
522 function clean_param($param, $type) {
526 if (is_array($param)) { // Let's loop
528 foreach ($param as $key => $value) {
529 $newparam[$key] = clean_param($value, $type);
535 case PARAM_RAW: // no cleaning at all
538 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
539 if (is_numeric($param)) {
542 return clean_text($param); // Sweep for scripts, etc
544 case PARAM_CLEANHTML: // prepare html fragment for display, do not store it into db!!
545 $param = clean_text($param); // Sweep for scripts, etc
549 return (int)$param; // Convert to integer
553 return (float)$param; // Convert to float
555 case PARAM_ALPHA: // Remove everything not a-z
556 return preg_replace('/[^a-zA-Z]/i', '', $param);
558 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
559 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
561 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
562 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
564 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
565 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
567 case PARAM_SEQUENCE: // Remove everything not 0-9,
568 return preg_replace('/[^0-9,]/i', '', $param);
570 case PARAM_BOOL: // Convert to 1 or 0
571 $tempstr = strtolower($param);
572 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
574 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
577 $param = empty($param) ? 0 : 1;
581 case PARAM_NOTAGS: // Strip all tags
582 return strip_tags($param);
584 case PARAM_TEXT: // leave only tags needed for multilang
585 return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);
587 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
588 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
590 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
591 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
593 case PARAM_FILE: // Strip all suspicious characters from filename
594 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
595 $param = preg_replace('~\.\.+~', '', $param);
596 if ($param === '.') {
601 case PARAM_PATH: // Strip all suspicious characters from file path
602 $param = str_replace('\\', '/', $param);
603 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
604 $param = preg_replace('~\.\.+~', '', $param);
605 $param = preg_replace('~//+~', '/', $param);
606 return preg_replace('~/(\./)+~', '/', $param);
608 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
609 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
610 // match ipv4 dotted quad
611 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
612 // confirm values are ok
616 || $match[4] > 255 ) {
617 // hmmm, what kind of dotted quad is this?
620 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
621 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
622 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
624 // all is ok - $param is respected
631 case PARAM_URL: // allow safe ftp, http, mailto urls
632 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
633 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
634 // all is ok, param is respected
636 $param =''; // not really ok
640 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
641 $param = clean_param($param, PARAM_URL);
642 if (!empty($param)) {
643 if (preg_match(':^/:', $param)) {
644 // root-relative, ok!
645 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
646 // absolute, and matches our wwwroot
648 // relative - let's make sure there are no tricks
649 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
659 $param = trim($param);
660 // PEM formatted strings may contain letters/numbers and the symbols
664 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
665 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
666 list($wholething, $body) = $matches;
667 unset($wholething, $matches);
668 $b64 = clean_param($body, PARAM_BASE64);
670 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
678 if (!empty($param)) {
679 // PEM formatted strings may contain letters/numbers and the symbols
683 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
686 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
687 // Each line of base64 encoded data must be 64 characters in
688 // length, except for the last line which may be less than (or
689 // equal to) 64 characters long.
690 for ($i=0, $j=count($lines); $i < $j; $i++) {
692 if (64 < strlen($lines[$i])) {
698 if (64 != strlen($lines[$i])) {
702 return implode("\n",$lines);
708 //as long as magic_quotes_gpc is used, a backslash will be a
709 //problem, so remove *all* backslash.
710 //$param = str_replace('\\', '', $param);
711 //remove some nasties
712 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
713 //convert many whitespace chars into one
714 $param = preg_replace('/\s+/', ' ', $param);
715 $textlib = textlib_get_instance();
716 $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
721 $tags = explode(',', $param);
723 foreach ($tags as $tag) {
724 $res = clean_param($tag, PARAM_TAG);
730 return implode(',', $result);
735 case PARAM_CAPABILITY:
736 if (get_capability_info($param)) {
742 case PARAM_PERMISSION:
743 $param = (int)$param;
744 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
751 $param = clean_param($param, PARAM_SAFEDIR);
752 if (exists_auth_plugin($param)) {
759 $param = clean_param($param, PARAM_SAFEDIR);
760 if (get_string_manager()->translation_exists($param)) {
763 return ''; // Specified language is not installed or param malformed
767 $param = clean_param($param, PARAM_SAFEDIR);
768 if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
770 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
773 return ''; // Specified theme is not installed
777 $param = str_replace(" " , "", $param);
778 $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
779 if (empty($CFG->extendedusernamechars)) {
780 // regular expression, eliminate all chars EXCEPT:
781 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
782 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
787 if (validate_email($param)) {
794 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
800 default: // throw error, switched parameters in optional_param or another serious problem
801 print_error("unknownparamtype", '', '', $type);
806 * Return true if given value is integer or string with integer value
808 * @param mixed $value String or Int
809 * @return bool true if number, false if not
811 function is_number($value) {
812 if (is_int($value)) {
814 } else if (is_string($value)) {
815 return ((string)(int)$value) === $value;
822 * Returns host part from url
823 * @param string $url full url
824 * @return string host, null if not found
826 function get_host_from_url($url) {
827 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
835 * Tests whether anything was returned by text editor
837 * This function is useful for testing whether something you got back from
838 * the HTML editor actually contains anything. Sometimes the HTML editor
839 * appear to be empty, but actually you get back a <br> tag or something.
841 * @param string $string a string containing HTML.
842 * @return boolean does the string contain any actual content - that is text,
843 * images, objects, etc.
845 function html_is_blank($string) {
846 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
850 * Set a key in global configuration
852 * Set a key/value pair in both this session's {@link $CFG} global variable
853 * and in the 'config' database table for future sessions.
855 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
856 * In that case it doesn't affect $CFG.
858 * A NULL value will delete the entry.
862 * @param string $name the key to set
863 * @param string $value the value to set (without magic quotes)
864 * @param string $plugin (optional) the plugin scope, default NULL
865 * @return bool true or exception
867 function set_config($name, $value, $plugin=NULL) {
870 if (empty($plugin)) {
871 if (!array_key_exists($name, $CFG->config_php_settings)) {
872 // So it's defined for this invocation at least
873 if (is_null($value)) {
876 $CFG->$name = (string)$value; // settings from db are always strings
880 if ($DB->get_field('config', 'name', array('name'=>$name))) {
881 if ($value === null) {
882 $DB->delete_records('config', array('name'=>$name));
884 $DB->set_field('config', 'value', $value, array('name'=>$name));
887 if ($value !== null) {
888 $config = new object();
889 $config->name = $name;
890 $config->value = $value;
891 $DB->insert_record('config', $config, false);
895 } else { // plugin scope
896 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
898 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
900 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
903 if ($value !== null) {
904 $config = new object();
905 $config->plugin = $plugin;
906 $config->name = $name;
907 $config->value = $value;
908 $DB->insert_record('config_plugins', $config, false);
917 * Get configuration values from the global config table
918 * or the config_plugins table.
920 * If called with one parameter, it will load all the config
921 * variables for one plugin, and return them as an object.
923 * If called with 2 parameters it will return a string single
924 * value or false if the value is not found.
926 * @param string $plugin full component name
927 * @param string $name default NULL
928 * @return mixed hash-like object or single value, return false no config found
930 function get_config($plugin, $name = NULL) {
933 // normalise component name
934 if ($plugin === 'moodle' or $plugin === 'core') {
938 if (!empty($name)) { // the user is asking for a specific value
939 if (!empty($plugin)) {
940 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
941 // setting forced in config file
942 return $CFG->forced_plugin_settings[$plugin][$name];
944 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
947 if (array_key_exists($name, $CFG->config_php_settings)) {
948 // setting force in config file
949 return $CFG->config_php_settings[$name];
951 return $DB->get_field('config', 'value', array('name'=>$name));
956 // the user is after a recordset
958 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
959 if (isset($CFG->forced_plugin_settings[$plugin])) {
960 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
961 if (is_null($v) or is_array($v) or is_object($v)) {
962 // we do not want any extra mess here, just real settings that could be saved in db
963 unset($localcfg[$n]);
965 //convert to string as if it went through the DB
966 $localcfg[$n] = (string)$v;
970 return (object)$localcfg;
973 // this part is not really used any more, but anyway...
974 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
975 foreach($CFG->config_php_settings as $n=>$v) {
976 if (is_null($v) or is_array($v) or is_object($v)) {
977 // we do not want any extra mess here, just real settings that could be saved in db
978 unset($localcfg[$n]);
980 //convert to string as if it went through the DB
981 $localcfg[$n] = (string)$v;
984 return (object)$localcfg;
989 * Removes a key from global configuration
991 * @param string $name the key to set
992 * @param string $plugin (optional) the plugin scope
994 * @return boolean whether the operation succeeded.
996 function unset_config($name, $plugin=NULL) {
999 if (empty($plugin)) {
1001 $DB->delete_records('config', array('name'=>$name));
1003 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1010 * Remove all the config variables for a given plugin.
1012 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1013 * @return boolean whether the operation succeeded.
1015 function unset_all_config_for_plugin($plugin) {
1017 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1018 $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
1023 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1025 * All users are verified if they still have the necessary capability.
1027 * @param string $value the value of the config setting.
1028 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1029 * @param bool $include admins, include administrators
1030 * @return array of user objects.
1032 function get_users_from_config($value, $capability, $includeadmins = true) {
1035 if (empty($value) or $value === '$@NONE@$') {
1039 // we have to make sure that users still have the necessary capability,
1040 // it should be faster to fetch them all first and then test if they are present
1041 // instead of validating them one-by-one
1042 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1043 if ($includeadmins) {
1044 $admins = get_admins();
1045 foreach ($admins as $admin) {
1046 $users[$admin->id] = $admin;
1050 if ($value === '$@ALL@$') {
1054 $result = array(); // result in correct order
1055 $allowed = explode(',', $value);
1056 foreach ($allowed as $uid) {
1057 if (isset($users[$uid])) {
1058 $user = $users[$uid];
1059 $result[$user->id] = $user;
1068 * Invalidates browser caches and cached data in temp
1071 function purge_all_caches() {
1074 reset_text_filters_cache();
1075 js_reset_all_caches();
1076 theme_reset_all_caches();
1077 get_string_manager()->reset_caches();
1079 // purge all other caches: rss, simplepie, etc.
1080 remove_dir($CFG->dataroot.'/cache', true);
1082 // some more diagnostics in case site is misconfigured
1083 if (!check_dir_exists($CFG->dataroot.'/cache', true, true)) {
1084 debugging('Can not create cache directory, please check permissions in dataroot.');
1085 } else if (!is_writeable($CFG->dataroot.'/cache')) {
1086 debugging('Cache directory is not writeable, please verify permissions in dataroot.');
1093 * Get volatile flags
1095 * @param string $type
1096 * @param int $changedsince default null
1097 * @return records array
1099 function get_cache_flags($type, $changedsince=NULL) {
1102 $params = array('type'=>$type, 'expiry'=>time());
1103 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1104 if ($changedsince !== NULL) {
1105 $params['changedsince'] = $changedsince;
1106 $sqlwhere .= " AND timemodified > :changedsince";
1110 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1111 foreach ($flags as $flag) {
1112 $cf[$flag->name] = $flag->value;
1119 * Get volatile flags
1121 * @param string $type
1122 * @param string $name
1123 * @param int $changedsince default null
1124 * @return records array
1126 function get_cache_flag($type, $name, $changedsince=NULL) {
1129 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1131 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1132 if ($changedsince !== NULL) {
1133 $params['changedsince'] = $changedsince;
1134 $sqlwhere .= " AND timemodified > :changedsince";
1137 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1141 * Set a volatile flag
1143 * @param string $type the "type" namespace for the key
1144 * @param string $name the key to set
1145 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1146 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1147 * @return bool Always returns true
1149 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1152 $timemodified = time();
1153 if ($expiry===NULL || $expiry < $timemodified) {
1154 $expiry = $timemodified + 24 * 60 * 60;
1156 $expiry = (int)$expiry;
1159 if ($value === NULL) {
1160 unset_cache_flag($type,$name);
1164 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potentail problem in DEBUG_DEVELOPER
1165 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1166 return true; //no need to update; helps rcache too
1169 $f->expiry = $expiry;
1170 $f->timemodified = $timemodified;
1171 $DB->update_record('cache_flags', $f);
1174 $f->flagtype = $type;
1177 $f->expiry = $expiry;
1178 $f->timemodified = $timemodified;
1179 $DB->insert_record('cache_flags', $f);
1185 * Removes a single volatile flag
1188 * @param string $type the "type" namespace for the key
1189 * @param string $name the key to set
1192 function unset_cache_flag($type, $name) {
1194 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1199 * Garbage-collect volatile flags
1201 * @return bool Always returns true
1203 function gc_cache_flags() {
1205 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1209 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1212 * Refresh current $USER session global variable with all their current preferences.
1215 * @param mixed $time default null
1218 function check_user_preferences_loaded($time = null) {
1220 static $timenow = null; // Static cache, so we only check up-to-dateness once per request.
1222 if (!empty($USER->preference) && isset($USER->preference['_lastloaded'])) {
1223 // Already loaded. Are we up to date?
1225 if (is_null($timenow) || (!is_null($time) && $time != $timenow)) {
1227 if (!get_cache_flag('userpreferenceschanged', $USER->id, $USER->preference['_lastloaded'])) {
1228 // We are up-to-date.
1232 // Already checked for up-to-date-ness.
1237 // OK, so we have to reload. Reset preference
1238 $USER->preference = array();
1240 if (!isloggedin() or isguestuser()) {
1241 // No permanent storage for not-logged-in user and guest
1243 } else if ($preferences = $DB->get_records('user_preferences', array('userid'=>$USER->id))) {
1244 foreach ($preferences as $preference) {
1245 $USER->preference[$preference->name] = $preference->value;
1249 $USER->preference['_lastloaded'] = $timenow;
1253 * Called from set/delete_user_preferences, so that the prefs can be correctly reloaded.
1257 * @param integer $userid the user whose prefs were changed.
1259 function mark_user_preferences_changed($userid) {
1261 if ($userid == $USER->id) {
1262 check_user_preferences_loaded(time());
1264 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1268 * Sets a preference for the current user
1270 * Optionally, can set a preference for a different user object
1272 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
1276 * @param string $name The key to set as preference for the specified user
1277 * @param string $value The value to set for the $name key in the specified user's record
1278 * @param int $otheruserid A moodle user ID, default null
1281 function set_user_preference($name, $value, $otheruserid=NULL) {
1289 if (empty($otheruserid)){
1290 if (!isloggedin() or isguestuser()) {
1293 $userid = $USER->id;
1295 if (isguestuser($otheruserid)) {
1298 $userid = $otheruserid;
1302 // no permanent storage for not-logged-in user and guest
1304 } else if ($preference = $DB->get_record('user_preferences', array('userid'=>$userid, 'name'=>$name))) {
1305 if ($preference->value === $value) {
1308 $DB->set_field('user_preferences', 'value', (string)$value, array('id'=>$preference->id));
1311 $preference = new object();
1312 $preference->userid = $userid;
1313 $preference->name = $name;
1314 $preference->value = (string)$value;
1315 $DB->insert_record('user_preferences', $preference);
1318 mark_user_preferences_changed($userid);
1319 // update value in USER session if needed
1320 if ($userid == $USER->id) {
1321 $USER->preference[$name] = (string)$value;
1322 $USER->preference['_lastloaded'] = time();
1329 * Sets a whole array of preferences for the current user
1331 * @param array $prefarray An array of key/value pairs to be set
1332 * @param int $otheruserid A moodle user ID
1335 function set_user_preferences($prefarray, $otheruserid=NULL) {
1337 if (!is_array($prefarray) or empty($prefarray)) {
1341 foreach ($prefarray as $name => $value) {
1342 set_user_preference($name, $value, $otheruserid);
1348 * Unsets a preference completely by deleting it from the database
1350 * Optionally, can set a preference for a different user id
1353 * @param string $name The key to unset as preference for the specified user
1354 * @param int $otheruserid A moodle user ID
1356 function unset_user_preference($name, $otheruserid=NULL) {
1359 if (empty($otheruserid)){
1360 $userid = $USER->id;
1361 check_user_preferences_loaded();
1363 $userid = $otheruserid;
1367 $DB->delete_records('user_preferences', array('userid'=>$userid, 'name'=>$name));
1369 mark_user_preferences_changed($userid);
1370 //Delete the preference from $USER if needed
1371 if ($userid == $USER->id) {
1372 unset($USER->preference[$name]);
1373 $USER->preference['_lastloaded'] = time();
1380 * Used to fetch user preference(s)
1382 * If no arguments are supplied this function will return
1383 * all of the current user preferences as an array.
1385 * If a name is specified then this function
1386 * attempts to return that particular preference value. If
1387 * none is found, then the optional value $default is returned,
1392 * @param string $name Name of the key to use in finding a preference value
1393 * @param string $default Value to be returned if the $name key is not set in the user preferences
1394 * @param int $otheruserid A moodle user ID
1397 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
1400 if (empty($otheruserid) || (isloggedin() && ($USER->id == $otheruserid))){
1401 check_user_preferences_loaded();
1404 return $USER->preference; // All values
1405 } else if (array_key_exists($name, $USER->preference)) {
1406 return $USER->preference[$name]; // The single value
1408 return $default; // Default value (or NULL)
1413 return $DB->get_records_menu('user_preferences', array('userid'=>$otheruserid), '', 'name,value'); // All values
1414 } else if ($value = $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>$name))) {
1415 return $value; // The single value
1417 return $default; // Default value (or NULL)
1422 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1425 * Given date parts in user time produce a GMT timestamp.
1427 * @todo Finish documenting this function
1428 * @param int $year The year part to create timestamp of
1429 * @param int $month The month part to create timestamp of
1430 * @param int $day The day part to create timestamp of
1431 * @param int $hour The hour part to create timestamp of
1432 * @param int $minute The minute part to create timestamp of
1433 * @param int $second The second part to create timestamp of
1434 * @param float $timezone Timezone modifier
1435 * @param bool $applydst Toggle Daylight Saving Time, default true
1436 * @return int timestamp
1438 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1440 $strtimezone = NULL;
1441 if (!is_numeric($timezone)) {
1442 $strtimezone = $timezone;
1445 $timezone = get_user_timezone_offset($timezone);
1447 if (abs($timezone) > 13) {
1448 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1450 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1451 $time = usertime($time, $timezone);
1453 $time -= dst_offset_on($time, $strtimezone);
1462 * Format a date/time (seconds) as weeks, days, hours etc as needed
1464 * Given an amount of time in seconds, returns string
1465 * formatted nicely as weeks, days, hours etc as needed
1471 * @param int $totalsecs Time in seconds
1472 * @param object $str Should be a time object
1473 * @return string A nicely formatted date/time string
1475 function format_time($totalsecs, $str=NULL) {
1477 $totalsecs = abs($totalsecs);
1479 if (!$str) { // Create the str structure the slow way
1480 $str->day = get_string('day');
1481 $str->days = get_string('days');
1482 $str->hour = get_string('hour');
1483 $str->hours = get_string('hours');
1484 $str->min = get_string('min');
1485 $str->mins = get_string('mins');
1486 $str->sec = get_string('sec');
1487 $str->secs = get_string('secs');
1488 $str->year = get_string('year');
1489 $str->years = get_string('years');
1493 $years = floor($totalsecs/YEARSECS);
1494 $remainder = $totalsecs - ($years*YEARSECS);
1495 $days = floor($remainder/DAYSECS);
1496 $remainder = $totalsecs - ($days*DAYSECS);
1497 $hours = floor($remainder/HOURSECS);
1498 $remainder = $remainder - ($hours*HOURSECS);
1499 $mins = floor($remainder/MINSECS);
1500 $secs = $remainder - ($mins*MINSECS);
1502 $ss = ($secs == 1) ? $str->sec : $str->secs;
1503 $sm = ($mins == 1) ? $str->min : $str->mins;
1504 $sh = ($hours == 1) ? $str->hour : $str->hours;
1505 $sd = ($days == 1) ? $str->day : $str->days;
1506 $sy = ($years == 1) ? $str->year : $str->years;
1514 if ($years) $oyears = $years .' '. $sy;
1515 if ($days) $odays = $days .' '. $sd;
1516 if ($hours) $ohours = $hours .' '. $sh;
1517 if ($mins) $omins = $mins .' '. $sm;
1518 if ($secs) $osecs = $secs .' '. $ss;
1520 if ($years) return trim($oyears .' '. $odays);
1521 if ($days) return trim($odays .' '. $ohours);
1522 if ($hours) return trim($ohours .' '. $omins);
1523 if ($mins) return trim($omins .' '. $osecs);
1524 if ($secs) return $osecs;
1525 return get_string('now');
1529 * Returns a formatted string that represents a date in user time
1531 * Returns a formatted string that represents a date in user time
1532 * <b>WARNING: note that the format is for strftime(), not date().</b>
1533 * Because of a bug in most Windows time libraries, we can't use
1534 * the nicer %e, so we have to use %d which has leading zeroes.
1535 * A lot of the fuss in the function is just getting rid of these leading
1536 * zeroes as efficiently as possible.
1538 * If parameter fixday = true (default), then take off leading
1539 * zero from %d, else maintain it.
1541 * @param int $date the timestamp in UTC, as obtained from the database.
1542 * @param string $format strftime format. You should probably get this using
1543 * get_string('strftime...', 'langconfig');
1544 * @param float $timezone by default, uses the user's time zone.
1545 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1546 * If false then the leading zero is maintained.
1547 * @return string the formatted date/time.
1549 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1553 $strtimezone = NULL;
1554 if (!is_numeric($timezone)) {
1555 $strtimezone = $timezone;
1558 if (empty($format)) {
1559 $format = get_string('strftimedaydatetime', 'langconfig');
1562 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1564 } else if ($fixday) {
1565 $formatnoday = str_replace('%d', 'DD', $format);
1566 $fixday = ($formatnoday != $format);
1569 $date += dst_offset_on($date, $strtimezone);
1571 $timezone = get_user_timezone_offset($timezone);
1573 if (abs($timezone) > 13) { /// Server time
1575 $datestring = strftime($formatnoday, $date);
1576 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
1577 $datestring = str_replace('DD', $daystring, $datestring);
1579 $datestring = strftime($format, $date);
1582 $date += (int)($timezone * 3600);
1584 $datestring = gmstrftime($formatnoday, $date);
1585 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
1586 $datestring = str_replace('DD', $daystring, $datestring);
1588 $datestring = gmstrftime($format, $date);
1592 /// If we are running under Windows convert from windows encoding to UTF-8
1593 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1595 if ($CFG->ostype == 'WINDOWS') {
1596 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1597 $textlib = textlib_get_instance();
1598 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1606 * Given a $time timestamp in GMT (seconds since epoch),
1607 * returns an array that represents the date in user time
1609 * @todo Finish documenting this function
1611 * @param int $time Timestamp in GMT
1612 * @param float $timezone ?
1613 * @return array An array that represents the date in user time
1615 function usergetdate($time, $timezone=99) {
1617 $strtimezone = NULL;
1618 if (!is_numeric($timezone)) {
1619 $strtimezone = $timezone;
1622 $timezone = get_user_timezone_offset($timezone);
1624 if (abs($timezone) > 13) { // Server time
1625 return getdate($time);
1628 // There is no gmgetdate so we use gmdate instead
1629 $time += dst_offset_on($time, $strtimezone);
1630 $time += intval((float)$timezone * HOURSECS);
1632 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
1634 //be careful to ensure the returned array matches that produced by getdate() above
1637 $getdate['weekday'],
1644 $getdate['minutes'],
1646 ) = explode('_', $datestring);
1652 * Given a GMT timestamp (seconds since epoch), offsets it by
1653 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1656 * @param int $date Timestamp in GMT
1657 * @param float $timezone
1660 function usertime($date, $timezone=99) {
1662 $timezone = get_user_timezone_offset($timezone);
1664 if (abs($timezone) > 13) {
1667 return $date - (int)($timezone * HOURSECS);
1671 * Given a time, return the GMT timestamp of the most recent midnight
1672 * for the current user.
1674 * @param int $date Timestamp in GMT
1675 * @param float $timezone Defaults to user's timezone
1676 * @return int Returns a GMT timestamp
1678 function usergetmidnight($date, $timezone=99) {
1680 $userdate = usergetdate($date, $timezone);
1682 // Time of midnight of this user's day, in GMT
1683 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1688 * Returns a string that prints the user's timezone
1690 * @param float $timezone The user's timezone
1693 function usertimezone($timezone=99) {
1695 $tz = get_user_timezone($timezone);
1697 if (!is_float($tz)) {
1701 if(abs($tz) > 13) { // Server time
1702 return get_string('serverlocaltime');
1705 if($tz == intval($tz)) {
1706 // Don't show .0 for whole hours
1723 * Returns a float which represents the user's timezone difference from GMT in hours
1724 * Checks various settings and picks the most dominant of those which have a value
1728 * @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
1731 function get_user_timezone_offset($tz = 99) {
1735 $tz = get_user_timezone($tz);
1737 if (is_float($tz)) {
1740 $tzrecord = get_timezone_record($tz);
1741 if (empty($tzrecord)) {
1744 return (float)$tzrecord->gmtoff / HOURMINS;
1749 * Returns an int which represents the systems's timezone difference from GMT in seconds
1752 * @param mixed $tz timezone
1753 * @return int if found, false is timezone 99 or error
1755 function get_timezone_offset($tz) {
1762 if (is_numeric($tz)) {
1763 return intval($tz * 60*60);
1766 if (!$tzrecord = get_timezone_record($tz)) {
1769 return intval($tzrecord->gmtoff * 60);
1773 * Returns a float or a string which denotes the user's timezone
1774 * 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)
1775 * means that for this timezone there are also DST rules to be taken into account
1776 * Checks various settings and picks the most dominant of those which have a value
1780 * @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
1783 function get_user_timezone($tz = 99) {
1788 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1789 isset($USER->timezone) ? $USER->timezone : 99,
1790 isset($CFG->timezone) ? $CFG->timezone : 99,
1795 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
1796 $tz = $next['value'];
1799 return is_numeric($tz) ? (float) $tz : $tz;
1803 * Returns cached timezone record for given $timezonename
1807 * @param string $timezonename
1808 * @return mixed timezonerecord object or false
1810 function get_timezone_record($timezonename) {
1812 static $cache = NULL;
1814 if ($cache === NULL) {
1818 if (isset($cache[$timezonename])) {
1819 return $cache[$timezonename];
1822 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
1823 WHERE name = ? ORDER BY year DESC', array($timezonename), true);
1827 * Build and store the users Daylight Saving Time (DST) table
1832 * @param mixed $from_year Start year for the table, defaults to 1971
1833 * @param mixed $to_year End year for the table, defaults to 2035
1834 * @param mixed $strtimezone
1837 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
1838 global $CFG, $SESSION, $DB;
1840 $usertz = get_user_timezone($strtimezone);
1842 if (is_float($usertz)) {
1843 // Trivial timezone, no DST
1847 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1848 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1849 unset($SESSION->dst_offsets);
1850 unset($SESSION->dst_range);
1853 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1854 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1855 // This will be the return path most of the time, pretty light computationally
1859 // Reaching here means we either need to extend our table or create it from scratch
1861 // Remember which TZ we calculated these changes for
1862 $SESSION->dst_offsettz = $usertz;
1864 if(empty($SESSION->dst_offsets)) {
1865 // If we 're creating from scratch, put the two guard elements in there
1866 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1868 if(empty($SESSION->dst_range)) {
1869 // If creating from scratch
1870 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1871 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1873 // Fill in the array with the extra years we need to process
1874 $yearstoprocess = array();
1875 for($i = $from; $i <= $to; ++$i) {
1876 $yearstoprocess[] = $i;
1879 // Take note of which years we have processed for future calls
1880 $SESSION->dst_range = array($from, $to);
1883 // If needing to extend the table, do the same
1884 $yearstoprocess = array();
1886 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1887 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
1889 if($from < $SESSION->dst_range[0]) {
1890 // Take note of which years we need to process and then note that we have processed them for future calls
1891 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
1892 $yearstoprocess[] = $i;
1894 $SESSION->dst_range[0] = $from;
1896 if($to > $SESSION->dst_range[1]) {
1897 // Take note of which years we need to process and then note that we have processed them for future calls
1898 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
1899 $yearstoprocess[] = $i;
1901 $SESSION->dst_range[1] = $to;
1905 if(empty($yearstoprocess)) {
1906 // This means that there was a call requesting a SMALLER range than we have already calculated
1910 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1911 // Also, the array is sorted in descending timestamp order!
1915 static $presets_cache = array();
1916 if (!isset($presets_cache[$usertz])) {
1917 $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');
1919 if(empty($presets_cache[$usertz])) {
1923 // Remove ending guard (first element of the array)
1924 reset($SESSION->dst_offsets);
1925 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
1927 // Add all required change timestamps
1928 foreach($yearstoprocess as $y) {
1929 // Find the record which is in effect for the year $y
1930 foreach($presets_cache[$usertz] as $year => $preset) {
1936 $changes = dst_changes_for_year($y, $preset);
1938 if($changes === NULL) {
1941 if($changes['dst'] != 0) {
1942 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
1944 if($changes['std'] != 0) {
1945 $SESSION->dst_offsets[$changes['std']] = 0;
1949 // Put in a guard element at the top
1950 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1951 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1954 krsort($SESSION->dst_offsets);
1960 * Calculates the required DST change and returns a Timestamp Array
1964 * @param mixed $year Int or String Year to focus on
1965 * @param object $timezone Instatiated Timezone object
1966 * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
1968 function dst_changes_for_year($year, $timezone) {
1970 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1974 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1975 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1977 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1978 list($std_hour, $std_min) = explode(':', $timezone->std_time);
1980 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1981 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
1983 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1984 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1985 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1987 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1988 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
1990 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1994 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
1997 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2000 function dst_offset_on($time, $strtimezone = NULL) {
2003 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2007 reset($SESSION->dst_offsets);
2008 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2009 if($from <= $time) {
2014 // This is the normal return path
2015 if($offset !== NULL) {
2019 // Reaching this point means we haven't calculated far enough, do it now:
2020 // Calculate extra DST changes if needed and recurse. The recursion always
2021 // moves toward the stopping condition, so will always end.
2024 // We need a year smaller than $SESSION->dst_range[0]
2025 if($SESSION->dst_range[0] == 1971) {
2028 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2029 return dst_offset_on($time, $strtimezone);
2032 // We need a year larger than $SESSION->dst_range[1]
2033 if($SESSION->dst_range[1] == 2035) {
2036 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2037 return dst_offset_on($time, $strtimezone);
2044 * @todo Document what this function does
2045 * @param int $startday
2046 * @param int $weekday
2051 function find_day_in_month($startday, $weekday, $month, $year) {
2053 $daysinmonth = days_in_month($month, $year);
2055 if($weekday == -1) {
2056 // Don't care about weekday, so return:
2057 // abs($startday) if $startday != -1
2058 // $daysinmonth otherwise
2059 return ($startday == -1) ? $daysinmonth : abs($startday);
2062 // From now on we 're looking for a specific weekday
2064 // Give "end of month" its actual value, since we know it
2065 if($startday == -1) {
2066 $startday = -1 * $daysinmonth;
2069 // Starting from day $startday, the sign is the direction
2073 $startday = abs($startday);
2074 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2076 // This is the last such weekday of the month
2077 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2078 if($lastinmonth > $daysinmonth) {
2082 // Find the first such weekday <= $startday
2083 while($lastinmonth > $startday) {
2087 return $lastinmonth;
2092 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
2094 $diff = $weekday - $indexweekday;
2099 // This is the first such weekday of the month equal to or after $startday
2100 $firstfromindex = $startday + $diff;
2102 return $firstfromindex;
2108 * Calculate the number of days in a given month
2110 * @param int $month The month whose day count is sought
2111 * @param int $year The year of the month whose day count is sought
2114 function days_in_month($month, $year) {
2115 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
2119 * Calculate the position in the week of a specific calendar day
2121 * @param int $day The day of the date whose position in the week is sought
2122 * @param int $month The month of the date whose position in the week is sought
2123 * @param int $year The year of the date whose position in the week is sought
2126 function dayofweek($day, $month, $year) {
2127 // I wonder if this is any different from
2128 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2129 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
2132 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2135 * Returns full login url.
2137 * @return string login url
2139 function get_login_url() {
2142 $url = "$CFG->wwwroot/login/index.php";
2144 if (!empty($CFG->loginhttps)) {
2145 $url = str_replace('http:', 'https:', $url);
2152 * This function checks that the current user is logged in and has the
2153 * required privileges
2155 * This function checks that the current user is logged in, and optionally
2156 * whether they are allowed to be in a particular course and view a particular
2158 * If they are not logged in, then it redirects them to the site login unless
2159 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2160 * case they are automatically logged in as guests.
2161 * If $courseid is given and the user is not enrolled in that course then the
2162 * user is redirected to the course enrolment page.
2163 * If $cm is given and the course module is hidden and the user is not a teacher
2164 * in the course then the user is redirected to the course home page.
2166 * When $cm parameter specified, this function sets page layout to 'module'.
2167 * You need to change it manually later if some other layout needed.
2169 * @param mixed $courseorid id of the course or course object
2170 * @param bool $autologinguest default true
2171 * @param object $cm course module object
2172 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2173 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2174 * in order to keep redirects working properly. MDL-14495
2175 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2176 * @return mixed Void, exit, and die depending on path
2178 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2179 global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2181 // setup global $COURSE, themes, language and locale
2182 if (!empty($courseorid)) {
2183 if (is_object($courseorid)) {
2184 $course = $courseorid;
2185 } else if ($courseorid == SITEID) {
2186 $course = clone($SITE);
2188 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2191 if ($cm->course != $course->id) {
2192 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2194 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2195 $PAGE->set_pagelayout('incourse');
2197 $PAGE->set_course($course); // set's up global $COURSE
2200 // do not touch global $COURSE via $PAGE->set_course(),
2201 // the reasons is we need to be able to call require_login() at any time!!
2204 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2208 // If the user is not even logged in yet then make sure they are
2209 if (!isloggedin()) {
2210 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2211 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2212 // misconfigured site guest, just redirect to login page
2213 redirect(get_login_url());
2214 exit; // never reached
2216 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2217 complete_user_login($guest, false);
2218 $SESSION->lang = $lang;
2220 //NOTE: $USER->site check was obsoleted by session test cookie,
2221 // $USER->confirmed test is in login/index.php
2222 if ($preventredirect) {
2223 throw new require_login_exception('You are not logged in');
2226 if ($setwantsurltome) {
2227 // TODO: switch to PAGE->url
2228 $SESSION->wantsurl = $FULLME;
2230 if (!empty($_SERVER['HTTP_REFERER'])) {
2231 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2233 redirect(get_login_url());
2234 exit; // never reached
2238 // loginas as redirection if needed
2239 if ($course->id != SITEID and session_is_loggedinas()) {
2240 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2241 if ($USER->loginascontext->instanceid != $course->id) {
2242 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2247 // check whether the user should be changing password (but only if it is REALLY them)
2248 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2249 $userauth = get_auth_plugin($USER->auth);
2250 if ($userauth->can_change_password() and !$preventredirect) {
2251 $SESSION->wantsurl = $FULLME;
2252 if ($changeurl = $userauth->change_password_url()) {
2253 //use plugin custom url
2254 redirect($changeurl);
2256 //use moodle internal method
2257 if (empty($CFG->loginhttps)) {
2258 redirect($CFG->wwwroot .'/login/change_password.php');
2260 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2261 redirect($wwwroot .'/login/change_password.php');
2265 print_error('nopasswordchangeforced', 'auth');
2269 // Check that the user account is properly set up
2270 if (user_not_fully_set_up($USER)) {
2271 if ($preventredirect) {
2272 throw new require_login_exception('User not fully set-up');
2274 $SESSION->wantsurl = $FULLME;
2275 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2278 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2281 // Do not bother admins with any formalities
2282 if (is_siteadmin()) {
2283 //set accesstime or the user will appear offline which messes up messaging
2284 user_accesstime_log($course->id);
2288 // Check that the user has agreed to a site policy if there is one
2289 if (!empty($CFG->sitepolicy)) {
2290 if ($preventredirect) {
2291 throw new require_login_exception('Policy not agreed');
2293 if (!$USER->policyagreed) {
2294 $SESSION->wantsurl = $FULLME;
2295 redirect($CFG->wwwroot .'/user/policy.php');
2299 // Fetch the system context, the course context, and prefetch its child contexts
2300 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2301 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2303 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2308 // If the site is currently under maintenance, then print a message
2309 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2310 if ($preventredirect) {
2311 throw new require_login_exception('Maintenance in progress');
2314 print_maintenance_message();
2317 // make sure the course itself is not hidden
2318 if ($course->id == SITEID) {
2319 // frontpage can not be hidden
2321 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2322 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2324 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2325 // originally there was also test of parent category visibility,
2326 // BUT is was very slow in complex queries involving "my courses"
2327 // now it is also possible to simply hide all courses user is not enrolled in :-)
2328 if ($preventredirect) {
2329 throw new require_login_exception('Course is hidden');
2331 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2336 // is the user enrolled?
2337 if ($course->id == SITEID) {
2338 // everybody is enrolled on the frontpage
2341 if (session_is_loggedinas()) {
2342 // Make sure the REAL person can access this course first
2343 $realuser = session_get_realuser();
2344 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2345 if ($preventredirect) {
2346 throw new require_login_exception('Invalid course login-as access');
2348 echo $OUTPUT->header();
2349 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2353 // very simple enrolment caching - changes in course setting are not reflected immediately
2354 if (!isset($USER->enrol)) {
2355 $USER->enrol = array();
2356 $USER->enrol['enrolled'] = array();
2357 $USER->enrol['tempguest'] = array();
2362 if (is_viewing($coursecontext, $USER)) {
2363 // ok, no need to mess with enrol
2367 if (isset($USER->enrol['enrolled'][$course->id])) {
2368 if ($USER->enrol['enrolled'][$course->id] == 0) {
2370 } else if ($USER->enrol['enrolled'][$course->id] > time()) {
2374 unset($USER->enrol['enrolled'][$course->id]);
2377 if (isset($USER->enrol['tempguest'][$course->id])) {
2378 if ($USER->enrol['tempguest'][$course->id] == 0) {
2380 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2384 unset($USER->enrol['tempguest'][$course->id]);
2385 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2391 } else if (is_enrolled($coursecontext, $USER, '', true)) {
2392 // active participants may always access
2393 // TODO: refactor this into some new function
2395 $sql = "SELECT MAX(ue.timeend)
2396 FROM {user_enrolments} ue
2397 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2398 JOIN {user} u ON u.id = ue.userid
2399 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0
2400 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
2401 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE,
2402 'userid'=>$USER->id, 'courseid'=>$coursecontext->instanceid, 'now1'=>$now, 'now2'=>$now);
2403 $until = $DB->get_field_sql($sql, $params);
2404 if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) {
2405 $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD;
2408 $USER->enrol['enrolled'][$course->id] = $until;
2411 // remove traces of previous temp guest access
2412 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2415 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2416 $enrols = enrol_get_plugins(true);
2417 // first ask all enabled enrol instances in course if they want to auto enrol user
2418 foreach($instances as $instance) {
2419 if (!isset($enrols[$instance->enrol])) {
2422 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2423 if ($until !== false) {
2424 $USER->enrol['enrolled'][$course->id] = $until;
2425 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2430 // if not enrolled yet try to gain temporary guest access
2432 foreach($instances as $instance) {
2433 if (!isset($enrols[$instance->enrol])) {
2436 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2437 if ($until !== false) {
2438 $USER->enrol['tempguest'][$course->id] = $until;
2448 if ($preventredirect) {
2449 throw new require_login_exception('Not enrolled');
2451 $SESSION->wantsurl = $FULLME;
2452 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2457 if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2458 if ($preventredirect) {
2459 throw new require_login_exception('Activity is hidden');
2461 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2464 // groupmembersonly access control
2465 if (!empty($CFG->enablegroupmembersonly) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2466 if (isguestuser() or !groups_has_membership($cm)) {
2467 if ($preventredirect) {
2468 throw new require_login_exception('Not member of a group');
2470 print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
2474 // Conditional activity access control
2475 if (!empty($CFG->enableavailability) and $cm) {
2476 // TODO: this is going to work with login-as-user, sorry!
2477 // We cache conditional access in session
2478 if (!isset($SESSION->conditionaccessok)) {
2479 $SESSION->conditionaccessok = array();
2481 // If you have been allowed into the module once then you are allowed
2482 // in for rest of session, no need to do conditional checks
2483 if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
2484 // Get condition info (does a query for the availability table)
2485 require_once($CFG->libdir.'/conditionlib.php');
2486 $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
2487 // Check condition for user (this will do a query if the availability
2488 // information depends on grade or completion information)
2489 if ($ci->is_available($junk) || has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2490 $SESSION->conditionaccessok[$cm->id] = true;
2492 print_error('activityiscurrentlyhidden');
2497 // Finally access granted, update lastaccess times
2498 user_accesstime_log($course->id);
2503 * This function just makes sure a user is logged out.
2507 function require_logout() {
2511 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2513 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2514 foreach($authsequence as $authname) {
2515 $authplugin = get_auth_plugin($authname);
2516 $authplugin->prelogout_hook();
2520 session_get_instance()->terminate_current();
2524 * Weaker version of require_login()
2526 * This is a weaker version of {@link require_login()} which only requires login
2527 * when called from within a course rather than the site page, unless
2528 * the forcelogin option is turned on.
2529 * @see require_login()
2532 * @param mixed $courseorid The course object or id in question
2533 * @param bool $autologinguest Allow autologin guests if that is wanted
2534 * @param object $cm Course activity module if known
2535 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2536 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2537 * in order to keep redirects working properly. MDL-14495
2538 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2541 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2542 global $CFG, $PAGE, $SITE;
2543 if (!empty($CFG->forcelogin)) {
2544 // login required for both SITE and courses
2545 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2547 } else if (!empty($cm) and !$cm->visible) {
2548 // always login for hidden activities
2549 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2551 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2552 or (!is_object($courseorid) and $courseorid == SITEID)) {
2553 //login for SITE not required
2554 if ($cm and empty($cm->visible)) {
2555 // hidden activities are not accessible without login
2556 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2557 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2558 // not-logged-in users do not have any group membership
2559 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2561 // We still need to instatiate PAGE vars properly so that things
2562 // that rely on it like navigation function correctly.
2563 if (!empty($courseorid)) {
2564 if (is_object($courseorid)) {
2565 $course = $courseorid;
2567 $course = clone($SITE);
2570 if ($cm->course != $course->id) {
2571 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2573 $PAGE->set_cm($cm, $course);
2574 $PAGE->set_pagelayout('incourse');
2576 $PAGE->set_course($course);
2579 // If $PAGE->course, and hence $PAGE->context, have not already been set
2580 // up properly, set them up now.
2581 $PAGE->set_course($PAGE->course);
2583 //TODO: verify conditional activities here
2584 user_accesstime_log(SITEID);
2589 // course login always required
2590 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2595 * Require key login. Function terminates with error if key not found or incorrect.
2601 * @uses NO_MOODLE_COOKIES
2602 * @uses PARAM_ALPHANUM
2603 * @param string $script unique script identifier
2604 * @param int $instance optional instance id
2605 * @return int Instance ID
2607 function require_user_key_login($script, $instance=null) {
2608 global $USER, $SESSION, $CFG, $DB;
2610 if (!NO_MOODLE_COOKIES) {
2611 print_error('sessioncookiesdisable');
2615 @session_write_close();
2617 $keyvalue = required_param('key', PARAM_ALPHANUM);
2619 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2620 print_error('invalidkey');
2623 if (!empty($key->validuntil) and $key->validuntil < time()) {
2624 print_error('expiredkey');
2627 if ($key->iprestriction) {
2628 $remoteaddr = getremoteaddr(null);
2629 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2630 print_error('ipmismatch');
2634 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2635 print_error('invaliduserid');
2638 /// emulate normal session
2639 session_set_user($user);
2641 /// note we are not using normal login
2642 if (!defined('USER_KEY_LOGIN')) {
2643 define('USER_KEY_LOGIN', true);
2646 /// return instance id - it might be empty
2647 return $key->instance;
2651 * Creates a new private user access key.
2654 * @param string $script unique target identifier
2655 * @param int $userid
2656 * @param int $instance optional instance id
2657 * @param string $iprestriction optional ip restricted access
2658 * @param timestamp $validuntil key valid only until given data
2659 * @return string access key value
2661 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2664 $key = new object();
2665 $key->script = $script;
2666 $key->userid = $userid;
2667 $key->instance = $instance;
2668 $key->iprestriction = $iprestriction;
2669 $key->validuntil = $validuntil;
2670 $key->timecreated = time();
2672 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
2673 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
2675 $key->value = md5($userid.'_'.time().random_string(40));
2677 $DB->insert_record('user_private_key', $key);
2682 * Delete the user's new private user access keys for a particular script.
2685 * @param string $script unique target identifier
2686 * @param int $userid
2689 function delete_user_key($script,$userid) {
2691 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
2695 * Gets a private user access key (and creates one if one doesn't exist).
2698 * @param string $script unique target identifier
2699 * @param int $userid
2700 * @param int $instance optional instance id
2701 * @param string $iprestriction optional ip restricted access
2702 * @param timestamp $validuntil key valid only until given data
2703 * @return string access key value
2705 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2708 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
2709 'instance'=>$instance, 'iprestriction'=>$iprestriction,
2710 'validuntil'=>$validuntil))) {
2713 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
2719 * Modify the user table by setting the currently logged in user's
2720 * last login to now.
2724 * @return bool Always returns true
2726 function update_user_login_times() {
2729 $user = new object();
2730 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2731 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2733 $user->id = $USER->id;
2735 $DB->update_record('user', $user);
2740 * Determines if a user has completed setting up their account.
2742 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
2745 function user_not_fully_set_up($user) {
2746 if (isguestuser($user)) {
2749 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
2753 * Check whether the user has exceeded the bounce threshold
2757 * @param user $user A {@link $USER} object
2758 * @return bool true=>User has exceeded bounce threshold
2760 function over_bounce_threshold($user) {
2763 if (empty($CFG->handlebounces)) {
2767 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2771 // set sensible defaults
2772 if (empty($CFG->minbounces)) {
2773 $CFG->minbounces = 10;
2775 if (empty($CFG->bounceratio)) {
2776 $CFG->bounceratio = .20;
2780 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2781 $bouncecount = $bounce->value;
2783 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2784 $sendcount = $send->value;
2786 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2790 * Used to increment or reset email sent count
2793 * @param user $user object containing an id
2794 * @param bool $reset will reset the count to 0
2797 function set_send_count($user,$reset=false) {
2800 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2804 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2805 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2806 $DB->update_record('user_preferences', $pref);
2808 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2810 $pref = new object();
2811 $pref->name = 'email_send_count';
2813 $pref->userid = $user->id;
2814 $DB->insert_record('user_preferences', $pref, false);
2819 * Increment or reset user's email bounce count
2822 * @param user $user object containing an id
2823 * @param bool $reset will reset the count to 0
2825 function set_bounce_count($user,$reset=false) {
2828 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2829 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2830 $DB->update_record('user_preferences', $pref);
2832 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2834 $pref = new object();
2835 $pref->name = 'email_bounce_count';
2837 $pref->userid = $user->id;
2838 $DB->insert_record('user_preferences', $pref, false);
2843 * Keeps track of login attempts
2847 function update_login_count() {
2852 if (empty($SESSION->logincount)) {
2853 $SESSION->logincount = 1;
2855 $SESSION->logincount++;
2858 if ($SESSION->logincount > $max_logins) {
2859 unset($SESSION->wantsurl);
2860 print_error('errortoomanylogins');
2865 * Resets login attempts
2869 function reset_login_count() {
2872 $SESSION->logincount = 0;
2876 * Returns reference to full info about modules in course (including visibility).
2877 * Cached and as fast as possible (0 or 1 db query).
2882 * @uses CONTEXT_MODULE
2883 * @uses MAX_MODINFO_CACHE_SIZE
2884 * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
2885 * @param int $userid Defaults to current user id
2886 * @return mixed courseinfo object or nothing if resetting
2888 function &get_fast_modinfo(&$course, $userid=0) {
2889 global $CFG, $USER, $DB;
2890 require_once($CFG->dirroot.'/course/lib.php');
2892 if (!empty($CFG->enableavailability)) {
2893 require_once($CFG->libdir.'/conditionlib.php');
2896 static $cache = array();
2898 if ($course === 'reset') {
2901 return $nothing; // we must return some reference
2904 if (empty($userid)) {
2905 $userid = $USER->id;
2908 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
2909 return $cache[$course->id];
2912 if (empty($course->modinfo)) {
2913 // no modinfo yet - load it
2914 rebuild_course_cache($course->id);
2915 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2918 $modinfo = new object();
2919 $modinfo->courseid = $course->id;
2920 $modinfo->userid = $userid;
2921 $modinfo->sections = array();
2922 $modinfo->cms = array();
2923 $modinfo->instances = array();
2924 $modinfo->groups = null; // loaded only when really needed - the only one db query
2926 $info = unserialize($course->modinfo);
2927 if (!is_array($info)) {
2928 // hmm, something is wrong - lets try to fix it
2929 rebuild_course_cache($course->id);
2930 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2931 $info = unserialize($course->modinfo);
2932 if (!is_array($info)) {
2938 // detect if upgrade required
2939 $first = reset($info);
2940 if (!isset($first->id)) {
2941 rebuild_course_cache($course->id);
2942 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2943 $info = unserialize($course->modinfo);
2944 if (!is_array($info)) {
2950 $modlurals = array();
2952 // If we haven't already preloaded contexts for the course, do it now
2953 preload_course_contexts($course->id);
2955 foreach ($info as $mod) {
2956 if (empty($mod->name)) {
2957 // something is wrong here
2960 // reconstruct minimalistic $cm
2963 $cm->instance = $mod->id;
2964 $cm->course = $course->id;
2965 $cm->modname = $mod->mod;
2966 $cm->idnumber = $mod->idnumber;
2967 $cm->name = $mod->name;
2968 $cm->visible = $mod->visible;
2969 $cm->sectionnum = $mod->section;
2970 $cm->groupmode = $mod->groupmode;
2971 $cm->groupingid = $mod->groupingid;
2972 $cm->groupmembersonly = $mod->groupmembersonly;
2973 $cm->indent = $mod->indent;
2974 $cm->completion = $mod->completion;
2975 $cm->extra = isset($mod->extra) ? $mod->extra : '';
2976 $cm->icon = isset($mod->icon) ? $mod->icon : '';
2977 $cm->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
2978 $cm->uservisible = true;
2979 if(!empty($CFG->enableavailability)) {
2980 // We must have completion information from modinfo. If it's not
2981 // there, cache needs rebuilding
2982 if(!isset($mod->availablefrom)) {
2983 debugging('enableavailability option was changed; rebuilding '.
2984 'cache for course '.$course->id);
2985 rebuild_course_cache($course->id,true);
2986 // Re-enter this routine to do it all properly
2987 return get_fast_modinfo($course,$userid);
2989 $cm->availablefrom = $mod->availablefrom;
2990 $cm->availableuntil = $mod->availableuntil;
2991 $cm->showavailability = $mod->showavailability;
2992 $cm->conditionscompletion = $mod->conditionscompletion;
2993 $cm->conditionsgrade = $mod->conditionsgrade;
2996 // preload long names plurals and also check module is installed properly
2997 if (!isset($modlurals[$cm->modname])) {
2998 if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
3001 $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
3003 $cm->modplural = $modlurals[$cm->modname];
3004 $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id);
3006 if(!empty($CFG->enableavailability)) {
3007 // Unfortunately the next call really wants to call
3008 // get_fast_modinfo, but that would be recursive, so we fake up a
3009 // modinfo for it already
3010 if(empty($minimalmodinfo)) {
3011 $minimalmodinfo=new stdClass();
3012 $minimalmodinfo->cms=array();
3013 foreach($info as $mod) {
3014 if (empty($mod->name)) {
3015 // something is wrong here
3018 $minimalcm = new stdClass();
3019 $minimalcm->id = $mod->cm;
3020 $minimalcm->name = $mod->name;
3021 $minimalmodinfo->cms[$minimalcm->id]=$minimalcm;
3025 // Get availability information
3026 $ci = new condition_info($cm);
3027 $cm->available=$ci->is_available($cm->availableinfo, true, $userid, $minimalmodinfo);
3029 $cm->available=true;
3031 if ((!$cm->visible or !$cm->available) and !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
3032 $cm->uservisible = false;
3034 } else if (!empty($CFG->enablegroupmembersonly) and !empty($cm->groupmembersonly)
3035 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
3036 if (is_null($modinfo->groups)) {
3037 $modinfo->groups = groups_get_user_groups($course->id, $userid);
3039 if (empty($modinfo->groups[$cm->groupingid])) {
3040 $cm->uservisible = false;
3044 if (!isset($modinfo->instances[$cm->modname])) {
3045 $modinfo->instances[$cm->modname] = array();
3047 $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
3048 $modinfo->cms[$cm->id] =& $cm;
3050 // reconstruct sections
3051 if (!isset($modinfo->sections[$cm->sectionnum])) {
3052 $modinfo->sections[$cm->sectionnum] = array();
3054 $modinfo->sections[$cm->sectionnum][] = $cm->id;
3059 unset($cache[$course->id]); // prevent potential reference problems when switching users
3060 $cache[$course->id] = $modinfo;
3062 // Ensure cache does not use too much RAM
3063 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
3066 unset($cache[$key]);
3069 return $cache[$course->id];
3073 * Determines if the currently logged in user is in editing mode.
3074 * Note: originally this function had $userid parameter - it was not usable anyway
3076 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3077 * @todo Deprecated function remove when ready
3080 * @uses DEBUG_DEVELOPER
3083 function isediting() {
3085 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3086 return $PAGE->user_is_editing();
3090 * Determines if the logged in user is currently moving an activity
3093 * @param int $courseid The id of the course being tested
3096 function ismoving($courseid) {
3099 if (!empty($USER->activitycopy)) {
3100 return ($USER->activitycopycourse == $courseid);
3106 * Returns a persons full name
3108 * Given an object containing firstname and lastname
3109 * values, this function returns a string with the
3110 * full name of the person.
3111 * The result may depend on system settings
3112 * or language. 'override' will force both names
3113 * to be used even if system settings specify one.
3117 * @param object $user A {@link $USER} object to get full name of
3118 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3121 function fullname($user, $override=false) {
3122 global $CFG, $SESSION;
3124 if (!isset($user->firstname) and !isset($user->lastname)) {
3129 if (!empty($CFG->forcefirstname)) {
3130 $user->firstname = $CFG->forcefirstname;
3132 if (!empty($CFG->forcelastname)) {
3133 $user->lastname = $CFG->forcelastname;
3137 if (!empty($SESSION->fullnamedisplay)) {
3138 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3141 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3142 return $user->firstname .' '. $user->lastname;
3144 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3145 return $user->lastname .' '. $user->firstname;
3147 } else if ($CFG->fullnamedisplay == 'firstname') {
3149 return get_string('fullnamedisplay', '', $user);
3151 return $user->firstname;
3155 return get_string('fullnamedisplay', '', $user);
3159 * Returns whether a given authentication plugin exists.
3162 * @param string $auth Form of authentication to check for. Defaults to the
3163 * global setting in {@link $CFG}.
3164 * @return boolean Whether the plugin is available.
3166 function exists_auth_plugin($auth) {
3169 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3170 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3176 * Checks if a given plugin is in the list of enabled authentication plugins.
3178 * @param string $auth Authentication plugin.
3179 * @return boolean Whether the plugin is enabled.
3181 function is_enabled_auth($auth) {
3186 $enabled = get_enabled_auth_plugins();
3188 return in_array($auth, $enabled);
3192 * Returns an authentication plugin instance.
3195 * @param string $auth name of authentication plugin
3196 * @return auth_plugin_base An instance of the required authentication plugin.
3198 function get_auth_plugin($auth) {
3201 // check the plugin exists first
3202 if (! exists_auth_plugin($auth)) {
3203 print_error('authpluginnotfound', 'debug', '', $auth);
3206 // return auth plugin instance
3207 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3208 $class = "auth_plugin_$auth";
3213 * Returns array of active auth plugins.
3215 * @param bool $fix fix $CFG->auth if needed
3218 function get_enabled_auth_plugins($fix=false) {
3221 $default = array('manual', 'nologin');
3223 if (empty($CFG->auth)) {
3226 $auths = explode(',', $CFG->auth);
3230 $auths = array_unique($auths);
3231 foreach($auths as $k=>$authname) {
3232 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3236 $newconfig = implode(',', $auths);
3237 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3238 set_config('auth', $newconfig);
3242 return (array_merge($default, $auths));
3246 * Returns true if an internal authentication method is being used.
3247 * if method not specified then, global default is assumed
3249 * @param string $auth Form of authentication required
3252 function is_internal_auth($auth) {
3253 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3254 return $authplugin->is_internal();
3258 * Returns true if the user is a 'restored' one
3260 * Used in the login process to inform the user
3261 * and allow him/her to reset the password
3265 * @param string $username username to be checked
3268 function is_restored_user($username) {
3271 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3275 * Returns an array of user fields
3277 * @return array User field/column names
3279 function get_user_fieldnames() {
3282 $fieldarray = $DB->get_columns('user');
3283 unset($fieldarray['id']);
3284 $fieldarray = array_keys($fieldarray);
3290 * Creates a bare-bones user record
3292 * @todo Outline auth types and provide code example
3296 * @param string $username New user's username to add to record
3297 * @param string $password New user's password to add to record
3298 * @param string $auth Form of authentication required
3299 * @return object A {@link $USER} object
3301 function create_user_record($username, $password, $auth='manual') {
3304 //just in case check text case
3305 $username = trim(moodle_strtolower($username));
3307 $authplugin = get_auth_plugin($auth);
3309 $newuser = new object();
3311 if ($newinfo = $authplugin->get_userinfo($username)) {
3312 $newinfo = truncate_userinfo($newinfo);
3313 foreach ($newinfo as $key => $value){
3314 $newuser->$key = $value;
3318 if (!empty($newuser->email)) {
3319 if (email_is_not_allowed($newuser->email)) {
3320 unset($newuser->email);
3324 if (!isset($newuser->city)) {
3325 $newuser->city = '';
3328 $newuser->auth = $auth;
3329 $newuser->username = $username;
3332 // user CFG lang for user if $newuser->lang is empty
3333 // or $user->lang is not an installed language
3334 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3335 $newuser->lang = $CFG->lang;
3337 $newuser->confirmed = 1;
3338 $newuser->lastip = getremoteaddr();
3339 $newuser->timemodified = time();
3340 $newuser->mnethostid = $CFG->mnet_localhost_id;
3342 $DB->insert_record('user', $newuser);
3343 $user = get_complete_user_data('username', $newuser->username);
3344 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3345 set_user_preference('auth_forcepasswordchange', 1, $user->id);
3347 update_internal_user_password($user, $password);
3352 * Will update a local user record from an external source
3355 * @param string $username New user's username to add to record
3356 * @param string $authplugin Unused
3357 * @return user A {@link $USER} object
3359 function update_user_record($username, $authplugin) {
3362 $username = trim(moodle_strtolower($username)); /// just in case check text case
3364 $oldinfo = $DB->get_record('user', array('username'=>$username), 'username, auth');
3365 $userauth = get_auth_plugin($oldinfo->auth);
3367 if ($newinfo = $userauth->get_userinfo($username)) {
3368 $newinfo = truncate_userinfo($newinfo);
3369 foreach ($newinfo as $key => $value){
3370 if ($key === 'username') {
3371 // 'username' is not a mapped updateable/lockable field, so skip it.
3374 $confval = $userauth->config->{'field_updatelocal_' . $key};
3375 $lockval = $userauth->config->{'field_lock_' . $key};
3376 if (empty($confval) || empty($lockval)) {
3379 if ($confval === 'onlogin') {
3380 // MDL-4207 Don't overwrite modified user profile values with
3381 // empty LDAP values when 'unlocked if empty' is set. The purpose
3382 // of the setting 'unlocked if empty' is to allow the user to fill
3383 // in a value for the selected field _if LDAP is giving
3384 // nothing_ for this field. Thus it makes sense to let this value
3385 // stand in until LDAP is giving a value for this field.
3386 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3387 $DB->set_field('user', $key, $value, array('username'=>$username));
3393 return get_complete_user_data('username', $username);
3397 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3398 * which may have large fields
3400 * @todo Add vartype handling to ensure $info is an array
3402 * @param array $info Array of user properties to truncate if needed
3403 * @return array The now truncated information that was passed in
3405 function truncate_userinfo($info) {
3406 // define the limits
3416 'institution' => 40,
3424 // apply where needed
3425 foreach (array_keys($info) as $key) {
3426 if (!empty($limit[$key])) {
3427 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
3435 * Marks user deleted in internal user database and notifies the auth plugin.
3436 * Also unenrols user from all roles and does other cleanup.
3438 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3440 * @param object $user User object before delete
3441 * @return boolean always true
3443 function delete_user($user) {
3445 require_once($CFG->libdir.'/grouplib.php');
3446 require_once($CFG->libdir.'/gradelib.php');
3447 require_once($CFG->dirroot.'/message/lib.php');
3449 // delete all grades - backup is kept in grade_grades_history table
3450 grade_user_delete($user->id);
3452 //move unread messages from this user to read
3453 message_move_userfrom_unread2read($user->id);
3455 // remove from all cohorts
3456 $DB->delete_records('cohort_members', array('userid'=>$user->id));
3458 // remove from all groups
3459 $DB->delete_records('groups_members', array('userid'=>$user->id));
3461 // brute force unenrol from all courses
3462 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
3464 // purge user preferences
3465 $DB->delete_records('user_preferences', array('userid'=>$user->id));
3467 // purge user extra profile info
3468 $DB->delete_records('user_info_data', array('userid'=>$user->id));
3470 // last course access not necessary either
3471 $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
3473 // final accesslib cleanup - removes all role assignments in user context and context itself, files, etc.
3474 delete_context(CONTEXT_USER, $user->id);
3476 require_once($CFG->dirroot.'/tag/lib.php');
3477 tag_set('user', $user->id, array());
3479 // workaround for bulk deletes of users with the same email address
3480 $delname = "$user->email.".time();
3481 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3485 // mark internal user record as "deleted"
3486 $updateuser = new object();
3487 $updateuser->id = $user->id;
3488 $updateuser->deleted = 1;
3489 $updateuser->username = $delname; // Remember it just in case
3490 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
3491 $updateuser->idnumber = ''; // Clear this field to free it up
3492 $updateuser->timemodified = time();
3494 $DB->update_record('user', $updateuser);
3496 // notify auth plugin - do not block the delete even when plugin fails
3497 $authplugin = get_auth_plugin($user->auth);
3498 $authplugin->user_delete($user);
3500 // any plugin that needs to cleanup should register this event
3501 events_trigger('user_deleted', $user);
3507 * Retrieve the guest user object
3511 * @return user A {@link $USER} object
3513 function guest_user() {
3516 if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
3517 $newuser->confirmed = 1;
3518 $newuser->lang = $CFG->lang;
3519 $newuser->lastip = getremoteaddr();
3526 * Authenticates a user against the chosen authentication mechanism
3528 * Given a username and password, this function looks them
3529 * up using the currently selected authentication mechanism,
3530 * and if the authentication is successful, it returns a
3531 * valid $user object from the 'user' table.
3533 * Uses auth_ functions from the currently active auth module
3535 * After authenticate_user_login() returns success, you will need to
3536 * log that the user has logged in, and call complete_user_login() to set
3541 * @param string $username User's username
3542 * @param string $password User's password
3543 * @return user|flase A {@link $USER} object or false if error
3545 function authenticate_user_login($username, $password) {
3546 global $CFG, $DB, $OUTPUT;
3548 $authsenabled = get_enabled_auth_plugins();
3550 if ($user = get_complete_user_data('username', $username)) {
3551 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
3552 if (!empty($user->suspended)) {
3553 add_to_log(0, 'login', 'error', 'index.php', $username);
3554 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3557 if ($auth=='nologin' or !is_enabled_auth($auth)) {
3558 add_to_log(0, 'login', 'error', 'index.php', $username);
3559 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3562 $auths = array($auth);
3565 // check if there's a deleted record (cheaply)
3566 if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
3567 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3571 $auths = $authsenabled;
3572 $user = new object();
3573 $user->id = 0; // User does not exist
3576 foreach ($auths as $auth) {
3577 $authplugin = get_auth_plugin($auth);
3579 // on auth fail fall through to the next plugin
3580 if (!$authplugin->user_login($username, $password)) {
3584 // successful authentication
3585 if ($user->id) { // User already exists in database
3586 if (empty($user->auth)) { // For some reason auth isn't set yet
3587 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
3588 $user->auth = $auth;
3590 if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3591 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
3592 $user->firstaccess = $user->timemodified;
3595 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3597 if (!$authplugin->is_internal()) { // update user record from external DB
3598 $user = update_user_record($username, get_auth_plugin($user->auth));
3601 // if user not found, create him
3602 $user = create_user_record($username, $password, $auth);
3605 $authplugin->sync_roles($user);
3607 foreach ($authsenabled as $hau) {
3608 $hauth = get_auth_plugin($hau);
3609 $hauth->user_authenticated_hook($user, $username, $password);
3612 if (empty($user->id)) {
3616 if (!empty($user->suspended)) {
3617 // just in case some auth plugin suspended account
3618 add_to_log(0, 'login', 'error', 'index.php', $username);
3619 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3626 // failed if all the plugins have failed
3627 add_to_log(0, 'login', 'error', 'index.php', $username);
3628 if (debugging('', DEBUG_ALL)) {
3629 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3635 * Call to complete the user login process after authenticate_user_login()
3636 * has succeeded. It will setup the $USER variable and other required bits
3640 * - It will NOT log anything -- up to the caller to decide what to log.
3645 * @param object $user
3646 * @param bool $setcookie
3647 * @return object A {@link $USER} object - BC only, do not use
3649 function complete_user_login($user, $setcookie=true) {
3650 global $CFG, $USER, $SESSION;
3652 // regenerate session id and delete old session,
3653 // this helps prevent session fixation attacks from the same domain
3654 session_regenerate_id(true);
3656 // check enrolments, load caps and setup $USER object
3657 session_set_user($user);
3659 update_user_login_times();
3660 set_login_session_preferences();
3662 if (isguestuser()) {
3663 // no need to continue when user is THE guest
3668 if (empty($CFG->nolastloggedin)) {
3669 set_moodle_cookie($USER->username);
3671 // do not store last logged in user in cookie
3672 // auth plugins can temporarily override this from loginpage_hook()
3673 // do not save $CFG->nolastloggedin in database!
3674 set_moodle_cookie('nobody');
3678 /// Select password change url
3679 $userauth = get_auth_plugin($USER->auth);
3681 /// check whether the user should be changing password
3682 if (get_user_preferences('auth_forcepasswordchange', false)){
3683 if ($userauth->can_change_password()) {
3684 if ($changeurl = $userauth->change_password_url()) {
3685 redirect($changeurl);
3687 redirect($CFG->httpswwwroot.'/login/change_password.php');
3690 print_error('nopasswordchangeforced', 'auth');
3697 * Compare password against hash stored in internal user table.
3698 * If necessary it also updates the stored hash to new format.
3701 * @param object $user
3702 * @param string $password plain text password
3703 * @return bool is password valid?
3705 function validate_internal_user_password(&$user, $password) {
3708 if (!isset($CFG->passwordsaltmain)) {
3709 $CFG->passwordsaltmain = '';