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;
1070 * Invalidates browser caches and cached data in temp
1073 function purge_all_caches() {
1076 reset_text_filters_cache();
1077 js_reset_all_caches();
1078 theme_reset_all_caches();
1079 get_string_manager()->reset_caches();
1081 // purge all other caches: rss, simplepie, etc.
1082 remove_dir($CFG->dataroot.'/cache', true);
1084 // some more diagnostics in case site is misconfigured
1085 if (!check_dir_exists($CFG->dataroot.'/cache', true, true)) {
1086 debugging('Can not create cache directory, please check permissions in dataroot.');
1087 } else if (!is_writeable($CFG->dataroot.'/cache')) {
1088 debugging('Cache directory is not writeable, please verify permissions in dataroot.');
1095 * Get volatile flags
1097 * @param string $type
1098 * @param int $changedsince default null
1099 * @return records array
1101 function get_cache_flags($type, $changedsince=NULL) {
1104 $params = array('type'=>$type, 'expiry'=>time());
1105 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1106 if ($changedsince !== NULL) {
1107 $params['changedsince'] = $changedsince;
1108 $sqlwhere .= " AND timemodified > :changedsince";
1112 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1113 foreach ($flags as $flag) {
1114 $cf[$flag->name] = $flag->value;
1121 * Get volatile flags
1123 * @param string $type
1124 * @param string $name
1125 * @param int $changedsince default null
1126 * @return records array
1128 function get_cache_flag($type, $name, $changedsince=NULL) {
1131 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1133 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1134 if ($changedsince !== NULL) {
1135 $params['changedsince'] = $changedsince;
1136 $sqlwhere .= " AND timemodified > :changedsince";
1139 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1143 * Set a volatile flag
1145 * @param string $type the "type" namespace for the key
1146 * @param string $name the key to set
1147 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1148 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1149 * @return bool Always returns true
1151 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1154 $timemodified = time();
1155 if ($expiry===NULL || $expiry < $timemodified) {
1156 $expiry = $timemodified + 24 * 60 * 60;
1158 $expiry = (int)$expiry;
1161 if ($value === NULL) {
1162 unset_cache_flag($type,$name);
1166 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potentail problem in DEBUG_DEVELOPER
1167 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1168 return true; //no need to update; helps rcache too
1171 $f->expiry = $expiry;
1172 $f->timemodified = $timemodified;
1173 $DB->update_record('cache_flags', $f);
1176 $f->flagtype = $type;
1179 $f->expiry = $expiry;
1180 $f->timemodified = $timemodified;
1181 $DB->insert_record('cache_flags', $f);
1187 * Removes a single volatile flag
1190 * @param string $type the "type" namespace for the key
1191 * @param string $name the key to set
1194 function unset_cache_flag($type, $name) {
1196 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1201 * Garbage-collect volatile flags
1203 * @return bool Always returns true
1205 function gc_cache_flags() {
1207 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1211 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1214 * Refresh current $USER session global variable with all their current preferences.
1217 * @param mixed $time default null
1220 function check_user_preferences_loaded($time = null) {
1222 static $timenow = null; // Static cache, so we only check up-to-dateness once per request.
1224 if (!empty($USER->preference) && isset($USER->preference['_lastloaded'])) {
1225 // Already loaded. Are we up to date?
1227 if (is_null($timenow) || (!is_null($time) && $time != $timenow)) {
1229 if (!get_cache_flag('userpreferenceschanged', $USER->id, $USER->preference['_lastloaded'])) {
1230 // We are up-to-date.
1234 // Already checked for up-to-date-ness.
1239 // OK, so we have to reload. Reset preference
1240 $USER->preference = array();
1242 if (!isloggedin() or isguestuser()) {
1243 // No permanent storage for not-logged-in user and guest
1245 } else if ($preferences = $DB->get_records('user_preferences', array('userid'=>$USER->id))) {
1246 foreach ($preferences as $preference) {
1247 $USER->preference[$preference->name] = $preference->value;
1251 $USER->preference['_lastloaded'] = $timenow;
1255 * Called from set/delete_user_preferences, so that the prefs can be correctly reloaded.
1259 * @param integer $userid the user whose prefs were changed.
1261 function mark_user_preferences_changed($userid) {
1263 if ($userid == $USER->id) {
1264 check_user_preferences_loaded(time());
1266 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1270 * Sets a preference for the current user
1272 * Optionally, can set a preference for a different user object
1274 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
1278 * @param string $name The key to set as preference for the specified user
1279 * @param string $value The value to set for the $name key in the specified user's record
1280 * @param int $otheruserid A moodle user ID, default null
1283 function set_user_preference($name, $value, $otheruserid=NULL) {
1291 if (empty($otheruserid)){
1292 if (!isloggedin() or isguestuser()) {
1295 $userid = $USER->id;
1297 if (isguestuser($otheruserid)) {
1300 $userid = $otheruserid;
1304 // no permanent storage for not-logged-in user and guest
1306 } else if ($preference = $DB->get_record('user_preferences', array('userid'=>$userid, 'name'=>$name))) {
1307 if ($preference->value === $value) {
1310 $DB->set_field('user_preferences', 'value', (string)$value, array('id'=>$preference->id));
1313 $preference = new object();
1314 $preference->userid = $userid;
1315 $preference->name = $name;
1316 $preference->value = (string)$value;
1317 $DB->insert_record('user_preferences', $preference);
1320 mark_user_preferences_changed($userid);
1321 // update value in USER session if needed
1322 if ($userid == $USER->id) {
1323 $USER->preference[$name] = (string)$value;
1324 $USER->preference['_lastloaded'] = time();
1331 * Sets a whole array of preferences for the current user
1333 * @param array $prefarray An array of key/value pairs to be set
1334 * @param int $otheruserid A moodle user ID
1337 function set_user_preferences($prefarray, $otheruserid=NULL) {
1339 if (!is_array($prefarray) or empty($prefarray)) {
1343 foreach ($prefarray as $name => $value) {
1344 set_user_preference($name, $value, $otheruserid);
1350 * Unsets a preference completely by deleting it from the database
1352 * Optionally, can set a preference for a different user id
1355 * @param string $name The key to unset as preference for the specified user
1356 * @param int $otheruserid A moodle user ID
1358 function unset_user_preference($name, $otheruserid=NULL) {
1361 if (empty($otheruserid)){
1362 $userid = $USER->id;
1363 check_user_preferences_loaded();
1365 $userid = $otheruserid;
1369 $DB->delete_records('user_preferences', array('userid'=>$userid, 'name'=>$name));
1371 mark_user_preferences_changed($userid);
1372 //Delete the preference from $USER if needed
1373 if ($userid == $USER->id) {
1374 unset($USER->preference[$name]);
1375 $USER->preference['_lastloaded'] = time();
1382 * Used to fetch user preference(s)
1384 * If no arguments are supplied this function will return
1385 * all of the current user preferences as an array.
1387 * If a name is specified then this function
1388 * attempts to return that particular preference value. If
1389 * none is found, then the optional value $default is returned,
1394 * @param string $name Name of the key to use in finding a preference value
1395 * @param string $default Value to be returned if the $name key is not set in the user preferences
1396 * @param int $otheruserid A moodle user ID
1399 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
1402 if (empty($otheruserid) || (isloggedin() && ($USER->id == $otheruserid))){
1403 check_user_preferences_loaded();
1406 return $USER->preference; // All values
1407 } else if (array_key_exists($name, $USER->preference)) {
1408 return $USER->preference[$name]; // The single value
1410 return $default; // Default value (or NULL)
1415 return $DB->get_records_menu('user_preferences', array('userid'=>$otheruserid), '', 'name,value'); // All values
1416 } else if ($value = $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>$name))) {
1417 return $value; // The single value
1419 return $default; // Default value (or NULL)
1424 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1427 * Given date parts in user time produce a GMT timestamp.
1429 * @todo Finish documenting this function
1430 * @param int $year The year part to create timestamp of
1431 * @param int $month The month part to create timestamp of
1432 * @param int $day The day part to create timestamp of
1433 * @param int $hour The hour part to create timestamp of
1434 * @param int $minute The minute part to create timestamp of
1435 * @param int $second The second part to create timestamp of
1436 * @param float $timezone Timezone modifier
1437 * @param bool $applydst Toggle Daylight Saving Time, default true
1438 * @return int timestamp
1440 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1442 $strtimezone = NULL;
1443 if (!is_numeric($timezone)) {
1444 $strtimezone = $timezone;
1447 $timezone = get_user_timezone_offset($timezone);
1449 if (abs($timezone) > 13) {
1450 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1452 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1453 $time = usertime($time, $timezone);
1455 $time -= dst_offset_on($time, $strtimezone);
1464 * Format a date/time (seconds) as weeks, days, hours etc as needed
1466 * Given an amount of time in seconds, returns string
1467 * formatted nicely as weeks, days, hours etc as needed
1473 * @param int $totalsecs Time in seconds
1474 * @param object $str Should be a time object
1475 * @return string A nicely formatted date/time string
1477 function format_time($totalsecs, $str=NULL) {
1479 $totalsecs = abs($totalsecs);
1481 if (!$str) { // Create the str structure the slow way
1482 $str->day = get_string('day');
1483 $str->days = get_string('days');
1484 $str->hour = get_string('hour');
1485 $str->hours = get_string('hours');
1486 $str->min = get_string('min');
1487 $str->mins = get_string('mins');
1488 $str->sec = get_string('sec');
1489 $str->secs = get_string('secs');
1490 $str->year = get_string('year');
1491 $str->years = get_string('years');
1495 $years = floor($totalsecs/YEARSECS);
1496 $remainder = $totalsecs - ($years*YEARSECS);
1497 $days = floor($remainder/DAYSECS);
1498 $remainder = $totalsecs - ($days*DAYSECS);
1499 $hours = floor($remainder/HOURSECS);
1500 $remainder = $remainder - ($hours*HOURSECS);
1501 $mins = floor($remainder/MINSECS);
1502 $secs = $remainder - ($mins*MINSECS);
1504 $ss = ($secs == 1) ? $str->sec : $str->secs;
1505 $sm = ($mins == 1) ? $str->min : $str->mins;
1506 $sh = ($hours == 1) ? $str->hour : $str->hours;
1507 $sd = ($days == 1) ? $str->day : $str->days;
1508 $sy = ($years == 1) ? $str->year : $str->years;
1516 if ($years) $oyears = $years .' '. $sy;
1517 if ($days) $odays = $days .' '. $sd;
1518 if ($hours) $ohours = $hours .' '. $sh;
1519 if ($mins) $omins = $mins .' '. $sm;
1520 if ($secs) $osecs = $secs .' '. $ss;
1522 if ($years) return trim($oyears .' '. $odays);
1523 if ($days) return trim($odays .' '. $ohours);
1524 if ($hours) return trim($ohours .' '. $omins);
1525 if ($mins) return trim($omins .' '. $osecs);
1526 if ($secs) return $osecs;
1527 return get_string('now');
1531 * Returns a formatted string that represents a date in user time
1533 * Returns a formatted string that represents a date in user time
1534 * <b>WARNING: note that the format is for strftime(), not date().</b>
1535 * Because of a bug in most Windows time libraries, we can't use
1536 * the nicer %e, so we have to use %d which has leading zeroes.
1537 * A lot of the fuss in the function is just getting rid of these leading
1538 * zeroes as efficiently as possible.
1540 * If parameter fixday = true (default), then take off leading
1541 * zero from %d, else maintain it.
1543 * @param int $date the timestamp in UTC, as obtained from the database.
1544 * @param string $format strftime format. You should probably get this using
1545 * get_string('strftime...', 'langconfig');
1546 * @param float $timezone by default, uses the user's time zone.
1547 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1548 * If false then the leading zero is maintained.
1549 * @return string the formatted date/time.
1551 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1555 $strtimezone = NULL;
1556 if (!is_numeric($timezone)) {
1557 $strtimezone = $timezone;
1560 if (empty($format)) {
1561 $format = get_string('strftimedaydatetime', 'langconfig');
1564 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1566 } else if ($fixday) {
1567 $formatnoday = str_replace('%d', 'DD', $format);
1568 $fixday = ($formatnoday != $format);
1571 $date += dst_offset_on($date, $strtimezone);
1573 $timezone = get_user_timezone_offset($timezone);
1575 if (abs($timezone) > 13) { /// Server time
1577 $datestring = strftime($formatnoday, $date);
1578 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
1579 $datestring = str_replace('DD', $daystring, $datestring);
1581 $datestring = strftime($format, $date);
1584 $date += (int)($timezone * 3600);
1586 $datestring = gmstrftime($formatnoday, $date);
1587 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
1588 $datestring = str_replace('DD', $daystring, $datestring);
1590 $datestring = gmstrftime($format, $date);
1594 /// If we are running under Windows convert from windows encoding to UTF-8
1595 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1597 if ($CFG->ostype == 'WINDOWS') {
1598 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1599 $textlib = textlib_get_instance();
1600 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1608 * Given a $time timestamp in GMT (seconds since epoch),
1609 * returns an array that represents the date in user time
1611 * @todo Finish documenting this function
1613 * @param int $time Timestamp in GMT
1614 * @param float $timezone ?
1615 * @return array An array that represents the date in user time
1617 function usergetdate($time, $timezone=99) {
1619 $strtimezone = NULL;
1620 if (!is_numeric($timezone)) {
1621 $strtimezone = $timezone;
1624 $timezone = get_user_timezone_offset($timezone);
1626 if (abs($timezone) > 13) { // Server time
1627 return getdate($time);
1630 // There is no gmgetdate so we use gmdate instead
1631 $time += dst_offset_on($time, $strtimezone);
1632 $time += intval((float)$timezone * HOURSECS);
1634 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
1636 //be careful to ensure the returned array matches that produced by getdate() above
1639 $getdate['weekday'],
1646 $getdate['minutes'],
1648 ) = explode('_', $datestring);
1654 * Given a GMT timestamp (seconds since epoch), offsets it by
1655 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1658 * @param int $date Timestamp in GMT
1659 * @param float $timezone
1662 function usertime($date, $timezone=99) {
1664 $timezone = get_user_timezone_offset($timezone);
1666 if (abs($timezone) > 13) {
1669 return $date - (int)($timezone * HOURSECS);
1673 * Given a time, return the GMT timestamp of the most recent midnight
1674 * for the current user.
1676 * @param int $date Timestamp in GMT
1677 * @param float $timezone Defaults to user's timezone
1678 * @return int Returns a GMT timestamp
1680 function usergetmidnight($date, $timezone=99) {
1682 $userdate = usergetdate($date, $timezone);
1684 // Time of midnight of this user's day, in GMT
1685 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1690 * Returns a string that prints the user's timezone
1692 * @param float $timezone The user's timezone
1695 function usertimezone($timezone=99) {
1697 $tz = get_user_timezone($timezone);
1699 if (!is_float($tz)) {
1703 if(abs($tz) > 13) { // Server time
1704 return get_string('serverlocaltime');
1707 if($tz == intval($tz)) {
1708 // Don't show .0 for whole hours
1725 * Returns a float which represents the user's timezone difference from GMT in hours
1726 * Checks various settings and picks the most dominant of those which have a value
1730 * @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
1733 function get_user_timezone_offset($tz = 99) {
1737 $tz = get_user_timezone($tz);
1739 if (is_float($tz)) {
1742 $tzrecord = get_timezone_record($tz);
1743 if (empty($tzrecord)) {
1746 return (float)$tzrecord->gmtoff / HOURMINS;
1751 * Returns an int which represents the systems's timezone difference from GMT in seconds
1754 * @param mixed $tz timezone
1755 * @return int if found, false is timezone 99 or error
1757 function get_timezone_offset($tz) {
1764 if (is_numeric($tz)) {
1765 return intval($tz * 60*60);
1768 if (!$tzrecord = get_timezone_record($tz)) {
1771 return intval($tzrecord->gmtoff * 60);
1775 * Returns a float or a string which denotes the user's timezone
1776 * 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)
1777 * means that for this timezone there are also DST rules to be taken into account
1778 * Checks various settings and picks the most dominant of those which have a value
1782 * @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
1785 function get_user_timezone($tz = 99) {
1790 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1791 isset($USER->timezone) ? $USER->timezone : 99,
1792 isset($CFG->timezone) ? $CFG->timezone : 99,
1797 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
1798 $tz = $next['value'];
1801 return is_numeric($tz) ? (float) $tz : $tz;
1805 * Returns cached timezone record for given $timezonename
1809 * @param string $timezonename
1810 * @return mixed timezonerecord object or false
1812 function get_timezone_record($timezonename) {
1814 static $cache = NULL;
1816 if ($cache === NULL) {
1820 if (isset($cache[$timezonename])) {
1821 return $cache[$timezonename];
1824 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
1825 WHERE name = ? ORDER BY year DESC', array($timezonename), true);
1829 * Build and store the users Daylight Saving Time (DST) table
1834 * @param mixed $from_year Start year for the table, defaults to 1971
1835 * @param mixed $to_year End year for the table, defaults to 2035
1836 * @param mixed $strtimezone
1839 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
1840 global $CFG, $SESSION, $DB;
1842 $usertz = get_user_timezone($strtimezone);
1844 if (is_float($usertz)) {
1845 // Trivial timezone, no DST
1849 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1850 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1851 unset($SESSION->dst_offsets);
1852 unset($SESSION->dst_range);
1855 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1856 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1857 // This will be the return path most of the time, pretty light computationally
1861 // Reaching here means we either need to extend our table or create it from scratch
1863 // Remember which TZ we calculated these changes for
1864 $SESSION->dst_offsettz = $usertz;
1866 if(empty($SESSION->dst_offsets)) {
1867 // If we 're creating from scratch, put the two guard elements in there
1868 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1870 if(empty($SESSION->dst_range)) {
1871 // If creating from scratch
1872 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1873 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1875 // Fill in the array with the extra years we need to process
1876 $yearstoprocess = array();
1877 for($i = $from; $i <= $to; ++$i) {
1878 $yearstoprocess[] = $i;
1881 // Take note of which years we have processed for future calls
1882 $SESSION->dst_range = array($from, $to);
1885 // If needing to extend the table, do the same
1886 $yearstoprocess = array();
1888 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1889 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
1891 if($from < $SESSION->dst_range[0]) {
1892 // Take note of which years we need to process and then note that we have processed them for future calls
1893 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
1894 $yearstoprocess[] = $i;
1896 $SESSION->dst_range[0] = $from;
1898 if($to > $SESSION->dst_range[1]) {
1899 // Take note of which years we need to process and then note that we have processed them for future calls
1900 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
1901 $yearstoprocess[] = $i;
1903 $SESSION->dst_range[1] = $to;
1907 if(empty($yearstoprocess)) {
1908 // This means that there was a call requesting a SMALLER range than we have already calculated
1912 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1913 // Also, the array is sorted in descending timestamp order!
1917 static $presets_cache = array();
1918 if (!isset($presets_cache[$usertz])) {
1919 $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');
1921 if(empty($presets_cache[$usertz])) {
1925 // Remove ending guard (first element of the array)
1926 reset($SESSION->dst_offsets);
1927 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
1929 // Add all required change timestamps
1930 foreach($yearstoprocess as $y) {
1931 // Find the record which is in effect for the year $y
1932 foreach($presets_cache[$usertz] as $year => $preset) {
1938 $changes = dst_changes_for_year($y, $preset);
1940 if($changes === NULL) {
1943 if($changes['dst'] != 0) {
1944 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
1946 if($changes['std'] != 0) {
1947 $SESSION->dst_offsets[$changes['std']] = 0;
1951 // Put in a guard element at the top
1952 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1953 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1956 krsort($SESSION->dst_offsets);
1962 * Calculates the required DST change and returns a Timestamp Array
1966 * @param mixed $year Int or String Year to focus on
1967 * @param object $timezone Instatiated Timezone object
1968 * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
1970 function dst_changes_for_year($year, $timezone) {
1972 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1976 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1977 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1979 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1980 list($std_hour, $std_min) = explode(':', $timezone->std_time);
1982 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1983 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
1985 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1986 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1987 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1989 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1990 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
1992 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1996 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
1999 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2002 function dst_offset_on($time, $strtimezone = NULL) {
2005 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2009 reset($SESSION->dst_offsets);
2010 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2011 if($from <= $time) {
2016 // This is the normal return path
2017 if($offset !== NULL) {
2021 // Reaching this point means we haven't calculated far enough, do it now:
2022 // Calculate extra DST changes if needed and recurse. The recursion always
2023 // moves toward the stopping condition, so will always end.
2026 // We need a year smaller than $SESSION->dst_range[0]
2027 if($SESSION->dst_range[0] == 1971) {
2030 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2031 return dst_offset_on($time, $strtimezone);
2034 // We need a year larger than $SESSION->dst_range[1]
2035 if($SESSION->dst_range[1] == 2035) {
2038 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2039 return dst_offset_on($time, $strtimezone);
2046 * @todo Document what this function does
2047 * @param int $startday
2048 * @param int $weekday
2053 function find_day_in_month($startday, $weekday, $month, $year) {
2055 $daysinmonth = days_in_month($month, $year);
2057 if($weekday == -1) {
2058 // Don't care about weekday, so return:
2059 // abs($startday) if $startday != -1
2060 // $daysinmonth otherwise
2061 return ($startday == -1) ? $daysinmonth : abs($startday);
2064 // From now on we 're looking for a specific weekday
2066 // Give "end of month" its actual value, since we know it
2067 if($startday == -1) {
2068 $startday = -1 * $daysinmonth;
2071 // Starting from day $startday, the sign is the direction
2075 $startday = abs($startday);
2076 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2078 // This is the last such weekday of the month
2079 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2080 if($lastinmonth > $daysinmonth) {
2084 // Find the first such weekday <= $startday
2085 while($lastinmonth > $startday) {
2089 return $lastinmonth;
2094 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
2096 $diff = $weekday - $indexweekday;
2101 // This is the first such weekday of the month equal to or after $startday
2102 $firstfromindex = $startday + $diff;
2104 return $firstfromindex;
2110 * Calculate the number of days in a given month
2112 * @param int $month The month whose day count is sought
2113 * @param int $year The year of the month whose day count is sought
2116 function days_in_month($month, $year) {
2117 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
2121 * Calculate the position in the week of a specific calendar day
2123 * @param int $day The day of the date whose position in the week is sought
2124 * @param int $month The month of the date whose position in the week is sought
2125 * @param int $year The year of the date whose position in the week is sought
2128 function dayofweek($day, $month, $year) {
2129 // I wonder if this is any different from
2130 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2131 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
2134 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2137 * Returns full login url.
2140 * @param bool $loginguest add login guest param, return false
2141 * @return string login url
2143 function get_login_url($loginguest=false) {
2146 if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
2147 $loginguest = $loginguest ? '?loginguest=true' : '';
2148 $url = "$CFG->wwwroot/login/index.php$loginguest";
2151 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2152 $url = "$wwwroot/login/index.php";
2159 * This function checks that the current user is logged in and has the
2160 * required privileges
2162 * This function checks that the current user is logged in, and optionally
2163 * whether they are allowed to be in a particular course and view a particular
2165 * If they are not logged in, then it redirects them to the site login unless
2166 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2167 * case they are automatically logged in as guests.
2168 * If $courseid is given and the user is not enrolled in that course then the
2169 * user is redirected to the course enrolment page.
2170 * If $cm is given and the course module is hidden and the user is not a teacher
2171 * in the course then the user is redirected to the course home page.
2173 * When $cm parameter specified, this function sets page layout to 'module'.
2174 * You need to change it manually later if some other layout needed.
2176 * @param mixed $courseorid id of the course or course object
2177 * @param bool $autologinguest default true
2178 * @param object $cm course module object
2179 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2180 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2181 * in order to keep redirects working properly. MDL-14495
2182 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2183 * @return mixed Void, exit, and die depending on path
2185 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2186 global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2188 // setup global $COURSE, themes, language and locale
2189 if (!empty($courseorid)) {
2190 if (is_object($courseorid)) {
2191 $course = $courseorid;
2192 } else if ($courseorid == SITEID) {
2193 $course = clone($SITE);
2195 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2198 if ($cm->course != $course->id) {
2199 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2201 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2202 $PAGE->set_pagelayout('incourse');
2204 $PAGE->set_course($course); // set's up global $COURSE
2207 // do not touch global $COURSE via $PAGE->set_course(),
2208 // the reasons is we need to be able to call require_login() at any time!!
2211 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2215 // If the user is not even logged in yet then make sure they are
2216 if (!isloggedin()) {
2217 //NOTE: $USER->site check was obsoleted by session test cookie,
2218 // $USER->confirmed test is in login/index.php
2219 if ($preventredirect) {
2220 throw new require_login_exception('You are not logged in');
2223 if ($setwantsurltome) {
2224 $SESSION->wantsurl = $FULLME;
2226 if (!empty($_SERVER['HTTP_REFERER'])) {
2227 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2229 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2230 if ($course->id == SITEID) {
2233 $loginguest = false;
2236 $loginguest = false;
2238 redirect(get_login_url($loginguest));
2239 exit; // never reached
2242 // loginas as redirection if needed
2243 if ($course->id != SITEID and session_is_loggedinas()) {
2244 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2245 if ($USER->loginascontext->instanceid != $course->id) {
2246 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2251 // check whether the user should be changing password (but only if it is REALLY them)
2252 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2253 $userauth = get_auth_plugin($USER->auth);
2254 if ($userauth->can_change_password() and !$preventredirect) {
2255 $SESSION->wantsurl = $FULLME;
2256 if ($changeurl = $userauth->change_password_url()) {
2257 //use plugin custom url
2258 redirect($changeurl);
2260 //use moodle internal method
2261 if (empty($CFG->loginhttps)) {
2262 redirect($CFG->wwwroot .'/login/change_password.php');
2264 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2265 redirect($wwwroot .'/login/change_password.php');
2269 print_error('nopasswordchangeforced', 'auth');
2273 // Check that the user account is properly set up
2274 if (user_not_fully_set_up($USER)) {
2275 if ($preventredirect) {
2276 throw new require_login_exception('User not fully set-up');
2278 $SESSION->wantsurl = $FULLME;
2279 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2282 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2285 // Do not bother admins with any formalities
2286 if (is_siteadmin()) {
2287 //set accesstime or the user will appear offline which messes up messaging
2288 user_accesstime_log($course->id);
2292 // Check that the user has agreed to a site policy if there is one
2293 if (!empty($CFG->sitepolicy)) {
2294 if ($preventredirect) {
2295 throw new require_login_exception('Policy not agreed');
2297 if (!$USER->policyagreed) {
2298 $SESSION->wantsurl = $FULLME;
2299 redirect($CFG->wwwroot .'/user/policy.php');
2303 // Fetch the system context, the course context, and prefetch its child contexts
2304 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2305 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2307 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2312 // If the site is currently under maintenance, then print a message
2313 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2314 if ($preventredirect) {
2315 throw new require_login_exception('Maintenance in progress');
2318 print_maintenance_message();
2321 // make sure the course itself is not hidden
2322 if ($course->id == SITEID) {
2323 // frontpage can not be hidden
2325 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2326 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2328 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2329 // originally there was also test of parent category visibility,
2330 // BUT is was very slow in complex queries involving "my courses"
2331 // now it is also possible to simply hide all courses user is not enrolled in :-)
2332 if ($preventredirect) {
2333 throw new require_login_exception('Course is hidden');
2335 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2340 // is the user enrolled?
2341 if ($course->id == SITEID) {
2342 // everybody is enrolled on the frontpage
2345 if (session_is_loggedinas()) {
2346 // Make sure the REAL person can access this course first
2347 $realuser = session_get_realuser();
2348 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2349 if ($preventredirect) {
2350 throw new require_login_exception('Invalid course login-as access');
2352 echo $OUTPUT->header();
2353 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2357 // very simple enrolment caching - changes in course setting are not reflected immediately
2358 if (!isset($USER->enrol)) {
2359 $USER->enrol = array();
2360 $USER->enrol['enrolled'] = array();
2361 $USER->enrol['tempguest'] = array();
2366 if (is_viewing($coursecontext, $USER)) {
2367 // ok, no need to mess with enrol
2371 if (isset($USER->enrol['enrolled'][$course->id])) {
2372 if ($USER->enrol['enrolled'][$course->id] == 0) {
2374 } else if ($USER->enrol['enrolled'][$course->id] > time()) {
2378 unset($USER->enrol['enrolled'][$course->id]);
2381 if (isset($USER->enrol['tempguest'][$course->id])) {
2382 if ($USER->enrol['tempguest'][$course->id] == 0) {
2384 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2388 unset($USER->enrol['tempguest'][$course->id]);
2389 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2395 } else if (is_enrolled($coursecontext, $USER, '', true)) {
2396 // active participants may always access
2397 // TODO: refactor this into some new function
2399 $sql = "SELECT MAX(ue.timeend)
2400 FROM {user_enrolments} ue
2401 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2402 JOIN {user} u ON u.id = ue.userid
2403 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0
2404 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
2405 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE,
2406 'userid'=>$USER->id, 'courseid'=>$coursecontext->instanceid, 'now1'=>$now, 'now2'=>$now);
2407 $until = $DB->get_field_sql($sql, $params);
2408 if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) {
2409 $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD;
2412 $USER->enrol['enrolled'][$course->id] = $until;
2415 // remove traces of previous temp guest access
2416 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2419 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2420 $enrols = enrol_get_plugins(true);
2421 // first ask all enabled enrol instances in course if they want to auto enrol user
2422 foreach($instances as $instance) {
2423 if (!isset($enrols[$instance->enrol])) {
2426 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2427 if ($until !== false) {
2428 $USER->enrol['enrolled'][$course->id] = $until;
2429 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2434 // if not enrolled yet try to gain temporary guest access
2436 foreach($instances as $instance) {
2437 if (!isset($enrols[$instance->enrol])) {
2440 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2441 if ($until !== false) {
2442 $USER->enrol['tempguest'][$course->id] = $until;
2452 if ($preventredirect) {
2453 throw new require_login_exception('Not enrolled');
2455 $SESSION->wantsurl = $FULLME;
2456 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2461 if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2462 if ($preventredirect) {
2463 throw new require_login_exception('Activity is hidden');
2465 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2468 // groupmembersonly access control
2469 if (!empty($CFG->enablegroupmembersonly) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2470 if (isguestuser() or !groups_has_membership($cm)) {
2471 if ($preventredirect) {
2472 throw new require_login_exception('Not member of a group');
2474 print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
2478 // Conditional activity access control
2479 if (!empty($CFG->enableavailability) and $cm) {
2480 // TODO: this is going to work with login-as-user, sorry!
2481 // We cache conditional access in session
2482 if (!isset($SESSION->conditionaccessok)) {
2483 $SESSION->conditionaccessok = array();
2485 // If you have been allowed into the module once then you are allowed
2486 // in for rest of session, no need to do conditional checks
2487 if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
2488 // Get condition info (does a query for the availability table)
2489 require_once($CFG->libdir.'/conditionlib.php');
2490 $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
2491 // Check condition for user (this will do a query if the availability
2492 // information depends on grade or completion information)
2493 if ($ci->is_available($junk) || has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2494 $SESSION->conditionaccessok[$cm->id] = true;
2496 print_error('activityiscurrentlyhidden');
2501 // Finally access granted, update lastaccess times
2502 user_accesstime_log($course->id);
2507 * This function just makes sure a user is logged out.
2511 function require_logout() {
2515 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2517 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2518 foreach($authsequence as $authname) {
2519 $authplugin = get_auth_plugin($authname);
2520 $authplugin->prelogout_hook();
2524 session_get_instance()->terminate_current();
2528 * Weaker version of require_login()
2530 * This is a weaker version of {@link require_login()} which only requires login
2531 * when called from within a course rather than the site page, unless
2532 * the forcelogin option is turned on.
2533 * @see require_login()
2536 * @param mixed $courseorid The course object or id in question
2537 * @param bool $autologinguest Allow autologin guests if that is wanted
2538 * @param object $cm Course activity module if known
2539 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2540 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2541 * in order to keep redirects working properly. MDL-14495
2542 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2545 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2546 global $CFG, $PAGE, $SITE;
2547 if (!empty($CFG->forcelogin)) {
2548 // login required for both SITE and courses
2549 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2551 } else if (!empty($cm) and !$cm->visible) {
2552 // always login for hidden activities
2553 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2555 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2556 or (!is_object($courseorid) and $courseorid == SITEID)) {
2557 //login for SITE not required
2558 if ($cm and empty($cm->visible)) {
2559 // hidden activities are not accessible without login
2560 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2561 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2562 // not-logged-in users do not have any group membership
2563 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2565 // We still need to instatiate PAGE vars properly so that things
2566 // that rely on it like navigation function correctly.
2567 if (!empty($courseorid)) {
2568 if (is_object($courseorid)) {
2569 $course = $courseorid;
2571 $course = clone($SITE);
2574 if ($cm->course != $course->id) {
2575 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2577 $PAGE->set_cm($cm, $course);
2578 $PAGE->set_pagelayout('incourse');
2580 $PAGE->set_course($course);
2583 // If $PAGE->course, and hence $PAGE->context, have not already been set
2584 // up properly, set them up now.
2585 $PAGE->set_course($PAGE->course);
2587 //TODO: verify conditional activities here
2588 user_accesstime_log(SITEID);
2593 // course login always required
2594 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2599 * Require key login. Function terminates with error if key not found or incorrect.
2605 * @uses NO_MOODLE_COOKIES
2606 * @uses PARAM_ALPHANUM
2607 * @param string $script unique script identifier
2608 * @param int $instance optional instance id
2609 * @return int Instance ID
2611 function require_user_key_login($script, $instance=null) {
2612 global $USER, $SESSION, $CFG, $DB;
2614 if (!NO_MOODLE_COOKIES) {
2615 print_error('sessioncookiesdisable');
2619 @session_write_close();
2621 $keyvalue = required_param('key', PARAM_ALPHANUM);
2623 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2624 print_error('invalidkey');
2627 if (!empty($key->validuntil) and $key->validuntil < time()) {
2628 print_error('expiredkey');
2631 if ($key->iprestriction) {
2632 $remoteaddr = getremoteaddr(null);
2633 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2634 print_error('ipmismatch');
2638 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2639 print_error('invaliduserid');
2642 /// emulate normal session
2643 session_set_user($user);
2645 /// note we are not using normal login
2646 if (!defined('USER_KEY_LOGIN')) {
2647 define('USER_KEY_LOGIN', true);
2650 /// return isntance id - it might be empty
2651 return $key->instance;
2655 * Creates a new private user access key.
2658 * @param string $script unique target identifier
2659 * @param int $userid
2660 * @param int $instance optional instance id
2661 * @param string $iprestriction optional ip restricted access
2662 * @param timestamp $validuntil key valid only until given data
2663 * @return string access key value
2665 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2668 $key = new object();
2669 $key->script = $script;
2670 $key->userid = $userid;
2671 $key->instance = $instance;
2672 $key->iprestriction = $iprestriction;
2673 $key->validuntil = $validuntil;
2674 $key->timecreated = time();
2676 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
2677 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
2679 $key->value = md5($userid.'_'.time().random_string(40));
2681 $DB->insert_record('user_private_key', $key);
2686 * Delete the user's new private user access keys for a particular script.
2689 * @param string $script unique target identifier
2690 * @param int $userid
2693 function delete_user_key($script,$userid) {
2695 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
2699 * Gets a private user access key (and creates one if one doesn't exist).
2702 * @param string $script unique target identifier
2703 * @param int $userid
2704 * @param int $instance optional instance id
2705 * @param string $iprestriction optional ip restricted access
2706 * @param timestamp $validuntil key valid only until given data
2707 * @return string access key value
2709 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2712 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
2713 'instance'=>$instance, 'iprestriction'=>$iprestriction,
2714 'validuntil'=>$validuntil))) {
2717 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
2723 * Modify the user table by setting the currently logged in user's
2724 * last login to now.
2728 * @return bool Always returns true
2730 function update_user_login_times() {
2733 $user = new object();
2734 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2735 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2737 $user->id = $USER->id;
2739 $DB->update_record('user', $user);
2744 * Determines if a user has completed setting up their account.
2746 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
2749 function user_not_fully_set_up($user) {
2750 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
2754 * Check whether the user has exceeded the bounce threshold
2758 * @param user $user A {@link $USER} object
2759 * @return bool true=>User has exceeded bounce threshold
2761 function over_bounce_threshold($user) {
2764 if (empty($CFG->handlebounces)) {
2768 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2772 // set sensible defaults
2773 if (empty($CFG->minbounces)) {
2774 $CFG->minbounces = 10;
2776 if (empty($CFG->bounceratio)) {
2777 $CFG->bounceratio = .20;
2781 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2782 $bouncecount = $bounce->value;
2784 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2785 $sendcount = $send->value;
2787 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2791 * Used to increment or reset email sent count
2794 * @param user $user object containing an id
2795 * @param bool $reset will reset the count to 0
2798 function set_send_count($user,$reset=false) {
2801 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2805 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2806 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2807 $DB->update_record('user_preferences', $pref);
2809 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2811 $pref = new object();
2812 $pref->name = 'email_send_count';
2814 $pref->userid = $user->id;
2815 $DB->insert_record('user_preferences', $pref, false);
2820 * Increment or reset user's email bounce count
2823 * @param user $user object containing an id
2824 * @param bool $reset will reset the count to 0
2826 function set_bounce_count($user,$reset=false) {
2829 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2830 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2831 $DB->update_record('user_preferences', $pref);
2833 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2835 $pref = new object();
2836 $pref->name = 'email_bounce_count';
2838 $pref->userid = $user->id;
2839 $DB->insert_record('user_preferences', $pref, false);
2844 * Keeps track of login attempts
2848 function update_login_count() {
2853 if (empty($SESSION->logincount)) {
2854 $SESSION->logincount = 1;
2856 $SESSION->logincount++;
2859 if ($SESSION->logincount > $max_logins) {
2860 unset($SESSION->wantsurl);
2861 print_error('errortoomanylogins');
2866 * Resets login attempts
2870 function reset_login_count() {
2873 $SESSION->logincount = 0;
2877 * Returns reference to full info about modules in course (including visibility).
2878 * Cached and as fast as possible (0 or 1 db query).
2883 * @uses CONTEXT_MODULE
2884 * @uses MAX_MODINFO_CACHE_SIZE
2885 * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
2886 * @param int $userid Defaults to current user id
2887 * @return mixed courseinfo object or nothing if resetting
2889 function &get_fast_modinfo(&$course, $userid=0) {
2890 global $CFG, $USER, $DB;
2891 require_once($CFG->dirroot.'/course/lib.php');
2893 if (!empty($CFG->enableavailability)) {
2894 require_once($CFG->libdir.'/conditionlib.php');
2897 static $cache = array();
2899 if ($course === 'reset') {
2902 return $nothing; // we must return some reference
2905 if (empty($userid)) {
2906 $userid = $USER->id;
2909 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
2910 return $cache[$course->id];
2913 if (empty($course->modinfo)) {
2914 // no modinfo yet - load it
2915 rebuild_course_cache($course->id);
2916 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2919 $modinfo = new object();
2920 $modinfo->courseid = $course->id;
2921 $modinfo->userid = $userid;
2922 $modinfo->sections = array();
2923 $modinfo->cms = array();
2924 $modinfo->instances = array();
2925 $modinfo->groups = null; // loaded only when really needed - the only one db query
2927 $info = unserialize($course->modinfo);
2928 if (!is_array($info)) {
2929 // hmm, something is wrong - lets try to fix it
2930 rebuild_course_cache($course->id);
2931 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2932 $info = unserialize($course->modinfo);
2933 if (!is_array($info)) {
2939 // detect if upgrade required
2940 $first = reset($info);
2941 if (!isset($first->id)) {
2942 rebuild_course_cache($course->id);
2943 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2944 $info = unserialize($course->modinfo);
2945 if (!is_array($info)) {
2951 $modlurals = array();
2953 // If we haven't already preloaded contexts for the course, do it now
2954 preload_course_contexts($course->id);
2956 foreach ($info as $mod) {
2957 if (empty($mod->name)) {
2958 // something is wrong here
2961 // reconstruct minimalistic $cm
2964 $cm->instance = $mod->id;
2965 $cm->course = $course->id;
2966 $cm->modname = $mod->mod;
2967 $cm->idnumber = $mod->idnumber;
2968 $cm->name = $mod->name;
2969 $cm->visible = $mod->visible;
2970 $cm->sectionnum = $mod->section;
2971 $cm->groupmode = $mod->groupmode;
2972 $cm->groupingid = $mod->groupingid;
2973 $cm->groupmembersonly = $mod->groupmembersonly;
2974 $cm->indent = $mod->indent;
2975 $cm->completion = $mod->completion;
2976 $cm->extra = isset($mod->extra) ? $mod->extra : '';
2977 $cm->icon = isset($mod->icon) ? $mod->icon : '';
2978 $cm->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
2979 $cm->uservisible = true;
2980 if(!empty($CFG->enableavailability)) {
2981 // We must have completion information from modinfo. If it's not
2982 // there, cache needs rebuilding
2983 if(!isset($mod->availablefrom)) {
2984 debugging('enableavailability option was changed; rebuilding '.
2985 'cache for course '.$course->id);
2986 rebuild_course_cache($course->id,true);
2987 // Re-enter this routine to do it all properly
2988 return get_fast_modinfo($course,$userid);
2990 $cm->availablefrom = $mod->availablefrom;
2991 $cm->availableuntil = $mod->availableuntil;
2992 $cm->showavailability = $mod->showavailability;
2993 $cm->conditionscompletion = $mod->conditionscompletion;
2994 $cm->conditionsgrade = $mod->conditionsgrade;
2997 // preload long names plurals and also check module is installed properly
2998 if (!isset($modlurals[$cm->modname])) {
2999 if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
3002 $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
3004 $cm->modplural = $modlurals[$cm->modname];
3005 $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id);
3007 if(!empty($CFG->enableavailability)) {
3008 // Unfortunately the next call really wants to call
3009 // get_fast_modinfo, but that would be recursive, so we fake up a
3010 // modinfo for it already
3011 if(empty($minimalmodinfo)) {
3012 $minimalmodinfo=new stdClass();
3013 $minimalmodinfo->cms=array();
3014 foreach($info as $mod) {
3015 if (empty($mod->name)) {
3016 // something is wrong here
3019 $minimalcm = new stdClass();
3020 $minimalcm->id = $mod->cm;
3021 $minimalcm->name = $mod->name;
3022 $minimalmodinfo->cms[$minimalcm->id]=$minimalcm;
3026 // Get availability information
3027 $ci = new condition_info($cm);
3028 $cm->available=$ci->is_available($cm->availableinfo, true, $userid, $minimalmodinfo);
3030 $cm->available=true;
3032 if ((!$cm->visible or !$cm->available) and !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
3033 $cm->uservisible = false;
3035 } else if (!empty($CFG->enablegroupmembersonly) and !empty($cm->groupmembersonly)
3036 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
3037 if (is_null($modinfo->groups)) {
3038 $modinfo->groups = groups_get_user_groups($course->id, $userid);
3040 if (empty($modinfo->groups[$cm->groupingid])) {
3041 $cm->uservisible = false;
3045 if (!isset($modinfo->instances[$cm->modname])) {
3046 $modinfo->instances[$cm->modname] = array();
3048 $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
3049 $modinfo->cms[$cm->id] =& $cm;
3051 // reconstruct sections
3052 if (!isset($modinfo->sections[$cm->sectionnum])) {
3053 $modinfo->sections[$cm->sectionnum] = array();
3055 $modinfo->sections[$cm->sectionnum][] = $cm->id;
3060 unset($cache[$course->id]); // prevent potential reference problems when switching users
3061 $cache[$course->id] = $modinfo;
3063 // Ensure cache does not use too much RAM
3064 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
3067 unset($cache[$key]);
3070 return $cache[$course->id];
3074 * Determines if the currently logged in user is in editing mode.
3075 * Note: originally this function had $userid parameter - it was not usable anyway
3077 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3078 * @todo Deprecated function remove when ready
3081 * @uses DEBUG_DEVELOPER
3084 function isediting() {
3086 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3087 return $PAGE->user_is_editing();
3091 * Determines if the logged in user is currently moving an activity
3094 * @param int $courseid The id of the course being tested
3097 function ismoving($courseid) {
3100 if (!empty($USER->activitycopy)) {
3101 return ($USER->activitycopycourse == $courseid);
3107 * Returns a persons full name
3109 * Given an object containing firstname and lastname
3110 * values, this function returns a string with the
3111 * full name of the person.
3112 * The result may depend on system settings
3113 * or language. 'override' will force both names
3114 * to be used even if system settings specify one.
3118 * @param object $user A {@link $USER} object to get full name of
3119 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3122 function fullname($user, $override=false) {
3123 global $CFG, $SESSION;
3125 if (!isset($user->firstname) and !isset($user->lastname)) {
3130 if (!empty($CFG->forcefirstname)) {
3131 $user->firstname = $CFG->forcefirstname;
3133 if (!empty($CFG->forcelastname)) {
3134 $user->lastname = $CFG->forcelastname;
3138 if (!empty($SESSION->fullnamedisplay)) {
3139 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3142 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3143 return $user->firstname .' '. $user->lastname;
3145 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3146 return $user->lastname .' '. $user->firstname;
3148 } else if ($CFG->fullnamedisplay == 'firstname') {
3150 return get_string('fullnamedisplay', '', $user);
3152 return $user->firstname;
3156 return get_string('fullnamedisplay', '', $user);
3160 * Returns whether a given authentication plugin exists.
3163 * @param string $auth Form of authentication to check for. Defaults to the
3164 * global setting in {@link $CFG}.
3165 * @return boolean Whether the plugin is available.
3167 function exists_auth_plugin($auth) {
3170 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3171 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3177 * Checks if a given plugin is in the list of enabled authentication plugins.
3179 * @param string $auth Authentication plugin.
3180 * @return boolean Whether the plugin is enabled.
3182 function is_enabled_auth($auth) {
3187 $enabled = get_enabled_auth_plugins();
3189 return in_array($auth, $enabled);
3193 * Returns an authentication plugin instance.
3196 * @param string $auth name of authentication plugin
3197 * @return auth_plugin_base An instance of the required authentication plugin.
3199 function get_auth_plugin($auth) {
3202 // check the plugin exists first
3203 if (! exists_auth_plugin($auth)) {
3204 print_error('authpluginnotfound', 'debug', '', $auth);
3207 // return auth plugin instance
3208 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3209 $class = "auth_plugin_$auth";
3214 * Returns array of active auth plugins.
3216 * @param bool $fix fix $CFG->auth if needed
3219 function get_enabled_auth_plugins($fix=false) {
3222 $default = array('manual', 'nologin');
3224 if (empty($CFG->auth)) {
3227 $auths = explode(',', $CFG->auth);
3231 $auths = array_unique($auths);
3232 foreach($auths as $k=>$authname) {
3233 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3237 $newconfig = implode(',', $auths);
3238 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3239 set_config('auth', $newconfig);
3243 return (array_merge($default, $auths));
3247 * Returns true if an internal authentication method is being used.
3248 * if method not specified then, global default is assumed
3250 * @param string $auth Form of authentication required
3253 function is_internal_auth($auth) {
3254 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3255 return $authplugin->is_internal();
3259 * Returns true if the user is a 'restored' one
3261 * Used in the login process to inform the user
3262 * and allow him/her to reset the password
3266 * @param string $username username to be checked
3269 function is_restored_user($username) {
3272 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3276 * Returns an array of user fields
3278 * @return array User field/column names
3280 function get_user_fieldnames() {
3283 $fieldarray = $DB->get_columns('user');
3284 unset($fieldarray['id']);
3285 $fieldarray = array_keys($fieldarray);
3291 * Creates a bare-bones user record
3293 * @todo Outline auth types and provide code example
3297 * @param string $username New user's username to add to record
3298 * @param string $password New user's password to add to record
3299 * @param string $auth Form of authentication required
3300 * @return object A {@link $USER} object
3302 function create_user_record($username, $password, $auth='manual') {
3305 //just in case check text case
3306 $username = trim(moodle_strtolower($username));
3308 $authplugin = get_auth_plugin($auth);
3310 $newuser = new object();
3312 if ($newinfo = $authplugin->get_userinfo($username)) {
3313 $newinfo = truncate_userinfo($newinfo);
3314 foreach ($newinfo as $key => $value){
3315 $newuser->$key = $value;
3319 if (!empty($newuser->email)) {
3320 if (email_is_not_allowed($newuser->email)) {
3321 unset($newuser->email);
3325 if (!isset($newuser->city)) {
3326 $newuser->city = '';
3329 $newuser->auth = $auth;
3330 $newuser->username = $username;
3333 // user CFG lang for user if $newuser->lang is empty
3334 // or $user->lang is not an installed language
3335 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3336 $newuser->lang = $CFG->lang;
3338 $newuser->confirmed = 1;
3339 $newuser->lastip = getremoteaddr();
3340 $newuser->timemodified = time();
3341 $newuser->mnethostid = $CFG->mnet_localhost_id;
3343 $DB->insert_record('user', $newuser);
3344 $user = get_complete_user_data('username', $newuser->username);
3345 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3346 set_user_preference('auth_forcepasswordchange', 1, $user->id);
3348 update_internal_user_password($user, $password);
3353 * Will update a local user record from an external source
3356 * @param string $username New user's username to add to record
3357 * @param string $authplugin Unused
3358 * @return user A {@link $USER} object
3360 function update_user_record($username, $authplugin) {
3363 $username = trim(moodle_strtolower($username)); /// just in case check text case
3365 $oldinfo = $DB->get_record('user', array('username'=>$username), 'username, auth');
3366 $userauth = get_auth_plugin($oldinfo->auth);
3368 if ($newinfo = $userauth->get_userinfo($username)) {
3369 $newinfo = truncate_userinfo($newinfo);
3370 foreach ($newinfo as $key => $value){
3371 if ($key === 'username') {
3372 // 'username' is not a mapped updateable/lockable field, so skip it.
3375 $confval = $userauth->config->{'field_updatelocal_' . $key};
3376 $lockval = $userauth->config->{'field_lock_' . $key};
3377 if (empty($confval) || empty($lockval)) {
3380 if ($confval === 'onlogin') {
3381 // MDL-4207 Don't overwrite modified user profile values with
3382 // empty LDAP values when 'unlocked if empty' is set. The purpose
3383 // of the setting 'unlocked if empty' is to allow the user to fill
3384 // in a value for the selected field _if LDAP is giving
3385 // nothing_ for this field. Thus it makes sense to let this value
3386 // stand in until LDAP is giving a value for this field.
3387 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3388 $DB->set_field('user', $key, $value, array('username'=>$username));
3394 return get_complete_user_data('username', $username);
3398 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3399 * which may have large fields
3401 * @todo Add vartype handling to ensure $info is an array
3403 * @param array $info Array of user properties to truncate if needed
3404 * @return array The now truncated information that was passed in
3406 function truncate_userinfo($info) {
3407 // define the limits
3417 'institution' => 40,
3425 // apply where needed
3426 foreach (array_keys($info) as $key) {
3427 if (!empty($limit[$key])) {
3428 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
3436 * Marks user deleted in internal user database and notifies the auth plugin.
3437 * Also unenrols user from all roles and does other cleanup.
3439 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3441 * @param object $user User object before delete
3442 * @return boolean always true
3444 function delete_user($user) {
3446 require_once($CFG->libdir.'/grouplib.php');
3447 require_once($CFG->libdir.'/gradelib.php');
3448 require_once($CFG->dirroot.'/message/lib.php');
3450 // delete all grades - backup is kept in grade_grades_history table
3451 grade_user_delete($user->id);
3453 //move unread messages from this user to read
3454 message_move_userfrom_unread2read($user->id);
3456 // remove from all cohorts
3457 $DB->delete_records('cohort_members', array('userid'=>$user->id));
3459 // remove from all groups
3460 $DB->delete_records('groups_members', array('userid'=>$user->id));
3462 // brute force unenrol from all courses
3463 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
3465 // purge user preferences
3466 $DB->delete_records('user_preferences', array('userid'=>$user->id));
3468 // purge user extra profile info
3469 $DB->delete_records('user_info_data', array('userid'=>$user->id));
3471 // last course access not necessary either
3472 $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
3474 // final accesslib cleanup - removes all role assignments in user context and context itself, files, etc.
3475 delete_context(CONTEXT_USER, $user->id);
3477 require_once($CFG->dirroot.'/tag/lib.php');
3478 tag_set('user', $user->id, array());
3480 // workaround for bulk deletes of users with the same email address
3481 $delname = "$user->email.".time();
3482 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3486 // mark internal user record as "deleted"
3487 $updateuser = new object();
3488 $updateuser->id = $user->id;
3489 $updateuser->deleted = 1;
3490 $updateuser->username = $delname; // Remember it just in case
3491 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
3492 $updateuser->idnumber = ''; // Clear this field to free it up
3493 $updateuser->timemodified = time();
3495 $DB->update_record('user', $updateuser);
3497 // notify auth plugin - do not block the delete even when plugin fails
3498 $authplugin = get_auth_plugin($user->auth);
3499 $authplugin->user_delete($user);
3501 // any plugin that needs to cleanup should register this event
3502 events_trigger('user_deleted', $user);
3508 * Retrieve the guest user object
3512 * @return user A {@link $USER} object
3514 function guest_user() {
3517 if ($newuser = $DB->get_record('user', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
3518 $newuser->confirmed = 1;
3519 $newuser->lang = $CFG->lang;
3520 $newuser->lastip = getremoteaddr();
3527 * Authenticates a user against the chosen authentication mechanism
3529 * Given a username and password, this function looks them
3530 * up using the currently selected authentication mechanism,
3531 * and if the authentication is successful, it returns a
3532 * valid $user object from the 'user' table.
3534 * Uses auth_ functions from the currently active auth module
3536 * After authenticate_user_login() returns success, you will need to
3537 * log that the user has logged in, and call complete_user_login() to set
3542 * @param string $username User's username
3543 * @param string $password User's password
3544 * @return user|flase A {@link $USER} object or false if error
3546 function authenticate_user_login($username, $password) {
3547 global $CFG, $DB, $OUTPUT;
3549 $authsenabled = get_enabled_auth_plugins();
3551 if ($user = get_complete_user_data('username', $username)) {
3552 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
3553 if (!empty($user->suspended)) {
3554 add_to_log(0, 'login', 'error', 'index.php', $username);
3555 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3558 if ($auth=='nologin' or !is_enabled_auth($auth)) {
3559 add_to_log(0, 'login', 'error', 'index.php', $username);
3560 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3563 $auths = array($auth);
3566 // check if there's a deleted record (cheaply)
3567 if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
3568 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3572 $auths = $authsenabled;
3573 $user = new object();
3574 $user->id = 0; // User does not exist
3577 foreach ($auths as $auth) {
3578 $authplugin = get_auth_plugin($auth);
3580 // on auth fail fall through to the next plugin
3581 if (!$authplugin->user_login($username, $password)) {
3585 // successful authentication
3586 if ($user->id) { // User already exists in database
3587 if (empty($user->auth)) { // For some reason auth isn't set yet
3588 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
3589 $user->auth = $auth;
3591 if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3592 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
3593 $user->firstaccess = $user->timemodified;
3596 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3598 if (!$authplugin->is_internal()) { // update user record from external DB
3599 $user = update_user_record($username, get_auth_plugin($user->auth));
3602 // if user not found, create him
3603 $user = create_user_record($username, $password, $auth);
3606 $authplugin->sync_roles($user);
3608 foreach ($authsenabled as $hau) {
3609 $hauth = get_auth_plugin($hau);
3610 $hauth->user_authenticated_hook($user, $username, $password);
3613 if (empty($user->id)) {
3617 if (!empty($user->suspended)) {
3618 // just in case some auth plugin suspended account
3619 add_to_log(0, 'login', 'error', 'index.php', $username);
3620 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3627 // failed if all the plugins have failed
3628 add_to_log(0, 'login', 'error', 'index.php', $username);
3629 if (debugging('', DEBUG_ALL)) {
3630 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3636 * Call to complete the user login process after authenticate_user_login()
3637 * has succeeded. It will setup the $USER variable and other required bits
3641 * - It will NOT log anything -- up to the caller to decide what to log.
3646 * @param object $user
3647 * @param bool $setcookie
3648 * @return object A {@link $USER} object - BC only, do not use
3650 function complete_user_login($user, $setcookie=true) {
3651 global $CFG, $USER, $SESSION;
3653 // regenerate session id and delete old session,
3654 // this helps prevent session fixation attacks from the same domain
3655 session_regenerate_id(true);
3657 // check enrolments, load caps and setup $USER object
3658 session_set_user($user);
3660 update_user_login_times();
3661 set_login_session_preferences();
3664 if (empty($CFG->nolastloggedin)) {
3665 set_moodle_cookie($USER->username);
3667 // do not store last logged in user in cookie
3668 // auth plugins can temporarily override this from loginpage_hook()
3669 // do not save $CFG->nolastloggedin in database!
3670 set_moodle_cookie('nobody');
3674 /// Select password change url
3675 $userauth = get_auth_plugin($USER->auth);
3677 /// check whether the user should be changing password
3678 if (get_user_preferences('auth_forcepasswordchange', false)){
3679 if ($userauth->can_change_password()) {
3680 if ($changeurl = $userauth->change_password_url()) {
3681 redirect($changeurl);
3683 redirect($CFG->httpswwwroot.'/login/change_password.php');
3686 print_error('nopasswordchangeforced', 'auth');
3693 * Compare password against hash stored in internal user table.
3694 * If necessary it also updates the stored hash to new format.
3697 * @param object $user
3698 * @param string $password plain text password
3699 * @return bool is password valid?
3701 function validate_internal_user_password(&$user, $password) {
3704 if (!isset($CFG->passwordsaltmain)) {
3705 $CFG->passwordsaltmain = '';
3710 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)) {
3713 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
3714 $alt = 'passwordsaltalt'.$i;
3715 if (!empty($CFG->$alt)) {
3716 if ($user->password == md5($password.$CFG->$alt)) {