3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * moodlelib.php - Moodle main library
21 * Main library file of miscellaneous general-purpose Moodle functions.
22 * Other main libraries:
23 * - weblib.php - functions that produce web output
24 * - datalib.php - functions that access the database
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
34 * Used by some scripts to check they are being called by Moodle
36 define('MOODLE_INTERNAL', true);
38 /// Date and time constants ///
40 * Time constant - the number of seconds in a year
42 define('YEARSECS', 31536000);
45 * Time constant - the number of seconds in a week
47 define('WEEKSECS', 604800);
50 * Time constant - the number of seconds in a day
52 define('DAYSECS', 86400);
55 * Time constant - the number of seconds in an hour
57 define('HOURSECS', 3600);
60 * Time constant - the number of seconds in a minute
62 define('MINSECS', 60);
65 * Time constant - the number of minutes in a day
67 define('DAYMINS', 1440);
70 * Time constant - the number of minutes in an hour
72 define('HOURMINS', 60);
74 /// Parameter constants - every call to optional_param(), required_param() ///
75 /// or clean_param() should have a specified type of parameter. //////////////
80 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
82 define('PARAM_ALPHA', 'alpha');
85 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
86 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
88 define('PARAM_ALPHAEXT', 'alphaext');
91 * PARAM_ALPHANUM - expected numbers and letters only.
93 define('PARAM_ALPHANUM', 'alphanum');
96 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
98 define('PARAM_ALPHANUMEXT', 'alphanumext');
101 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
103 define('PARAM_AUTH', 'auth');
106 * PARAM_BASE64 - Base 64 encoded format
108 define('PARAM_BASE64', 'base64');
111 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
113 define('PARAM_BOOL', 'bool');
116 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
117 * checked against the list of capabilities in the database.
119 define('PARAM_CAPABILITY', 'capability');
122 * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes. It stays as HTML.
124 define('PARAM_CLEANHTML', 'cleanhtml');
127 * PARAM_EMAIL - an email address following the RFC
129 define('PARAM_EMAIL', 'email');
132 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
134 define('PARAM_FILE', 'file');
137 * PARAM_FLOAT - a real/floating point number.
139 define('PARAM_FLOAT', 'float');
142 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
144 define('PARAM_HOST', 'host');
147 * PARAM_INT - integers only, use when expecting only numbers.
149 define('PARAM_INT', 'int');
152 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
154 define('PARAM_LANG', 'lang');
157 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
159 define('PARAM_LOCALURL', 'localurl');
162 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
164 define('PARAM_NOTAGS', 'notags');
167 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
168 * note: the leading slash is not removed, window drive letter is not allowed
170 define('PARAM_PATH', 'path');
173 * PARAM_PEM - Privacy Enhanced Mail format
175 define('PARAM_PEM', 'pem');
178 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
180 define('PARAM_PERMISSION', 'permission');
183 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way
185 define('PARAM_RAW', 'raw');
188 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
190 define('PARAM_SAFEDIR', 'safedir');
193 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
195 define('PARAM_SAFEPATH', 'safepath');
198 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
200 define('PARAM_SEQUENCE', 'sequence');
203 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
205 define('PARAM_TAG', 'tag');
208 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
210 define('PARAM_TAGLIST', 'taglist');
213 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
215 define('PARAM_TEXT', 'text');
218 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
220 define('PARAM_THEME', 'theme');
223 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
225 define('PARAM_URL', 'url');
228 * 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!!
230 define('PARAM_USERNAME', 'username');
233 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
235 define('PARAM_STRINGID', 'stringid');
237 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
239 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
240 * It was one of the first types, that is why it is abused so much ;-)
242 define('PARAM_CLEAN', 'clean');
245 * PARAM_INTEGER - deprecated alias for PARAM_INT
247 define('PARAM_INTEGER', 'int');
250 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
252 define('PARAM_NUMBER', 'float');
255 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
256 * NOTE: originally alias for PARAM_APLHA
258 define('PARAM_ACTION', 'alphanumext');
261 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
262 * NOTE: originally alias for PARAM_APLHA
264 define('PARAM_FORMAT', 'alphanumext');
267 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
269 define('PARAM_MULTILANG', 'text');
272 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
274 define('PARAM_CLEANFILE', 'file');
279 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
281 define('VALUE_REQUIRED', 1);
284 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
286 define('VALUE_OPTIONAL', 2);
289 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
291 define('VALUE_DEFAULT', 0);
294 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
296 define('NULL_NOT_ALLOWED', false);
299 * NULL_ALLOWED - the parameter can be set to null in the database
301 define('NULL_ALLOWED', true);
305 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
307 define('PAGE_COURSE_VIEW', 'course-view');
309 /** Get remote addr constant */
310 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
311 /** Get remote addr constant */
312 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
314 /// Blog access level constant declaration ///
315 define ('BLOG_USER_LEVEL', 1);
316 define ('BLOG_GROUP_LEVEL', 2);
317 define ('BLOG_COURSE_LEVEL', 3);
318 define ('BLOG_SITE_LEVEL', 4);
319 define ('BLOG_GLOBAL_LEVEL', 5);
324 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
325 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
326 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
328 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
330 define('TAG_MAX_LENGTH', 50);
332 /// Password policy constants ///
333 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
334 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
335 define ('PASSWORD_DIGITS', '0123456789');
336 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
338 /// Feature constants ///
339 // Used for plugin_supports() to report features that are, or are not, supported by a module.
341 /** True if module can provide a grade */
342 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
343 /** True if module supports outcomes */
344 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
346 /** True if module has code to track whether somebody viewed it */
347 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
348 /** True if module has custom completion rules */
349 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
351 /** True if module supports outcomes */
352 define('FEATURE_IDNUMBER', 'idnumber');
353 /** True if module supports groups */
354 define('FEATURE_GROUPS', 'groups');
355 /** True if module supports groupings */
356 define('FEATURE_GROUPINGS', 'groupings');
357 /** True if module supports groupmembersonly */
358 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
360 /** Type of module */
361 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
362 /** True if module supports intro editor */
363 define('FEATURE_MOD_INTRO', 'mod_intro');
364 /** True if module has default completion */
365 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
367 define('FEATURE_COMMENT', 'comment');
369 define('FEATURE_RATE', 'rate');
370 /** True if module supports backup/restore of moodle2 format */
371 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
373 /** Unspecified module archetype */
374 define('MOD_ARCHETYPE_OTHER', 0);
375 /** Resource-like type module */
376 define('MOD_ARCHETYPE_RESOURCE', 1);
377 /** Assignment module archetype */
378 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
381 * Security token used for allowing access
382 * from external application such as web services.
383 * Scripts do not use any session, performance is relatively
384 * low because we need to load access info in each request.
385 * Scripts are executed in parallel.
387 define('EXTERNAL_TOKEN_PERMANENT', 0);
390 * Security token used for allowing access
391 * of embedded applications, the code is executed in the
392 * active user session. Token is invalidated after user logs out.
393 * Scripts are executed serially - normal session locking is used.
395 define('EXTERNAL_TOKEN_EMBEDDED', 1);
398 * The home page should be the site home
400 define('HOMEPAGE_SITE', 0);
402 * The home page should be the users my page
404 define('HOMEPAGE_MY', 1);
406 * The home page can be chosen by the user
408 define('HOMEPAGE_USER', 2);
411 * Hub directory url (should be moodle.org)
413 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
417 * Moodle.org url (should be moodle.org)
419 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
422 /// PARAMETER HANDLING ////////////////////////////////////////////////////
425 * Returns a particular value for the named variable, taken from
426 * POST or GET. If the parameter doesn't exist then an error is
427 * thrown because we require this variable.
429 * This function should be used to initialise all required values
430 * in a script that are based on parameters. Usually it will be
432 * $id = required_param('id', PARAM_INT);
434 * @param string $parname the name of the page parameter we want,
435 * default PARAM_CLEAN
436 * @param int $type expected type of parameter
439 function required_param($parname, $type=PARAM_CLEAN) {
440 if (isset($_POST[$parname])) { // POST has precedence
441 $param = $_POST[$parname];
442 } else if (isset($_GET[$parname])) {
443 $param = $_GET[$parname];
445 print_error('missingparam', '', '', $parname);
448 return clean_param($param, $type);
452 * Returns a particular value for the named variable, taken from
453 * POST or GET, otherwise returning a given default.
455 * This function should be used to initialise all optional values
456 * in a script that are based on parameters. Usually it will be
458 * $name = optional_param('name', 'Fred', PARAM_TEXT);
460 * @param string $parname the name of the page parameter we want
461 * @param mixed $default the default value to return if nothing is found
462 * @param int $type expected type of parameter, default PARAM_CLEAN
465 function optional_param($parname, $default=NULL, $type=PARAM_CLEAN) {
466 if (isset($_POST[$parname])) { // POST has precedence
467 $param = $_POST[$parname];
468 } else if (isset($_GET[$parname])) {
469 $param = $_GET[$parname];
474 return clean_param($param, $type);
478 * Strict validation of parameter values, the values are only converted
479 * to requested PHP type. Internally it is using clean_param, the values
480 * before and after cleaning must be equal - otherwise
481 * an invalid_parameter_exception is thrown.
482 * Objects and classes are not accepted.
484 * @param mixed $param
485 * @param int $type PARAM_ constant
486 * @param bool $allownull are nulls valid value?
487 * @param string $debuginfo optional debug information
488 * @return mixed the $param value converted to PHP type or invalid_parameter_exception
490 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
491 if (is_null($param)) {
492 if ($allownull == NULL_ALLOWED) {
495 throw new invalid_parameter_exception($debuginfo);
498 if (is_array($param) or is_object($param)) {
499 throw new invalid_parameter_exception($debuginfo);
502 $cleaned = clean_param($param, $type);
503 if ((string)$param !== (string)$cleaned) {
504 // conversion to string is usually lossless
505 throw new invalid_parameter_exception($debuginfo);
512 * Used by {@link optional_param()} and {@link required_param()} to
513 * clean the variables and/or cast to specific types, based on
516 * $course->format = clean_param($course->format, PARAM_ALPHA);
517 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
520 * @param mixed $param the variable we are cleaning
521 * @param int $type expected format of param after cleaning.
524 function clean_param($param, $type) {
528 if (is_array($param)) { // Let's loop
530 foreach ($param as $key => $value) {
531 $newparam[$key] = clean_param($value, $type);
537 case PARAM_RAW: // no cleaning at all
540 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
541 if (is_numeric($param)) {
544 return clean_text($param); // Sweep for scripts, etc
546 case PARAM_CLEANHTML: // prepare html fragment for display, do not store it into db!!
547 $param = clean_text($param); // Sweep for scripts, etc
551 return (int)$param; // Convert to integer
555 return (float)$param; // Convert to float
557 case PARAM_ALPHA: // Remove everything not a-z
558 return preg_replace('/[^a-zA-Z]/i', '', $param);
560 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
561 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
563 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
564 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
566 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
567 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
569 case PARAM_SEQUENCE: // Remove everything not 0-9,
570 return preg_replace('/[^0-9,]/i', '', $param);
572 case PARAM_BOOL: // Convert to 1 or 0
573 $tempstr = strtolower($param);
574 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
576 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
579 $param = empty($param) ? 0 : 1;
583 case PARAM_NOTAGS: // Strip all tags
584 return strip_tags($param);
586 case PARAM_TEXT: // leave only tags needed for multilang
587 return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);
589 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
590 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
592 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
593 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
595 case PARAM_FILE: // Strip all suspicious characters from filename
596 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
597 $param = preg_replace('~\.\.+~', '', $param);
598 if ($param === '.') {
603 case PARAM_PATH: // Strip all suspicious characters from file path
604 $param = str_replace('\\', '/', $param);
605 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
606 $param = preg_replace('~\.\.+~', '', $param);
607 $param = preg_replace('~//+~', '/', $param);
608 return preg_replace('~/(\./)+~', '/', $param);
610 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
611 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
612 // match ipv4 dotted quad
613 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
614 // confirm values are ok
618 || $match[4] > 255 ) {
619 // hmmm, what kind of dotted quad is this?
622 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
623 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
624 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
626 // all is ok - $param is respected
633 case PARAM_URL: // allow safe ftp, http, mailto urls
634 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
635 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
636 // all is ok, param is respected
638 $param =''; // not really ok
642 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
643 $param = clean_param($param, PARAM_URL);
644 if (!empty($param)) {
645 if (preg_match(':^/:', $param)) {
646 // root-relative, ok!
647 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
648 // absolute, and matches our wwwroot
650 // relative - let's make sure there are no tricks
651 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
661 $param = trim($param);
662 // PEM formatted strings may contain letters/numbers and the symbols
666 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
667 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
668 list($wholething, $body) = $matches;
669 unset($wholething, $matches);
670 $b64 = clean_param($body, PARAM_BASE64);
672 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
680 if (!empty($param)) {
681 // PEM formatted strings may contain letters/numbers and the symbols
685 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
688 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
689 // Each line of base64 encoded data must be 64 characters in
690 // length, except for the last line which may be less than (or
691 // equal to) 64 characters long.
692 for ($i=0, $j=count($lines); $i < $j; $i++) {
694 if (64 < strlen($lines[$i])) {
700 if (64 != strlen($lines[$i])) {
704 return implode("\n",$lines);
710 //as long as magic_quotes_gpc is used, a backslash will be a
711 //problem, so remove *all* backslash.
712 //$param = str_replace('\\', '', $param);
713 //remove some nasties
714 $param = preg_replace('~[[:cntrl:]]|[<>`]~', '', $param);
715 //convert many whitespace chars into one
716 $param = preg_replace('/\s+/', ' ', $param);
717 $textlib = textlib_get_instance();
718 $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
723 $tags = explode(',', $param);
725 foreach ($tags as $tag) {
726 $res = clean_param($tag, PARAM_TAG);
732 return implode(',', $result);
737 case PARAM_CAPABILITY:
738 if (get_capability_info($param)) {
744 case PARAM_PERMISSION:
745 $param = (int)$param;
746 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
753 $param = clean_param($param, PARAM_SAFEDIR);
754 if (exists_auth_plugin($param)) {
761 $param = clean_param($param, PARAM_SAFEDIR);
762 if (get_string_manager()->translation_exists($param)) {
765 return ''; // Specified language is not installed or param malformed
769 $param = clean_param($param, PARAM_SAFEDIR);
770 if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
772 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
775 return ''; // Specified theme is not installed
779 $param = str_replace(" " , "", $param);
780 $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
781 if (empty($CFG->extendedusernamechars)) {
782 // regular expression, eliminate all chars EXCEPT:
783 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
784 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
789 if (validate_email($param)) {
796 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
802 default: // throw error, switched parameters in optional_param or another serious problem
803 print_error("unknownparamtype", '', '', $type);
808 * Return true if given value is integer or string with integer value
810 * @param mixed $value String or Int
811 * @return bool true if number, false if not
813 function is_number($value) {
814 if (is_int($value)) {
816 } else if (is_string($value)) {
817 return ((string)(int)$value) === $value;
824 * Returns host part from url
825 * @param string $url full url
826 * @return string host, null if not found
828 function get_host_from_url($url) {
829 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
837 * Tests whether anything was returned by text editor
839 * This function is useful for testing whether something you got back from
840 * the HTML editor actually contains anything. Sometimes the HTML editor
841 * appear to be empty, but actually you get back a <br> tag or something.
843 * @param string $string a string containing HTML.
844 * @return boolean does the string contain any actual content - that is text,
845 * images, objects, etc.
847 function html_is_blank($string) {
848 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
852 * Set a key in global configuration
854 * Set a key/value pair in both this session's {@link $CFG} global variable
855 * and in the 'config' database table for future sessions.
857 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
858 * In that case it doesn't affect $CFG.
860 * A NULL value will delete the entry.
864 * @param string $name the key to set
865 * @param string $value the value to set (without magic quotes)
866 * @param string $plugin (optional) the plugin scope, default NULL
867 * @return bool true or exception
869 function set_config($name, $value, $plugin=NULL) {
872 if (empty($plugin)) {
873 if (!array_key_exists($name, $CFG->config_php_settings)) {
874 // So it's defined for this invocation at least
875 if (is_null($value)) {
878 $CFG->$name = (string)$value; // settings from db are always strings
882 if ($DB->get_field('config', 'name', array('name'=>$name))) {
883 if ($value === null) {
884 $DB->delete_records('config', array('name'=>$name));
886 $DB->set_field('config', 'value', $value, array('name'=>$name));
889 if ($value !== null) {
890 $config = new object();
891 $config->name = $name;
892 $config->value = $value;
893 $DB->insert_record('config', $config, false);
897 } else { // plugin scope
898 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
900 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
902 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
905 if ($value !== null) {
906 $config = new object();
907 $config->plugin = $plugin;
908 $config->name = $name;
909 $config->value = $value;
910 $DB->insert_record('config_plugins', $config, false);
919 * Get configuration values from the global config table
920 * or the config_plugins table.
922 * If called with one parameter, it will load all the config
923 * variables for one plugin, and return them as an object.
925 * If called with 2 parameters it will return a string single
926 * value or false if the value is not found.
928 * @param string $plugin full component name
929 * @param string $name default NULL
930 * @return mixed hash-like object or single value, return false no config found
932 function get_config($plugin, $name = NULL) {
935 // normalise component name
936 if ($plugin === 'moodle' or $plugin === 'core') {
940 if (!empty($name)) { // the user is asking for a specific value
941 if (!empty($plugin)) {
942 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
943 // setting forced in config file
944 return $CFG->forced_plugin_settings[$plugin][$name];
946 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
949 if (array_key_exists($name, $CFG->config_php_settings)) {
950 // setting force in config file
951 return $CFG->config_php_settings[$name];
953 return $DB->get_field('config', 'value', array('name'=>$name));
958 // the user is after a recordset
960 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
961 if (isset($CFG->forced_plugin_settings[$plugin])) {
962 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
963 if (is_null($v) or is_array($v) or is_object($v)) {
964 // we do not want any extra mess here, just real settings that could be saved in db
965 unset($localcfg[$n]);
967 //convert to string as if it went through the DB
968 $localcfg[$n] = (string)$v;
972 return (object)$localcfg;
975 // this part is not really used any more, but anyway...
976 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
977 foreach($CFG->config_php_settings as $n=>$v) {
978 if (is_null($v) or is_array($v) or is_object($v)) {
979 // we do not want any extra mess here, just real settings that could be saved in db
980 unset($localcfg[$n]);
982 //convert to string as if it went through the DB
983 $localcfg[$n] = (string)$v;
986 return (object)$localcfg;
991 * Removes a key from global configuration
993 * @param string $name the key to set
994 * @param string $plugin (optional) the plugin scope
996 * @return boolean whether the operation succeeded.
998 function unset_config($name, $plugin=NULL) {
1001 if (empty($plugin)) {
1003 $DB->delete_records('config', array('name'=>$name));
1005 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1012 * Remove all the config variables for a given plugin.
1014 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1015 * @return boolean whether the operation succeeded.
1017 function unset_all_config_for_plugin($plugin) {
1019 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1020 $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
1025 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1027 * All users are verified if they still have the necessary capability.
1029 * @param string $value the value of the config setting.
1030 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1031 * @param bool $include admins, include administrators
1032 * @return array of user objects.
1034 function get_users_from_config($value, $capability, $includeadmins = true) {
1037 if (empty($value) or $value === '$@NONE@$') {
1041 // we have to make sure that users still have the necessary capability,
1042 // it should be faster to fetch them all first and then test if they are present
1043 // instead of validating them one-by-one
1044 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1045 if ($includeadmins) {
1046 $admins = get_admins();
1047 foreach ($admins as $admin) {
1048 $users[$admin->id] = $admin;
1052 if ($value === '$@ALL@$') {
1056 $result = array(); // result in correct order
1057 $allowed = explode(',', $value);
1058 foreach ($allowed as $uid) {
1059 if (isset($users[$uid])) {
1060 $user = $users[$uid];
1061 $result[$user->id] = $user;
1069 * Get volatile flags
1071 * @param string $type
1072 * @param int $changedsince default null
1073 * @return records array
1075 function get_cache_flags($type, $changedsince=NULL) {
1078 $params = array('type'=>$type, 'expiry'=>time());
1079 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1080 if ($changedsince !== NULL) {
1081 $params['changedsince'] = $changedsince;
1082 $sqlwhere .= " AND timemodified > :changedsince";
1086 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1087 foreach ($flags as $flag) {
1088 $cf[$flag->name] = $flag->value;
1095 * Get volatile flags
1097 * @param string $type
1098 * @param string $name
1099 * @param int $changedsince default null
1100 * @return records array
1102 function get_cache_flag($type, $name, $changedsince=NULL) {
1105 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1107 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1108 if ($changedsince !== NULL) {
1109 $params['changedsince'] = $changedsince;
1110 $sqlwhere .= " AND timemodified > :changedsince";
1113 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1117 * Set a volatile flag
1119 * @param string $type the "type" namespace for the key
1120 * @param string $name the key to set
1121 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1122 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1123 * @return bool Always returns true
1125 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1128 $timemodified = time();
1129 if ($expiry===NULL || $expiry < $timemodified) {
1130 $expiry = $timemodified + 24 * 60 * 60;
1132 $expiry = (int)$expiry;
1135 if ($value === NULL) {
1136 unset_cache_flag($type,$name);
1140 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potentail problem in DEBUG_DEVELOPER
1141 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1142 return true; //no need to update; helps rcache too
1145 $f->expiry = $expiry;
1146 $f->timemodified = $timemodified;
1147 $DB->update_record('cache_flags', $f);
1150 $f->flagtype = $type;
1153 $f->expiry = $expiry;
1154 $f->timemodified = $timemodified;
1155 $DB->insert_record('cache_flags', $f);
1161 * Removes a single volatile flag
1164 * @param string $type the "type" namespace for the key
1165 * @param string $name the key to set
1168 function unset_cache_flag($type, $name) {
1170 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1175 * Garbage-collect volatile flags
1177 * @return bool Always returns true
1179 function gc_cache_flags() {
1181 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1185 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1188 * Refresh current $USER session global variable with all their current preferences.
1191 * @param mixed $time default null
1194 function check_user_preferences_loaded($time = null) {
1196 static $timenow = null; // Static cache, so we only check up-to-dateness once per request.
1198 if (!empty($USER->preference) && isset($USER->preference['_lastloaded'])) {
1199 // Already loaded. Are we up to date?
1201 if (is_null($timenow) || (!is_null($time) && $time != $timenow)) {
1203 if (!get_cache_flag('userpreferenceschanged', $USER->id, $USER->preference['_lastloaded'])) {
1204 // We are up-to-date.
1208 // Already checked for up-to-date-ness.
1213 // OK, so we have to reload. Reset preference
1214 $USER->preference = array();
1216 if (!isloggedin() or isguestuser()) {
1217 // No permanent storage for not-logged-in user and guest
1219 } else if ($preferences = $DB->get_records('user_preferences', array('userid'=>$USER->id))) {
1220 foreach ($preferences as $preference) {
1221 $USER->preference[$preference->name] = $preference->value;
1225 $USER->preference['_lastloaded'] = $timenow;
1229 * Called from set/delete_user_preferences, so that the prefs can be correctly reloaded.
1233 * @param integer $userid the user whose prefs were changed.
1235 function mark_user_preferences_changed($userid) {
1237 if ($userid == $USER->id) {
1238 check_user_preferences_loaded(time());
1240 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1244 * Sets a preference for the current user
1246 * Optionally, can set a preference for a different user object
1248 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
1252 * @param string $name The key to set as preference for the specified user
1253 * @param string $value The value to set for the $name key in the specified user's record
1254 * @param int $otheruserid A moodle user ID, default null
1257 function set_user_preference($name, $value, $otheruserid=NULL) {
1265 if (empty($otheruserid)){
1266 if (!isloggedin() or isguestuser()) {
1269 $userid = $USER->id;
1271 if (isguestuser($otheruserid)) {
1274 $userid = $otheruserid;
1278 // no permanent storage for not-logged-in user and guest
1280 } else if ($preference = $DB->get_record('user_preferences', array('userid'=>$userid, 'name'=>$name))) {
1281 if ($preference->value === $value) {
1284 $DB->set_field('user_preferences', 'value', (string)$value, array('id'=>$preference->id));
1287 $preference = new object();
1288 $preference->userid = $userid;
1289 $preference->name = $name;
1290 $preference->value = (string)$value;
1291 $DB->insert_record('user_preferences', $preference);
1294 mark_user_preferences_changed($userid);
1295 // update value in USER session if needed
1296 if ($userid == $USER->id) {
1297 $USER->preference[$name] = (string)$value;
1298 $USER->preference['_lastloaded'] = time();
1305 * Sets a whole array of preferences for the current user
1307 * @param array $prefarray An array of key/value pairs to be set
1308 * @param int $otheruserid A moodle user ID
1311 function set_user_preferences($prefarray, $otheruserid=NULL) {
1313 if (!is_array($prefarray) or empty($prefarray)) {
1317 foreach ($prefarray as $name => $value) {
1318 set_user_preference($name, $value, $otheruserid);
1324 * Unsets a preference completely by deleting it from the database
1326 * Optionally, can set a preference for a different user id
1329 * @param string $name The key to unset as preference for the specified user
1330 * @param int $otheruserid A moodle user ID
1332 function unset_user_preference($name, $otheruserid=NULL) {
1335 if (empty($otheruserid)){
1336 $userid = $USER->id;
1337 check_user_preferences_loaded();
1339 $userid = $otheruserid;
1343 $DB->delete_records('user_preferences', array('userid'=>$userid, 'name'=>$name));
1345 mark_user_preferences_changed($userid);
1346 //Delete the preference from $USER if needed
1347 if ($userid == $USER->id) {
1348 unset($USER->preference[$name]);
1349 $USER->preference['_lastloaded'] = time();
1356 * Used to fetch user preference(s)
1358 * If no arguments are supplied this function will return
1359 * all of the current user preferences as an array.
1361 * If a name is specified then this function
1362 * attempts to return that particular preference value. If
1363 * none is found, then the optional value $default is returned,
1368 * @param string $name Name of the key to use in finding a preference value
1369 * @param string $default Value to be returned if the $name key is not set in the user preferences
1370 * @param int $otheruserid A moodle user ID
1373 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
1376 if (empty($otheruserid) || (isloggedin() && ($USER->id == $otheruserid))){
1377 check_user_preferences_loaded();
1380 return $USER->preference; // All values
1381 } else if (array_key_exists($name, $USER->preference)) {
1382 return $USER->preference[$name]; // The single value
1384 return $default; // Default value (or NULL)
1389 return $DB->get_records_menu('user_preferences', array('userid'=>$otheruserid), '', 'name,value'); // All values
1390 } else if ($value = $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>$name))) {
1391 return $value; // The single value
1393 return $default; // Default value (or NULL)
1398 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1401 * Given date parts in user time produce a GMT timestamp.
1403 * @todo Finish documenting this function
1404 * @param int $year The year part to create timestamp of
1405 * @param int $month The month part to create timestamp of
1406 * @param int $day The day part to create timestamp of
1407 * @param int $hour The hour part to create timestamp of
1408 * @param int $minute The minute part to create timestamp of
1409 * @param int $second The second part to create timestamp of
1410 * @param float $timezone Timezone modifier
1411 * @param bool $applydst Toggle Daylight Saving Time, default true
1412 * @return int timestamp
1414 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1416 $strtimezone = NULL;
1417 if (!is_numeric($timezone)) {
1418 $strtimezone = $timezone;
1421 $timezone = get_user_timezone_offset($timezone);
1423 if (abs($timezone) > 13) {
1424 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1426 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1427 $time = usertime($time, $timezone);
1429 $time -= dst_offset_on($time, $strtimezone);
1438 * Format a date/time (seconds) as weeks, days, hours etc as needed
1440 * Given an amount of time in seconds, returns string
1441 * formatted nicely as weeks, days, hours etc as needed
1447 * @param int $totalsecs Time in seconds
1448 * @param object $str Should be a time object
1449 * @return string A nicely formatted date/time string
1451 function format_time($totalsecs, $str=NULL) {
1453 $totalsecs = abs($totalsecs);
1455 if (!$str) { // Create the str structure the slow way
1456 $str->day = get_string('day');
1457 $str->days = get_string('days');
1458 $str->hour = get_string('hour');
1459 $str->hours = get_string('hours');
1460 $str->min = get_string('min');
1461 $str->mins = get_string('mins');
1462 $str->sec = get_string('sec');
1463 $str->secs = get_string('secs');
1464 $str->year = get_string('year');
1465 $str->years = get_string('years');
1469 $years = floor($totalsecs/YEARSECS);
1470 $remainder = $totalsecs - ($years*YEARSECS);
1471 $days = floor($remainder/DAYSECS);
1472 $remainder = $totalsecs - ($days*DAYSECS);
1473 $hours = floor($remainder/HOURSECS);
1474 $remainder = $remainder - ($hours*HOURSECS);
1475 $mins = floor($remainder/MINSECS);
1476 $secs = $remainder - ($mins*MINSECS);
1478 $ss = ($secs == 1) ? $str->sec : $str->secs;
1479 $sm = ($mins == 1) ? $str->min : $str->mins;
1480 $sh = ($hours == 1) ? $str->hour : $str->hours;
1481 $sd = ($days == 1) ? $str->day : $str->days;
1482 $sy = ($years == 1) ? $str->year : $str->years;
1490 if ($years) $oyears = $years .' '. $sy;
1491 if ($days) $odays = $days .' '. $sd;
1492 if ($hours) $ohours = $hours .' '. $sh;
1493 if ($mins) $omins = $mins .' '. $sm;
1494 if ($secs) $osecs = $secs .' '. $ss;
1496 if ($years) return trim($oyears .' '. $odays);
1497 if ($days) return trim($odays .' '. $ohours);
1498 if ($hours) return trim($ohours .' '. $omins);
1499 if ($mins) return trim($omins .' '. $osecs);
1500 if ($secs) return $osecs;
1501 return get_string('now');
1505 * Returns a formatted string that represents a date in user time
1507 * Returns a formatted string that represents a date in user time
1508 * <b>WARNING: note that the format is for strftime(), not date().</b>
1509 * Because of a bug in most Windows time libraries, we can't use
1510 * the nicer %e, so we have to use %d which has leading zeroes.
1511 * A lot of the fuss in the function is just getting rid of these leading
1512 * zeroes as efficiently as possible.
1514 * If parameter fixday = true (default), then take off leading
1515 * zero from %d, else maintain it.
1517 * @param int $date the timestamp in UTC, as obtained from the database.
1518 * @param string $format strftime format. You should probably get this using
1519 * get_string('strftime...', 'langconfig');
1520 * @param float $timezone by default, uses the user's time zone.
1521 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1522 * If false then the leading zero is maintained.
1523 * @return string the formatted date/time.
1525 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1529 $strtimezone = NULL;
1530 if (!is_numeric($timezone)) {
1531 $strtimezone = $timezone;
1534 if (empty($format)) {
1535 $format = get_string('strftimedaydatetime', 'langconfig');
1538 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1540 } else if ($fixday) {
1541 $formatnoday = str_replace('%d', 'DD', $format);
1542 $fixday = ($formatnoday != $format);
1545 $date += dst_offset_on($date, $strtimezone);
1547 $timezone = get_user_timezone_offset($timezone);
1549 if (abs($timezone) > 13) { /// Server time
1551 $datestring = strftime($formatnoday, $date);
1552 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
1553 $datestring = str_replace('DD', $daystring, $datestring);
1555 $datestring = strftime($format, $date);
1558 $date += (int)($timezone * 3600);
1560 $datestring = gmstrftime($formatnoday, $date);
1561 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
1562 $datestring = str_replace('DD', $daystring, $datestring);
1564 $datestring = gmstrftime($format, $date);
1568 /// If we are running under Windows convert from windows encoding to UTF-8
1569 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1571 if ($CFG->ostype == 'WINDOWS') {
1572 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1573 $textlib = textlib_get_instance();
1574 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1582 * Given a $time timestamp in GMT (seconds since epoch),
1583 * returns an array that represents the date in user time
1585 * @todo Finish documenting this function
1587 * @param int $time Timestamp in GMT
1588 * @param float $timezone ?
1589 * @return array An array that represents the date in user time
1591 function usergetdate($time, $timezone=99) {
1593 $strtimezone = NULL;
1594 if (!is_numeric($timezone)) {
1595 $strtimezone = $timezone;
1598 $timezone = get_user_timezone_offset($timezone);
1600 if (abs($timezone) > 13) { // Server time
1601 return getdate($time);
1604 // There is no gmgetdate so we use gmdate instead
1605 $time += dst_offset_on($time, $strtimezone);
1606 $time += intval((float)$timezone * HOURSECS);
1608 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
1610 //be careful to ensure the returned array matches that produced by getdate() above
1613 $getdate['weekday'],
1620 $getdate['minutes'],
1622 ) = explode('_', $datestring);
1628 * Given a GMT timestamp (seconds since epoch), offsets it by
1629 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1632 * @param int $date Timestamp in GMT
1633 * @param float $timezone
1636 function usertime($date, $timezone=99) {
1638 $timezone = get_user_timezone_offset($timezone);
1640 if (abs($timezone) > 13) {
1643 return $date - (int)($timezone * HOURSECS);
1647 * Given a time, return the GMT timestamp of the most recent midnight
1648 * for the current user.
1650 * @param int $date Timestamp in GMT
1651 * @param float $timezone Defaults to user's timezone
1652 * @return int Returns a GMT timestamp
1654 function usergetmidnight($date, $timezone=99) {
1656 $userdate = usergetdate($date, $timezone);
1658 // Time of midnight of this user's day, in GMT
1659 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1664 * Returns a string that prints the user's timezone
1666 * @param float $timezone The user's timezone
1669 function usertimezone($timezone=99) {
1671 $tz = get_user_timezone($timezone);
1673 if (!is_float($tz)) {
1677 if(abs($tz) > 13) { // Server time
1678 return get_string('serverlocaltime');
1681 if($tz == intval($tz)) {
1682 // Don't show .0 for whole hours
1699 * Returns a float which represents the user's timezone difference from GMT in hours
1700 * Checks various settings and picks the most dominant of those which have a value
1704 * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
1707 function get_user_timezone_offset($tz = 99) {
1711 $tz = get_user_timezone($tz);
1713 if (is_float($tz)) {
1716 $tzrecord = get_timezone_record($tz);
1717 if (empty($tzrecord)) {
1720 return (float)$tzrecord->gmtoff / HOURMINS;
1725 * Returns an int which represents the systems's timezone difference from GMT in seconds
1728 * @param mixed $tz timezone
1729 * @return int if found, false is timezone 99 or error
1731 function get_timezone_offset($tz) {
1738 if (is_numeric($tz)) {
1739 return intval($tz * 60*60);
1742 if (!$tzrecord = get_timezone_record($tz)) {
1745 return intval($tzrecord->gmtoff * 60);
1749 * Returns a float or a string which denotes the user's timezone
1750 * 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)
1751 * means that for this timezone there are also DST rules to be taken into account
1752 * Checks various settings and picks the most dominant of those which have a value
1756 * @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
1759 function get_user_timezone($tz = 99) {
1764 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1765 isset($USER->timezone) ? $USER->timezone : 99,
1766 isset($CFG->timezone) ? $CFG->timezone : 99,
1771 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
1772 $tz = $next['value'];
1775 return is_numeric($tz) ? (float) $tz : $tz;
1779 * Returns cached timezone record for given $timezonename
1783 * @param string $timezonename
1784 * @return mixed timezonerecord object or false
1786 function get_timezone_record($timezonename) {
1788 static $cache = NULL;
1790 if ($cache === NULL) {
1794 if (isset($cache[$timezonename])) {
1795 return $cache[$timezonename];
1798 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
1799 WHERE name = ? ORDER BY year DESC', array($timezonename), true);
1803 * Build and store the users Daylight Saving Time (DST) table
1808 * @param mixed $from_year Start year for the table, defaults to 1971
1809 * @param mixed $to_year End year for the table, defaults to 2035
1810 * @param mixed $strtimezone
1813 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
1814 global $CFG, $SESSION, $DB;
1816 $usertz = get_user_timezone($strtimezone);
1818 if (is_float($usertz)) {
1819 // Trivial timezone, no DST
1823 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1824 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1825 unset($SESSION->dst_offsets);
1826 unset($SESSION->dst_range);
1829 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1830 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1831 // This will be the return path most of the time, pretty light computationally
1835 // Reaching here means we either need to extend our table or create it from scratch
1837 // Remember which TZ we calculated these changes for
1838 $SESSION->dst_offsettz = $usertz;
1840 if(empty($SESSION->dst_offsets)) {
1841 // If we 're creating from scratch, put the two guard elements in there
1842 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1844 if(empty($SESSION->dst_range)) {
1845 // If creating from scratch
1846 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1847 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1849 // Fill in the array with the extra years we need to process
1850 $yearstoprocess = array();
1851 for($i = $from; $i <= $to; ++$i) {
1852 $yearstoprocess[] = $i;
1855 // Take note of which years we have processed for future calls
1856 $SESSION->dst_range = array($from, $to);
1859 // If needing to extend the table, do the same
1860 $yearstoprocess = array();
1862 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1863 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
1865 if($from < $SESSION->dst_range[0]) {
1866 // Take note of which years we need to process and then note that we have processed them for future calls
1867 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
1868 $yearstoprocess[] = $i;
1870 $SESSION->dst_range[0] = $from;
1872 if($to > $SESSION->dst_range[1]) {
1873 // Take note of which years we need to process and then note that we have processed them for future calls
1874 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
1875 $yearstoprocess[] = $i;
1877 $SESSION->dst_range[1] = $to;
1881 if(empty($yearstoprocess)) {
1882 // This means that there was a call requesting a SMALLER range than we have already calculated
1886 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1887 // Also, the array is sorted in descending timestamp order!
1891 static $presets_cache = array();
1892 if (!isset($presets_cache[$usertz])) {
1893 $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');
1895 if(empty($presets_cache[$usertz])) {
1899 // Remove ending guard (first element of the array)
1900 reset($SESSION->dst_offsets);
1901 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
1903 // Add all required change timestamps
1904 foreach($yearstoprocess as $y) {
1905 // Find the record which is in effect for the year $y
1906 foreach($presets_cache[$usertz] as $year => $preset) {
1912 $changes = dst_changes_for_year($y, $preset);
1914 if($changes === NULL) {
1917 if($changes['dst'] != 0) {
1918 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
1920 if($changes['std'] != 0) {
1921 $SESSION->dst_offsets[$changes['std']] = 0;
1925 // Put in a guard element at the top
1926 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1927 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1930 krsort($SESSION->dst_offsets);
1936 * Calculates the required DST change and returns a Timestamp Array
1940 * @param mixed $year Int or String Year to focus on
1941 * @param object $timezone Instatiated Timezone object
1942 * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
1944 function dst_changes_for_year($year, $timezone) {
1946 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1950 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1951 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1953 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1954 list($std_hour, $std_min) = explode(':', $timezone->std_time);
1956 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1957 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
1959 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1960 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1961 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1963 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1964 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
1966 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1970 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
1973 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
1976 function dst_offset_on($time, $strtimezone = NULL) {
1979 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
1983 reset($SESSION->dst_offsets);
1984 while(list($from, $offset) = each($SESSION->dst_offsets)) {
1985 if($from <= $time) {
1990 // This is the normal return path
1991 if($offset !== NULL) {
1995 // Reaching this point means we haven't calculated far enough, do it now:
1996 // Calculate extra DST changes if needed and recurse. The recursion always
1997 // moves toward the stopping condition, so will always end.
2000 // We need a year smaller than $SESSION->dst_range[0]
2001 if($SESSION->dst_range[0] == 1971) {
2004 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2005 return dst_offset_on($time, $strtimezone);
2008 // We need a year larger than $SESSION->dst_range[1]
2009 if($SESSION->dst_range[1] == 2035) {
2012 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2013 return dst_offset_on($time, $strtimezone);
2020 * @todo Document what this function does
2021 * @param int $startday
2022 * @param int $weekday
2027 function find_day_in_month($startday, $weekday, $month, $year) {
2029 $daysinmonth = days_in_month($month, $year);
2031 if($weekday == -1) {
2032 // Don't care about weekday, so return:
2033 // abs($startday) if $startday != -1
2034 // $daysinmonth otherwise
2035 return ($startday == -1) ? $daysinmonth : abs($startday);
2038 // From now on we 're looking for a specific weekday
2040 // Give "end of month" its actual value, since we know it
2041 if($startday == -1) {
2042 $startday = -1 * $daysinmonth;
2045 // Starting from day $startday, the sign is the direction
2049 $startday = abs($startday);
2050 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2052 // This is the last such weekday of the month
2053 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2054 if($lastinmonth > $daysinmonth) {
2058 // Find the first such weekday <= $startday
2059 while($lastinmonth > $startday) {
2063 return $lastinmonth;
2068 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
2070 $diff = $weekday - $indexweekday;
2075 // This is the first such weekday of the month equal to or after $startday
2076 $firstfromindex = $startday + $diff;
2078 return $firstfromindex;
2084 * Calculate the number of days in a given month
2086 * @param int $month The month whose day count is sought
2087 * @param int $year The year of the month whose day count is sought
2090 function days_in_month($month, $year) {
2091 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
2095 * Calculate the position in the week of a specific calendar day
2097 * @param int $day The day of the date whose position in the week is sought
2098 * @param int $month The month of the date whose position in the week is sought
2099 * @param int $year The year of the date whose position in the week is sought
2102 function dayofweek($day, $month, $year) {
2103 // I wonder if this is any different from
2104 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2105 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
2108 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2111 * Returns full login url.
2114 * @param bool $loginguest add login guest param, return false
2115 * @return string login url
2117 function get_login_url($loginguest=false) {
2120 if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
2121 $loginguest = $loginguest ? '?loginguest=true' : '';
2122 $url = "$CFG->wwwroot/login/index.php$loginguest";
2125 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2126 $url = "$wwwroot/login/index.php";
2133 * This function checks that the current user is logged in and has the
2134 * required privileges
2136 * This function checks that the current user is logged in, and optionally
2137 * whether they are allowed to be in a particular course and view a particular
2139 * If they are not logged in, then it redirects them to the site login unless
2140 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2141 * case they are automatically logged in as guests.
2142 * If $courseid is given and the user is not enrolled in that course then the
2143 * user is redirected to the course enrolment page.
2144 * If $cm is given and the course module is hidden and the user is not a teacher
2145 * in the course then the user is redirected to the course home page.
2147 * When $cm parameter specified, this function sets page layout to 'module'.
2148 * You need to change it manually later if some other layout needed.
2150 * @param mixed $courseorid id of the course or course object
2151 * @param bool $autologinguest default true
2152 * @param object $cm course module object
2153 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2154 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2155 * in order to keep redirects working properly. MDL-14495
2156 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2157 * @return mixed Void, exit, and die depending on path
2159 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2160 global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2162 // setup global $COURSE, themes, language and locale
2163 if (!empty($courseorid)) {
2164 if (is_object($courseorid)) {
2165 $course = $courseorid;
2166 } else if ($courseorid == SITEID) {
2167 $course = clone($SITE);
2169 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2172 if ($cm->course != $course->id) {
2173 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2175 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2176 $PAGE->set_pagelayout('incourse');
2178 $PAGE->set_course($course); // set's up global $COURSE
2181 // do not touch global $COURSE via $PAGE->set_course(),
2182 // the reasons is we need to be able to call require_login() at any time!!
2185 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2189 // If the user is not even logged in yet then make sure they are
2190 if (!isloggedin()) {
2191 //NOTE: $USER->site check was obsoleted by session test cookie,
2192 // $USER->confirmed test is in login/index.php
2193 if ($preventredirect) {
2194 throw new require_login_exception('You are not logged in');
2197 if ($setwantsurltome) {
2198 $SESSION->wantsurl = $FULLME;
2200 if (!empty($_SERVER['HTTP_REFERER'])) {
2201 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2203 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2204 if ($course->id == SITEID) {
2207 $loginguest = false;
2210 $loginguest = false;
2212 redirect(get_login_url($loginguest));
2213 exit; // never reached
2216 // loginas as redirection if needed
2217 if ($course->id != SITEID and session_is_loggedinas()) {
2218 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2219 if ($USER->loginascontext->instanceid != $course->id) {
2220 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2225 // check whether the user should be changing password (but only if it is REALLY them)
2226 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2227 $userauth = get_auth_plugin($USER->auth);
2228 if ($userauth->can_change_password() and !$preventredirect) {
2229 $SESSION->wantsurl = $FULLME;
2230 if ($changeurl = $userauth->change_password_url()) {
2231 //use plugin custom url
2232 redirect($changeurl);
2234 //use moodle internal method
2235 if (empty($CFG->loginhttps)) {
2236 redirect($CFG->wwwroot .'/login/change_password.php');
2238 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2239 redirect($wwwroot .'/login/change_password.php');
2243 print_error('nopasswordchangeforced', 'auth');
2247 // Check that the user account is properly set up
2248 if (user_not_fully_set_up($USER)) {
2249 if ($preventredirect) {
2250 throw new require_login_exception('User not fully set-up');
2252 $SESSION->wantsurl = $FULLME;
2253 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2256 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2259 // Do not bother admins with any formalities, no last access updates either
2260 if (is_siteadmin()) {
2264 // Check that the user has agreed to a site policy if there is one
2265 if (!empty($CFG->sitepolicy)) {
2266 if ($preventredirect) {
2267 throw new require_login_exception('Policy not agreed');
2269 if (!$USER->policyagreed) {
2270 $SESSION->wantsurl = $FULLME;
2271 redirect($CFG->wwwroot .'/user/policy.php');
2275 // Fetch the system context, the course context, and prefetch its child contexts
2276 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2277 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2279 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2284 // If the site is currently under maintenance, then print a message
2285 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2286 if ($preventredirect) {
2287 throw new require_login_exception('Maintenance in progress');
2290 print_maintenance_message();
2293 // make sure the course itself is not hidden
2294 if ($course->id == SITEID) {
2295 // frontpage can not be hidden
2297 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2298 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2300 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2301 // originally there was also test of parent category visibility,
2302 // BUT is was very slow in complex queries involving "my courses"
2303 // now it is also possible to simply hide all courses user is not enrolled in :-)
2304 if ($preventredirect) {
2305 throw new require_login_exception('Course is hidden');
2307 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2312 // is the user enrolled?
2313 if ($course->id == SITEID) {
2314 // everybody is enrolled on the frontpage
2317 if (session_is_loggedinas()) {
2318 // Make sure the REAL person can access this course first
2319 $realuser = session_get_realuser();
2320 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2321 if ($preventredirect) {
2322 throw new require_login_exception('Invalid course login-as access');
2324 echo $OUTPUT->header();
2325 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2329 // very simple enrolment caching - changes in course setting are not reflected immediately
2330 if (!isset($USER->enrol)) {
2331 $USER->enrol = array();
2332 $USER->enrol['enrolled'] = array();
2333 $USER->enrol['tempguest'] = array();
2338 if (is_viewing($coursecontext, $USER)) {
2339 // ok, no need to mess with enrol
2343 if (isset($USER->enrol['enrolled'][$course->id])) {
2344 if ($USER->enrol['enrolled'][$course->id] == 0) {
2346 } else if ($USER->enrol['enrolled'][$course->id] > time()) {
2350 unset($USER->enrol['enrolled'][$course->id]);
2353 if (isset($USER->enrol['tempguest'][$course->id])) {
2354 if ($USER->enrol['tempguest'][$course->id] == 0) {
2356 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2360 unset($USER->enrol['tempguest'][$course->id]);
2361 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2367 } else if (is_enrolled($coursecontext, $USER, '', true)) {
2368 // active participants may always access
2369 // TODO: refactor this into some new function
2371 $sql = "SELECT MAX(ue.timeend)
2372 FROM {user_enrolments} ue
2373 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2374 JOIN {user} u ON u.id = ue.userid
2375 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0
2376 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
2377 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE,
2378 'userid'=>$USER->id, 'courseid'=>$coursecontext->instanceid, 'now1'=>$now, 'now2'=>$now);
2379 $until = $DB->get_field_sql($sql, $params);
2380 if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) {
2381 $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD;
2384 $USER->enrol['enrolled'][$course->id] = $until;
2387 // remove traces of previous temp guest access
2388 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2391 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2392 $enrols = enrol_get_plugins(true);
2393 // first ask all enabled enrol instances in course if they want to auto enrol user
2394 foreach($instances as $instance) {
2395 if (!isset($enrols[$instance->enrol])) {
2398 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2399 if ($until !== false) {
2400 $USER->enrol['enrolled'][$course->id] = $until;
2401 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2406 // if not enrolled yet try to gain temporary guest access
2408 foreach($instances as $instance) {
2409 if (!isset($enrols[$instance->enrol])) {
2412 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2413 if ($until !== false) {
2414 $USER->enrol['tempguest'][$course->id] = $until;
2424 if ($preventredirect) {
2425 throw new require_login_exception('Not enrolled');
2427 $SESSION->wantsurl = $FULLME;
2428 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2433 if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2434 if ($preventredirect) {
2435 throw new require_login_exception('Activity is hidden');
2437 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2440 // groupmembersonly access control
2441 if (!empty($CFG->enablegroupmembersonly) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2442 if (isguestuser() or !groups_has_membership($cm)) {
2443 if ($preventredirect) {
2444 throw new require_login_exception('Not member of a group');
2446 print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
2450 // Conditional activity access control
2451 if (!empty($CFG->enableavailability) and $cm) {
2452 // TODO: this is going to work with login-as-user, sorry!
2453 // We cache conditional access in session
2454 if (!isset($SESSION->conditionaccessok)) {
2455 $SESSION->conditionaccessok = array();
2457 // If you have been allowed into the module once then you are allowed
2458 // in for rest of session, no need to do conditional checks
2459 if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
2460 // Get condition info (does a query for the availability table)
2461 require_once($CFG->libdir.'/conditionlib.php');
2462 $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
2463 // Check condition for user (this will do a query if the availability
2464 // information depends on grade or completion information)
2465 if ($ci->is_available($junk) || has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2466 $SESSION->conditionaccessok[$cm->id] = true;
2468 print_error('activityiscurrentlyhidden');
2473 // Finally access granted, update lastaccess times
2474 user_accesstime_log($course->id);
2479 * This function just makes sure a user is logged out.
2483 function require_logout() {
2487 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2489 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2490 foreach($authsequence as $authname) {
2491 $authplugin = get_auth_plugin($authname);
2492 $authplugin->prelogout_hook();
2496 session_get_instance()->terminate_current();
2500 * Weaker version of require_login()
2502 * This is a weaker version of {@link require_login()} which only requires login
2503 * when called from within a course rather than the site page, unless
2504 * the forcelogin option is turned on.
2505 * @see require_login()
2508 * @param mixed $courseorid The course object or id in question
2509 * @param bool $autologinguest Allow autologin guests if that is wanted
2510 * @param object $cm Course activity module if known
2511 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2512 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2513 * in order to keep redirects working properly. MDL-14495
2514 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2517 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2518 global $CFG, $PAGE, $SITE;
2519 if (!empty($CFG->forcelogin)) {
2520 // login required for both SITE and courses
2521 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2523 } else if (!empty($cm) and !$cm->visible) {
2524 // always login for hidden activities
2525 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2527 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2528 or (!is_object($courseorid) and $courseorid == SITEID)) {
2529 //login for SITE not required
2530 if ($cm and empty($cm->visible)) {
2531 // hidden activities are not accessible without login
2532 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2533 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2534 // not-logged-in users do not have any group membership
2535 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2537 // We still need to instatiate PAGE vars properly so that things
2538 // that rely on it like navigation function correctly.
2539 if (!empty($courseorid)) {
2540 if (is_object($courseorid)) {
2541 $course = $courseorid;
2543 $course = clone($SITE);
2546 if ($cm->course != $course->id) {
2547 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2549 $PAGE->set_cm($cm, $course);
2550 $PAGE->set_pagelayout('incourse');
2552 $PAGE->set_course($course);
2555 // If $PAGE->course, and hence $PAGE->context, have not already been set
2556 // up properly, set them up now.
2557 $PAGE->set_course($PAGE->course);
2559 //TODO: verify conditional activities here
2560 user_accesstime_log(SITEID);
2565 // course login always required
2566 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2571 * Require key login. Function terminates with error if key not found or incorrect.
2577 * @uses NO_MOODLE_COOKIES
2578 * @uses PARAM_ALPHANUM
2579 * @param string $script unique script identifier
2580 * @param int $instance optional instance id
2581 * @return int Instance ID
2583 function require_user_key_login($script, $instance=null) {
2584 global $USER, $SESSION, $CFG, $DB;
2586 if (!NO_MOODLE_COOKIES) {
2587 print_error('sessioncookiesdisable');
2591 @session_write_close();
2593 $keyvalue = required_param('key', PARAM_ALPHANUM);
2595 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2596 print_error('invalidkey');
2599 if (!empty($key->validuntil) and $key->validuntil < time()) {
2600 print_error('expiredkey');
2603 if ($key->iprestriction) {
2604 $remoteaddr = getremoteaddr(null);
2605 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2606 print_error('ipmismatch');
2610 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2611 print_error('invaliduserid');
2614 /// emulate normal session
2615 session_set_user($user);
2617 /// note we are not using normal login
2618 if (!defined('USER_KEY_LOGIN')) {
2619 define('USER_KEY_LOGIN', true);
2622 /// return isntance id - it might be empty
2623 return $key->instance;
2627 * Creates a new private user access key.
2630 * @param string $script unique target identifier
2631 * @param int $userid
2632 * @param int $instance optional instance id
2633 * @param string $iprestriction optional ip restricted access
2634 * @param timestamp $validuntil key valid only until given data
2635 * @return string access key value
2637 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2640 $key = new object();
2641 $key->script = $script;
2642 $key->userid = $userid;
2643 $key->instance = $instance;
2644 $key->iprestriction = $iprestriction;
2645 $key->validuntil = $validuntil;
2646 $key->timecreated = time();
2648 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
2649 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
2651 $key->value = md5($userid.'_'.time().random_string(40));
2653 $DB->insert_record('user_private_key', $key);
2658 * Delete the user's new private user access keys for a particular script.
2661 * @param string $script unique target identifier
2662 * @param int $userid
2665 function delete_user_key($script,$userid) {
2667 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
2671 * Gets a private user access key (and creates one if one doesn't exist).
2674 * @param string $script unique target identifier
2675 * @param int $userid
2676 * @param int $instance optional instance id
2677 * @param string $iprestriction optional ip restricted access
2678 * @param timestamp $validuntil key valid only until given data
2679 * @return string access key value
2681 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2684 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
2685 'instance'=>$instance, 'iprestriction'=>$iprestriction,
2686 'validuntil'=>$validuntil))) {
2689 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
2695 * Modify the user table by setting the currently logged in user's
2696 * last login to now.
2700 * @return bool Always returns true
2702 function update_user_login_times() {
2705 $user = new object();
2706 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2707 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2709 $user->id = $USER->id;
2711 $DB->update_record('user', $user);
2716 * Determines if a user has completed setting up their account.
2718 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
2721 function user_not_fully_set_up($user) {
2722 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
2726 * Check whether the user has exceeded the bounce threshold
2730 * @param user $user A {@link $USER} object
2731 * @return bool true=>User has exceeded bounce threshold
2733 function over_bounce_threshold($user) {
2736 if (empty($CFG->handlebounces)) {
2740 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2744 // set sensible defaults
2745 if (empty($CFG->minbounces)) {
2746 $CFG->minbounces = 10;
2748 if (empty($CFG->bounceratio)) {
2749 $CFG->bounceratio = .20;
2753 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2754 $bouncecount = $bounce->value;
2756 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2757 $sendcount = $send->value;
2759 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2763 * Used to increment or reset email sent count
2766 * @param user $user object containing an id
2767 * @param bool $reset will reset the count to 0
2770 function set_send_count($user,$reset=false) {
2773 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2777 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2778 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2779 $DB->update_record('user_preferences', $pref);
2781 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2783 $pref = new object();
2784 $pref->name = 'email_send_count';
2786 $pref->userid = $user->id;
2787 $DB->insert_record('user_preferences', $pref, false);
2792 * Increment or reset user's email bounce count
2795 * @param user $user object containing an id
2796 * @param bool $reset will reset the count to 0
2798 function set_bounce_count($user,$reset=false) {
2801 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2802 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2803 $DB->update_record('user_preferences', $pref);
2805 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2807 $pref = new object();
2808 $pref->name = 'email_bounce_count';
2810 $pref->userid = $user->id;
2811 $DB->insert_record('user_preferences', $pref, false);
2816 * Keeps track of login attempts
2820 function update_login_count() {
2825 if (empty($SESSION->logincount)) {
2826 $SESSION->logincount = 1;
2828 $SESSION->logincount++;
2831 if ($SESSION->logincount > $max_logins) {
2832 unset($SESSION->wantsurl);
2833 print_error('errortoomanylogins');
2838 * Resets login attempts
2842 function reset_login_count() {
2845 $SESSION->logincount = 0;
2849 * Returns reference to full info about modules in course (including visibility).
2850 * Cached and as fast as possible (0 or 1 db query).
2855 * @uses CONTEXT_MODULE
2856 * @uses MAX_MODINFO_CACHE_SIZE
2857 * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
2858 * @param int $userid Defaults to current user id
2859 * @return mixed courseinfo object or nothing if resetting
2861 function &get_fast_modinfo(&$course, $userid=0) {
2862 global $CFG, $USER, $DB;
2863 require_once($CFG->dirroot.'/course/lib.php');
2865 if (!empty($CFG->enableavailability)) {
2866 require_once($CFG->libdir.'/conditionlib.php');
2869 static $cache = array();
2871 if ($course === 'reset') {
2874 return $nothing; // we must return some reference
2877 if (empty($userid)) {
2878 $userid = $USER->id;
2881 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
2882 return $cache[$course->id];
2885 if (empty($course->modinfo)) {
2886 // no modinfo yet - load it
2887 rebuild_course_cache($course->id);
2888 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2891 $modinfo = new object();
2892 $modinfo->courseid = $course->id;
2893 $modinfo->userid = $userid;
2894 $modinfo->sections = array();
2895 $modinfo->cms = array();
2896 $modinfo->instances = array();
2897 $modinfo->groups = null; // loaded only when really needed - the only one db query
2899 $info = unserialize($course->modinfo);
2900 if (!is_array($info)) {
2901 // hmm, something is wrong - lets try to fix it
2902 rebuild_course_cache($course->id);
2903 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2904 $info = unserialize($course->modinfo);
2905 if (!is_array($info)) {
2911 // detect if upgrade required
2912 $first = reset($info);
2913 if (!isset($first->id)) {
2914 rebuild_course_cache($course->id);
2915 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2916 $info = unserialize($course->modinfo);
2917 if (!is_array($info)) {
2923 $modlurals = array();
2925 // If we haven't already preloaded contexts for the course, do it now
2926 preload_course_contexts($course->id);
2928 foreach ($info as $mod) {
2929 if (empty($mod->name)) {
2930 // something is wrong here
2933 // reconstruct minimalistic $cm
2936 $cm->instance = $mod->id;
2937 $cm->course = $course->id;
2938 $cm->modname = $mod->mod;
2939 $cm->idnumber = $mod->idnumber;
2940 $cm->name = $mod->name;
2941 $cm->visible = $mod->visible;
2942 $cm->sectionnum = $mod->section;
2943 $cm->groupmode = $mod->groupmode;
2944 $cm->groupingid = $mod->groupingid;
2945 $cm->groupmembersonly = $mod->groupmembersonly;
2946 $cm->indent = $mod->indent;
2947 $cm->completion = $mod->completion;
2948 $cm->extra = isset($mod->extra) ? $mod->extra : '';
2949 $cm->icon = isset($mod->icon) ? $mod->icon : '';
2950 $cm->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
2951 $cm->uservisible = true;
2952 if(!empty($CFG->enableavailability)) {
2953 // We must have completion information from modinfo. If it's not
2954 // there, cache needs rebuilding
2955 if(!isset($mod->availablefrom)) {
2956 debugging('enableavailability option was changed; rebuilding '.
2957 'cache for course '.$course->id);
2958 rebuild_course_cache($course->id,true);
2959 // Re-enter this routine to do it all properly
2960 return get_fast_modinfo($course,$userid);
2962 $cm->availablefrom = $mod->availablefrom;
2963 $cm->availableuntil = $mod->availableuntil;
2964 $cm->showavailability = $mod->showavailability;
2965 $cm->conditionscompletion = $mod->conditionscompletion;
2966 $cm->conditionsgrade = $mod->conditionsgrade;
2969 // preload long names plurals and also check module is installed properly
2970 if (!isset($modlurals[$cm->modname])) {
2971 if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
2974 $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
2976 $cm->modplural = $modlurals[$cm->modname];
2977 $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id);
2979 if(!empty($CFG->enableavailability)) {
2980 // Unfortunately the next call really wants to call
2981 // get_fast_modinfo, but that would be recursive, so we fake up a
2982 // modinfo for it already
2983 if(empty($minimalmodinfo)) {
2984 $minimalmodinfo=new stdClass();
2985 $minimalmodinfo->cms=array();
2986 foreach($info as $mod) {
2987 if (empty($mod->name)) {
2988 // something is wrong here
2991 $minimalcm = new stdClass();
2992 $minimalcm->id = $mod->cm;
2993 $minimalcm->name = $mod->name;
2994 $minimalmodinfo->cms[$minimalcm->id]=$minimalcm;
2998 // Get availability information
2999 $ci = new condition_info($cm);
3000 $cm->available=$ci->is_available($cm->availableinfo, true, $userid, $minimalmodinfo);
3002 $cm->available=true;
3004 if ((!$cm->visible or !$cm->available) and !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
3005 $cm->uservisible = false;
3007 } else if (!empty($CFG->enablegroupmembersonly) and !empty($cm->groupmembersonly)
3008 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
3009 if (is_null($modinfo->groups)) {
3010 $modinfo->groups = groups_get_user_groups($course->id, $userid);
3012 if (empty($modinfo->groups[$cm->groupingid])) {
3013 $cm->uservisible = false;
3017 if (!isset($modinfo->instances[$cm->modname])) {
3018 $modinfo->instances[$cm->modname] = array();
3020 $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
3021 $modinfo->cms[$cm->id] =& $cm;
3023 // reconstruct sections
3024 if (!isset($modinfo->sections[$cm->sectionnum])) {
3025 $modinfo->sections[$cm->sectionnum] = array();
3027 $modinfo->sections[$cm->sectionnum][] = $cm->id;
3032 unset($cache[$course->id]); // prevent potential reference problems when switching users
3033 $cache[$course->id] = $modinfo;
3035 // Ensure cache does not use too much RAM
3036 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
3039 unset($cache[$key]);
3042 return $cache[$course->id];
3046 * Determines if the currently logged in user is in editing mode.
3047 * Note: originally this function had $userid parameter - it was not usable anyway
3049 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3050 * @todo Deprecated function remove when ready
3053 * @uses DEBUG_DEVELOPER
3056 function isediting() {
3058 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3059 return $PAGE->user_is_editing();
3063 * Determines if the logged in user is currently moving an activity
3066 * @param int $courseid The id of the course being tested
3069 function ismoving($courseid) {
3072 if (!empty($USER->activitycopy)) {
3073 return ($USER->activitycopycourse == $courseid);
3079 * Returns a persons full name
3081 * Given an object containing firstname and lastname
3082 * values, this function returns a string with the
3083 * full name of the person.
3084 * The result may depend on system settings
3085 * or language. 'override' will force both names
3086 * to be used even if system settings specify one.
3090 * @param object $user A {@link $USER} object to get full name of
3091 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3094 function fullname($user, $override=false) {
3095 global $CFG, $SESSION;
3097 if (!isset($user->firstname) and !isset($user->lastname)) {
3102 if (!empty($CFG->forcefirstname)) {
3103 $user->firstname = $CFG->forcefirstname;
3105 if (!empty($CFG->forcelastname)) {
3106 $user->lastname = $CFG->forcelastname;
3110 if (!empty($SESSION->fullnamedisplay)) {
3111 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3114 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3115 return $user->firstname .' '. $user->lastname;
3117 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3118 return $user->lastname .' '. $user->firstname;
3120 } else if ($CFG->fullnamedisplay == 'firstname') {
3122 return get_string('fullnamedisplay', '', $user);
3124 return $user->firstname;
3128 return get_string('fullnamedisplay', '', $user);
3132 * Returns whether a given authentication plugin exists.
3135 * @param string $auth Form of authentication to check for. Defaults to the
3136 * global setting in {@link $CFG}.
3137 * @return boolean Whether the plugin is available.
3139 function exists_auth_plugin($auth) {
3142 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3143 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3149 * Checks if a given plugin is in the list of enabled authentication plugins.
3151 * @param string $auth Authentication plugin.
3152 * @return boolean Whether the plugin is enabled.
3154 function is_enabled_auth($auth) {
3159 $enabled = get_enabled_auth_plugins();
3161 return in_array($auth, $enabled);
3165 * Returns an authentication plugin instance.
3168 * @param string $auth name of authentication plugin
3169 * @return auth_plugin_base An instance of the required authentication plugin.
3171 function get_auth_plugin($auth) {
3174 // check the plugin exists first
3175 if (! exists_auth_plugin($auth)) {
3176 print_error('authpluginnotfound', 'debug', '', $auth);
3179 // return auth plugin instance
3180 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3181 $class = "auth_plugin_$auth";
3186 * Returns array of active auth plugins.
3188 * @param bool $fix fix $CFG->auth if needed
3191 function get_enabled_auth_plugins($fix=false) {
3194 $default = array('manual', 'nologin');
3196 if (empty($CFG->auth)) {
3199 $auths = explode(',', $CFG->auth);
3203 $auths = array_unique($auths);
3204 foreach($auths as $k=>$authname) {
3205 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3209 $newconfig = implode(',', $auths);
3210 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3211 set_config('auth', $newconfig);
3215 return (array_merge($default, $auths));
3219 * Returns true if an internal authentication method is being used.
3220 * if method not specified then, global default is assumed
3222 * @param string $auth Form of authentication required
3225 function is_internal_auth($auth) {
3226 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3227 return $authplugin->is_internal();
3231 * Returns true if the user is a 'restored' one
3233 * Used in the login process to inform the user
3234 * and allow him/her to reset the password
3238 * @param string $username username to be checked
3241 function is_restored_user($username) {
3244 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3248 * Returns an array of user fields
3250 * @return array User field/column names
3252 function get_user_fieldnames() {
3255 $fieldarray = $DB->get_columns('user');
3256 unset($fieldarray['id']);
3257 $fieldarray = array_keys($fieldarray);
3263 * Creates a bare-bones user record
3265 * @todo Outline auth types and provide code example
3269 * @param string $username New user's username to add to record
3270 * @param string $password New user's password to add to record
3271 * @param string $auth Form of authentication required
3272 * @return object A {@link $USER} object
3274 function create_user_record($username, $password, $auth='manual') {
3277 //just in case check text case
3278 $username = trim(moodle_strtolower($username));
3280 $authplugin = get_auth_plugin($auth);
3282 $newuser = new object();
3284 if ($newinfo = $authplugin->get_userinfo($username)) {
3285 $newinfo = truncate_userinfo($newinfo);
3286 foreach ($newinfo as $key => $value){
3287 $newuser->$key = $value;
3291 if (!empty($newuser->email)) {
3292 if (email_is_not_allowed($newuser->email)) {
3293 unset($newuser->email);
3297 if (!isset($newuser->city)) {
3298 $newuser->city = '';
3301 $newuser->auth = $auth;
3302 $newuser->username = $username;
3305 // user CFG lang for user if $newuser->lang is empty
3306 // or $user->lang is not an installed language
3307 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3308 $newuser->lang = $CFG->lang;
3310 $newuser->confirmed = 1;
3311 $newuser->lastip = getremoteaddr();
3312 $newuser->timemodified = time();
3313 $newuser->mnethostid = $CFG->mnet_localhost_id;
3315 $DB->insert_record('user', $newuser);
3316 $user = get_complete_user_data('username', $newuser->username);
3317 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3318 set_user_preference('auth_forcepasswordchange', 1, $user->id);
3320 update_internal_user_password($user, $password);
3325 * Will update a local user record from an external source
3328 * @param string $username New user's username to add to record
3329 * @param string $authplugin Unused
3330 * @return user A {@link $USER} object
3332 function update_user_record($username, $authplugin) {
3335 $username = trim(moodle_strtolower($username)); /// just in case check text case
3337 $oldinfo = $DB->get_record('user', array('username'=>$username), 'username, auth');
3338 $userauth = get_auth_plugin($oldinfo->auth);
3340 if ($newinfo = $userauth->get_userinfo($username)) {
3341 $newinfo = truncate_userinfo($newinfo);
3342 foreach ($newinfo as $key => $value){
3343 if ($key === 'username') {
3344 // 'username' is not a mapped updateable/lockable field, so skip it.
3347 $confval = $userauth->config->{'field_updatelocal_' . $key};
3348 $lockval = $userauth->config->{'field_lock_' . $key};
3349 if (empty($confval) || empty($lockval)) {
3352 if ($confval === 'onlogin') {
3353 // MDL-4207 Don't overwrite modified user profile values with
3354 // empty LDAP values when 'unlocked if empty' is set. The purpose
3355 // of the setting 'unlocked if empty' is to allow the user to fill
3356 // in a value for the selected field _if LDAP is giving
3357 // nothing_ for this field. Thus it makes sense to let this value
3358 // stand in until LDAP is giving a value for this field.
3359 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3360 $DB->set_field('user', $key, $value, array('username'=>$username));
3366 return get_complete_user_data('username', $username);
3370 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3371 * which may have large fields
3373 * @todo Add vartype handling to ensure $info is an array
3375 * @param array $info Array of user properties to truncate if needed
3376 * @return array The now truncated information that was passed in
3378 function truncate_userinfo($info) {
3379 // define the limits
3389 'institution' => 40,
3397 // apply where needed
3398 foreach (array_keys($info) as $key) {
3399 if (!empty($limit[$key])) {
3400 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
3408 * Marks user deleted in internal user database and notifies the auth plugin.
3409 * Also unenrols user from all roles and does other cleanup.
3411 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3413 * @param object $user User object before delete
3414 * @return boolean always true
3416 function delete_user($user) {
3418 require_once($CFG->libdir.'/grouplib.php');
3419 require_once($CFG->libdir.'/gradelib.php');
3420 require_once($CFG->dirroot.'/message/lib.php');
3422 // delete all grades - backup is kept in grade_grades_history table
3423 grade_user_delete($user->id);
3425 //move unread messages from this user to read
3426 message_move_userfrom_unread2read($user->id);
3428 // remove from all cohorts
3429 $DB->delete_records('cohort_members', array('userid'=>$user->id));
3431 // remove from all groups
3432 $DB->delete_records('groups_members', array('userid'=>$user->id));
3434 // brute force unenrol from all courses
3435 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
3437 // purge user preferences
3438 $DB->delete_records('user_preferences', array('userid'=>$user->id));
3440 // purge user extra profile info
3441 $DB->delete_records('user_info_data', array('userid'=>$user->id));
3443 // last course access not necessary either
3444 $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
3446 // final accesslib cleanup - removes all role assignments in user context and context itself
3447 delete_context(CONTEXT_USER, $user->id);
3449 require_once($CFG->dirroot.'/tag/lib.php');
3450 tag_set('user', $user->id, array());
3452 // workaround for bulk deletes of users with the same email address
3453 $delname = "$user->email.".time();
3454 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3458 // mark internal user record as "deleted"
3459 $updateuser = new object();
3460 $updateuser->id = $user->id;
3461 $updateuser->deleted = 1;
3462 $updateuser->username = $delname; // Remember it just in case
3463 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
3464 $updateuser->idnumber = ''; // Clear this field to free it up
3465 $updateuser->timemodified = time();
3467 $DB->update_record('user', $updateuser);
3469 // notify auth plugin - do not block the delete even when plugin fails
3470 $authplugin = get_auth_plugin($user->auth);
3471 $authplugin->user_delete($user);
3473 // any plugin that needs to cleanup should register this event
3474 events_trigger('user_deleted', $user);
3480 * Retrieve the guest user object
3484 * @return user A {@link $USER} object
3486 function guest_user() {
3489 if ($newuser = $DB->get_record('user', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
3490 $newuser->confirmed = 1;
3491 $newuser->lang = $CFG->lang;
3492 $newuser->lastip = getremoteaddr();
3499 * Authenticates a user against the chosen authentication mechanism
3501 * Given a username and password, this function looks them
3502 * up using the currently selected authentication mechanism,
3503 * and if the authentication is successful, it returns a
3504 * valid $user object from the 'user' table.
3506 * Uses auth_ functions from the currently active auth module
3508 * After authenticate_user_login() returns success, you will need to
3509 * log that the user has logged in, and call complete_user_login() to set
3514 * @param string $username User's username
3515 * @param string $password User's password
3516 * @return user|flase A {@link $USER} object or false if error
3518 function authenticate_user_login($username, $password) {
3519 global $CFG, $DB, $OUTPUT;
3521 $authsenabled = get_enabled_auth_plugins();
3523 if ($user = get_complete_user_data('username', $username)) {
3524 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
3525 if ($auth=='nologin' or !is_enabled_auth($auth)) {
3526 add_to_log(0, 'login', 'error', 'index.php', $username);
3527 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3530 $auths = array($auth);
3533 // check if there's a deleted record (cheaply)
3534 if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
3535 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3539 $auths = $authsenabled;
3540 $user = new object();
3541 $user->id = 0; // User does not exist
3544 foreach ($auths as $auth) {
3545 $authplugin = get_auth_plugin($auth);
3547 // on auth fail fall through to the next plugin
3548 if (!$authplugin->user_login($username, $password)) {
3552 // successful authentication
3553 if ($user->id) { // User already exists in database
3554 if (empty($user->auth)) { // For some reason auth isn't set yet
3555 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
3556 $user->auth = $auth;
3558 if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3559 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
3560 $user->firstaccess = $user->timemodified;
3563 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3565 if (!$authplugin->is_internal()) { // update user record from external DB
3566 $user = update_user_record($username, get_auth_plugin($user->auth));
3569 // if user not found, create him
3570 $user = create_user_record($username, $password, $auth);
3573 $authplugin->sync_roles($user);
3575 foreach ($authsenabled as $hau) {
3576 $hauth = get_auth_plugin($hau);
3577 $hauth->user_authenticated_hook($user, $username, $password);
3580 if ($user->id===0) {
3586 // failed if all the plugins have failed
3587 add_to_log(0, 'login', 'error', 'index.php', $username);
3588 if (debugging('', DEBUG_ALL)) {
3589 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3595 * Call to complete the user login process after authenticate_user_login()
3596 * has succeeded. It will setup the $USER variable and other required bits
3600 * - It will NOT log anything -- up to the caller to decide what to log.
3605 * @param object $user
3606 * @param bool $setcookie
3607 * @return object A {@link $USER} object - BC only, do not use
3609 function complete_user_login($user, $setcookie=true) {
3610 global $CFG, $USER, $SESSION;
3612 // regenerate session id and delete old session,
3613 // this helps prevent session fixation attacks from the same domain
3614 session_regenerate_id(true);
3616 // check enrolments, load caps and setup $USER object
3617 session_set_user($user);
3619 update_user_login_times();
3620 set_login_session_preferences();
3623 if (empty($CFG->nolastloggedin)) {
3624 set_moodle_cookie($USER->username);
3626 // do not store last logged in user in cookie
3627 // auth plugins can temporarily override this from loginpage_hook()
3628 // do not save $CFG->nolastloggedin in database!
3629 set_moodle_cookie('nobody');
3633 /// Select password change url
3634 $userauth = get_auth_plugin($USER->auth);
3636 /// check whether the user should be changing password
3637 if (get_user_preferences('auth_forcepasswordchange', false)){
3638 if ($userauth->can_change_password()) {
3639 if ($changeurl = $userauth->change_password_url()) {
3640 redirect($changeurl);
3642 redirect($CFG->httpswwwroot.'/login/change_password.php');
3645 print_error('nopasswordchangeforced', 'auth');
3652 * Compare password against hash stored in internal user table.
3653 * If necessary it also updates the stored hash to new format.
3656 * @param object $user
3657 * @param string $password plain text password
3658 * @return bool is password valid?
3660 function validate_internal_user_password(&$user, $password) {
3663 if (!isset($CFG->passwordsaltmain)) {
3664 $CFG->passwordsaltmain = '';
3669 // Commented out by Martin as this surely is not necessary now, right? MDL-22922
3670 // get password original encoding in case it was not updated to unicode yet
3671 //$textlib = textlib_get_instance();
3672 //$convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset', 'langconfig'));
3673 //if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
3674 // or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
3676 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)) {
3679 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
3680 $alt = 'passwordsaltalt'.$i;
3681 if (!empty($CFG->$alt)) {
3682 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
3691 // force update of password hash using latest main password salt and encoding if needed
3692 update_internal_user_password($user, $password);
3699 * Calculate hashed value from password using current hash mechanism.
3702 * @param string $password
3703 * @return string password hash
3705 function hash_internal_user_password($password) {
3708 if (isset($CFG->passwordsaltmain)) {
3709 return md5($password.$CFG->passwordsaltmain);
3711 return md5($password);