3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * moodlelib.php - Moodle main library
21 * Main library file of miscellaneous general-purpose Moodle functions.
22 * Other main libraries:
23 * - weblib.php - functions that produce web output
24 * - datalib.php - functions that access the database
28 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32 defined('MOODLE_INTERNAL') || die();
34 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
36 /// Date and time constants ///
38 * Time constant - the number of seconds in a year
40 define('YEARSECS', 31536000);
43 * Time constant - the number of seconds in a week
45 define('WEEKSECS', 604800);
48 * Time constant - the number of seconds in a day
50 define('DAYSECS', 86400);
53 * Time constant - the number of seconds in an hour
55 define('HOURSECS', 3600);
58 * Time constant - the number of seconds in a minute
60 define('MINSECS', 60);
63 * Time constant - the number of minutes in a day
65 define('DAYMINS', 1440);
68 * Time constant - the number of minutes in an hour
70 define('HOURMINS', 60);
72 /// Parameter constants - every call to optional_param(), required_param() ///
73 /// or clean_param() should have a specified type of parameter. //////////////
78 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
80 define('PARAM_ALPHA', 'alpha');
83 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
84 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
86 define('PARAM_ALPHAEXT', 'alphaext');
89 * PARAM_ALPHANUM - expected numbers and letters only.
91 define('PARAM_ALPHANUM', 'alphanum');
94 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
96 define('PARAM_ALPHANUMEXT', 'alphanumext');
99 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
101 define('PARAM_AUTH', 'auth');
104 * PARAM_BASE64 - Base 64 encoded format
106 define('PARAM_BASE64', 'base64');
109 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
111 define('PARAM_BOOL', 'bool');
114 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
115 * checked against the list of capabilities in the database.
117 define('PARAM_CAPABILITY', 'capability');
120 * PARAM_CLEANHTML - cleans submitted HTML code. use only for text in HTML format. This cleaning may fix xhtml strictness too.
122 define('PARAM_CLEANHTML', 'cleanhtml');
125 * PARAM_EMAIL - an email address following the RFC
127 define('PARAM_EMAIL', 'email');
130 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
132 define('PARAM_FILE', 'file');
135 * PARAM_FLOAT - a real/floating point number.
137 define('PARAM_FLOAT', 'float');
140 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
142 define('PARAM_HOST', 'host');
145 * PARAM_INT - integers only, use when expecting only numbers.
147 define('PARAM_INT', 'int');
150 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
152 define('PARAM_LANG', 'lang');
155 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
157 define('PARAM_LOCALURL', 'localurl');
160 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
162 define('PARAM_NOTAGS', 'notags');
165 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
166 * note: the leading slash is not removed, window drive letter is not allowed
168 define('PARAM_PATH', 'path');
171 * PARAM_PEM - Privacy Enhanced Mail format
173 define('PARAM_PEM', 'pem');
176 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
178 define('PARAM_PERMISSION', 'permission');
181 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way
183 define('PARAM_RAW', 'raw');
186 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
188 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
191 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
193 define('PARAM_SAFEDIR', 'safedir');
196 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
198 define('PARAM_SAFEPATH', 'safepath');
201 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
203 define('PARAM_SEQUENCE', 'sequence');
206 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
208 define('PARAM_TAG', 'tag');
211 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
213 define('PARAM_TAGLIST', 'taglist');
216 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
218 define('PARAM_TEXT', 'text');
221 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
223 define('PARAM_THEME', 'theme');
226 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
228 define('PARAM_URL', 'url');
231 * 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!!
233 define('PARAM_USERNAME', 'username');
236 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
238 define('PARAM_STRINGID', 'stringid');
240 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
242 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
243 * It was one of the first types, that is why it is abused so much ;-)
244 * @deprecated since 2.0
246 define('PARAM_CLEAN', 'clean');
249 * PARAM_INTEGER - deprecated alias for PARAM_INT
251 define('PARAM_INTEGER', 'int');
254 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
256 define('PARAM_NUMBER', 'float');
259 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
260 * NOTE: originally alias for PARAM_APLHA
262 define('PARAM_ACTION', 'alphanumext');
265 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
266 * NOTE: originally alias for PARAM_APLHA
268 define('PARAM_FORMAT', 'alphanumext');
271 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
273 define('PARAM_MULTILANG', 'text');
276 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
278 define('PARAM_CLEANFILE', 'file');
283 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
285 define('VALUE_REQUIRED', 1);
288 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
290 define('VALUE_OPTIONAL', 2);
293 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
295 define('VALUE_DEFAULT', 0);
298 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
300 define('NULL_NOT_ALLOWED', false);
303 * NULL_ALLOWED - the parameter can be set to null in the database
305 define('NULL_ALLOWED', true);
309 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
311 define('PAGE_COURSE_VIEW', 'course-view');
313 /** Get remote addr constant */
314 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
315 /** Get remote addr constant */
316 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
318 /// Blog access level constant declaration ///
319 define ('BLOG_USER_LEVEL', 1);
320 define ('BLOG_GROUP_LEVEL', 2);
321 define ('BLOG_COURSE_LEVEL', 3);
322 define ('BLOG_SITE_LEVEL', 4);
323 define ('BLOG_GLOBAL_LEVEL', 5);
328 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
329 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
330 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
332 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
334 define('TAG_MAX_LENGTH', 50);
336 /// Password policy constants ///
337 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
338 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
339 define ('PASSWORD_DIGITS', '0123456789');
340 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
342 /// Feature constants ///
343 // Used for plugin_supports() to report features that are, or are not, supported by a module.
345 /** True if module can provide a grade */
346 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
347 /** True if module supports outcomes */
348 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
350 /** True if module has code to track whether somebody viewed it */
351 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
352 /** True if module has custom completion rules */
353 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
355 /** True if module supports outcomes */
356 define('FEATURE_IDNUMBER', 'idnumber');
357 /** True if module supports groups */
358 define('FEATURE_GROUPS', 'groups');
359 /** True if module supports groupings */
360 define('FEATURE_GROUPINGS', 'groupings');
361 /** True if module supports groupmembersonly */
362 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
364 /** Type of module */
365 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
366 /** True if module supports intro editor */
367 define('FEATURE_MOD_INTRO', 'mod_intro');
368 /** True if module has default completion */
369 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
371 define('FEATURE_COMMENT', 'comment');
373 define('FEATURE_RATE', 'rate');
374 /** True if module supports backup/restore of moodle2 format */
375 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
377 /** Unspecified module archetype */
378 define('MOD_ARCHETYPE_OTHER', 0);
379 /** Resource-like type module */
380 define('MOD_ARCHETYPE_RESOURCE', 1);
381 /** Assignment module archetype */
382 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
385 * Security token used for allowing access
386 * from external application such as web services.
387 * Scripts do not use any session, performance is relatively
388 * low because we need to load access info in each request.
389 * Scripts are executed in parallel.
391 define('EXTERNAL_TOKEN_PERMANENT', 0);
394 * Security token used for allowing access
395 * of embedded applications, the code is executed in the
396 * active user session. Token is invalidated after user logs out.
397 * Scripts are executed serially - normal session locking is used.
399 define('EXTERNAL_TOKEN_EMBEDDED', 1);
402 * The home page should be the site home
404 define('HOMEPAGE_SITE', 0);
406 * The home page should be the users my page
408 define('HOMEPAGE_MY', 1);
410 * The home page can be chosen by the user
412 define('HOMEPAGE_USER', 2);
415 * Hub directory url (should be moodle.org)
417 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
421 * Moodle.org url (should be moodle.org)
423 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
426 /// PARAMETER HANDLING ////////////////////////////////////////////////////
429 * Returns a particular value for the named variable, taken from
430 * POST or GET. If the parameter doesn't exist then an error is
431 * thrown because we require this variable.
433 * This function should be used to initialise all required values
434 * in a script that are based on parameters. Usually it will be
436 * $id = required_param('id', PARAM_INT);
438 * Please note the $type parameter is now required,
439 * for now PARAM_CLEAN is used for backwards compatibility only.
441 * @param string $parname the name of the page parameter we want
442 * @param string $type expected type of parameter
445 function required_param($parname, $type) {
447 debugging('required_param() requires $type to be specified.');
448 $type = PARAM_CLEAN; // for now let's use this deprecated type
450 if (isset($_POST[$parname])) { // POST has precedence
451 $param = $_POST[$parname];
452 } else if (isset($_GET[$parname])) {
453 $param = $_GET[$parname];
455 print_error('missingparam', '', '', $parname);
458 return clean_param($param, $type);
462 * Returns a particular value for the named variable, taken from
463 * POST or GET, otherwise returning a given default.
465 * This function should be used to initialise all optional values
466 * in a script that are based on parameters. Usually it will be
468 * $name = optional_param('name', 'Fred', PARAM_TEXT);
470 * Please note $default and $type parameters are now required,
471 * for now PARAM_CLEAN is used for backwards compatibility only.
473 * @param string $parname the name of the page parameter we want
474 * @param mixed $default the default value to return if nothing is found
475 * @param string $type expected type of parameter
478 function optional_param($parname, $default, $type) {
480 debugging('optional_param() requires $default and $type to be specified.');
481 $type = PARAM_CLEAN; // for now let's use this deprecated type
483 if (!isset($default)) {
487 if (isset($_POST[$parname])) { // POST has precedence
488 $param = $_POST[$parname];
489 } else if (isset($_GET[$parname])) {
490 $param = $_GET[$parname];
495 return clean_param($param, $type);
499 * Strict validation of parameter values, the values are only converted
500 * to requested PHP type. Internally it is using clean_param, the values
501 * before and after cleaning must be equal - otherwise
502 * an invalid_parameter_exception is thrown.
503 * Objects and classes are not accepted.
505 * @param mixed $param
506 * @param int $type PARAM_ constant
507 * @param bool $allownull are nulls valid value?
508 * @param string $debuginfo optional debug information
509 * @return mixed the $param value converted to PHP type or invalid_parameter_exception
511 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
512 if (is_null($param)) {
513 if ($allownull == NULL_ALLOWED) {
516 throw new invalid_parameter_exception($debuginfo);
519 if (is_array($param) or is_object($param)) {
520 throw new invalid_parameter_exception($debuginfo);
523 $cleaned = clean_param($param, $type);
524 if ((string)$param !== (string)$cleaned) {
525 // conversion to string is usually lossless
526 throw new invalid_parameter_exception($debuginfo);
533 * Used by {@link optional_param()} and {@link required_param()} to
534 * clean the variables and/or cast to specific types, based on
537 * $course->format = clean_param($course->format, PARAM_ALPHA);
538 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
541 * @param mixed $param the variable we are cleaning
542 * @param int $type expected format of param after cleaning.
545 function clean_param($param, $type) {
549 if (is_array($param)) { // Let's loop
551 foreach ($param as $key => $value) {
552 $newparam[$key] = clean_param($value, $type);
558 case PARAM_RAW: // no cleaning at all
561 case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
564 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
565 // this is deprecated!, please use more specific type instead
566 if (is_numeric($param)) {
569 return clean_text($param); // Sweep for scripts, etc
571 case PARAM_CLEANHTML: // clean html fragment
572 $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
576 return (int)$param; // Convert to integer
580 return (float)$param; // Convert to float
582 case PARAM_ALPHA: // Remove everything not a-z
583 return preg_replace('/[^a-zA-Z]/i', '', $param);
585 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
586 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
588 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
589 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
591 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
592 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
594 case PARAM_SEQUENCE: // Remove everything not 0-9,
595 return preg_replace('/[^0-9,]/i', '', $param);
597 case PARAM_BOOL: // Convert to 1 or 0
598 $tempstr = strtolower($param);
599 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
601 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
604 $param = empty($param) ? 0 : 1;
608 case PARAM_NOTAGS: // Strip all tags
609 return strip_tags($param);
611 case PARAM_TEXT: // leave only tags needed for multilang
612 // if the multilang syntax is not correct we strip all tags
613 // because it would break xhtml strict which is required for accessibility standards
614 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
616 if (strpos($param, '</lang>') !== false) {
617 // old and future mutilang syntax
618 $param = strip_tags($param, '<lang>');
619 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
623 foreach ($matches[0] as $match) {
624 if ($match === '</lang>') {
632 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
643 } else if (strpos($param, '</span>') !== false) {
644 // current problematic multilang syntax
645 $param = strip_tags($param, '<span>');
646 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
650 foreach ($matches[0] as $match) {
651 if ($match === '</span>') {
659 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
671 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
672 return strip_tags($param);
674 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
675 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
677 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
678 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
680 case PARAM_FILE: // Strip all suspicious characters from filename
681 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
682 $param = preg_replace('~\.\.+~', '', $param);
683 if ($param === '.') {
688 case PARAM_PATH: // Strip all suspicious characters from file path
689 $param = str_replace('\\', '/', $param);
690 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
691 $param = preg_replace('~\.\.+~', '', $param);
692 $param = preg_replace('~//+~', '/', $param);
693 return preg_replace('~/(\./)+~', '/', $param);
695 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
696 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
697 // match ipv4 dotted quad
698 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
699 // confirm values are ok
703 || $match[4] > 255 ) {
704 // hmmm, what kind of dotted quad is this?
707 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
708 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
709 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
711 // all is ok - $param is respected
718 case PARAM_URL: // allow safe ftp, http, mailto urls
719 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
720 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
721 // all is ok, param is respected
723 $param =''; // not really ok
727 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
728 $param = clean_param($param, PARAM_URL);
729 if (!empty($param)) {
730 if (preg_match(':^/:', $param)) {
731 // root-relative, ok!
732 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
733 // absolute, and matches our wwwroot
735 // relative - let's make sure there are no tricks
736 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
746 $param = trim($param);
747 // PEM formatted strings may contain letters/numbers and the symbols
751 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
752 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
753 list($wholething, $body) = $matches;
754 unset($wholething, $matches);
755 $b64 = clean_param($body, PARAM_BASE64);
757 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
765 if (!empty($param)) {
766 // PEM formatted strings may contain letters/numbers and the symbols
770 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
773 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
774 // Each line of base64 encoded data must be 64 characters in
775 // length, except for the last line which may be less than (or
776 // equal to) 64 characters long.
777 for ($i=0, $j=count($lines); $i < $j; $i++) {
779 if (64 < strlen($lines[$i])) {
785 if (64 != strlen($lines[$i])) {
789 return implode("\n",$lines);
795 // Please note it is not safe to use the tag name directly anywhere,
796 // it must be processed with s(), urlencode() before embedding anywhere.
797 // remove some nasties
798 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
799 //convert many whitespace chars into one
800 $param = preg_replace('/\s+/', ' ', $param);
801 $textlib = textlib_get_instance();
802 $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
806 $tags = explode(',', $param);
808 foreach ($tags as $tag) {
809 $res = clean_param($tag, PARAM_TAG);
815 return implode(',', $result);
820 case PARAM_CAPABILITY:
821 if (get_capability_info($param)) {
827 case PARAM_PERMISSION:
828 $param = (int)$param;
829 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
836 $param = clean_param($param, PARAM_SAFEDIR);
837 if (exists_auth_plugin($param)) {
844 $param = clean_param($param, PARAM_SAFEDIR);
845 if (get_string_manager()->translation_exists($param)) {
848 return ''; // Specified language is not installed or param malformed
852 $param = clean_param($param, PARAM_SAFEDIR);
853 if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
855 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
858 return ''; // Specified theme is not installed
862 $param = str_replace(" " , "", $param);
863 $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
864 if (empty($CFG->extendedusernamechars)) {
865 // regular expression, eliminate all chars EXCEPT:
866 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
867 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
872 if (validate_email($param)) {
879 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
885 default: // throw error, switched parameters in optional_param or another serious problem
886 print_error("unknownparamtype", '', '', $type);
891 * Return true if given value is integer or string with integer value
893 * @param mixed $value String or Int
894 * @return bool true if number, false if not
896 function is_number($value) {
897 if (is_int($value)) {
899 } else if (is_string($value)) {
900 return ((string)(int)$value) === $value;
907 * Returns host part from url
908 * @param string $url full url
909 * @return string host, null if not found
911 function get_host_from_url($url) {
912 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
920 * Tests whether anything was returned by text editor
922 * This function is useful for testing whether something you got back from
923 * the HTML editor actually contains anything. Sometimes the HTML editor
924 * appear to be empty, but actually you get back a <br> tag or something.
926 * @param string $string a string containing HTML.
927 * @return boolean does the string contain any actual content - that is text,
928 * images, objects, etc.
930 function html_is_blank($string) {
931 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
935 * Set a key in global configuration
937 * Set a key/value pair in both this session's {@link $CFG} global variable
938 * and in the 'config' database table for future sessions.
940 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
941 * In that case it doesn't affect $CFG.
943 * A NULL value will delete the entry.
947 * @param string $name the key to set
948 * @param string $value the value to set (without magic quotes)
949 * @param string $plugin (optional) the plugin scope, default NULL
950 * @return bool true or exception
952 function set_config($name, $value, $plugin=NULL) {
955 if (empty($plugin)) {
956 if (!array_key_exists($name, $CFG->config_php_settings)) {
957 // So it's defined for this invocation at least
958 if (is_null($value)) {
961 $CFG->$name = (string)$value; // settings from db are always strings
965 if ($DB->get_field('config', 'name', array('name'=>$name))) {
966 if ($value === null) {
967 $DB->delete_records('config', array('name'=>$name));
969 $DB->set_field('config', 'value', $value, array('name'=>$name));
972 if ($value !== null) {
973 $config = new stdClass();
974 $config->name = $name;
975 $config->value = $value;
976 $DB->insert_record('config', $config, false);
980 } else { // plugin scope
981 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
983 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
985 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
988 if ($value !== null) {
989 $config = new stdClass();
990 $config->plugin = $plugin;
991 $config->name = $name;
992 $config->value = $value;
993 $DB->insert_record('config_plugins', $config, false);
1002 * Get configuration values from the global config table
1003 * or the config_plugins table.
1005 * If called with one parameter, it will load all the config
1006 * variables for one plugin, and return them as an object.
1008 * If called with 2 parameters it will return a string single
1009 * value or false if the value is not found.
1011 * @param string $plugin full component name
1012 * @param string $name default NULL
1013 * @return mixed hash-like object or single value, return false no config found
1015 function get_config($plugin, $name = NULL) {
1018 // normalise component name
1019 if ($plugin === 'moodle' or $plugin === 'core') {
1023 if (!empty($name)) { // the user is asking for a specific value
1024 if (!empty($plugin)) {
1025 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1026 // setting forced in config file
1027 return $CFG->forced_plugin_settings[$plugin][$name];
1029 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1032 if (array_key_exists($name, $CFG->config_php_settings)) {
1033 // setting force in config file
1034 return $CFG->config_php_settings[$name];
1036 return $DB->get_field('config', 'value', array('name'=>$name));
1041 // the user is after a recordset
1043 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1044 if (isset($CFG->forced_plugin_settings[$plugin])) {
1045 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1046 if (is_null($v) or is_array($v) or is_object($v)) {
1047 // we do not want any extra mess here, just real settings that could be saved in db
1048 unset($localcfg[$n]);
1050 //convert to string as if it went through the DB
1051 $localcfg[$n] = (string)$v;
1056 return (object)$localcfg;
1062 // this part is not really used any more, but anyway...
1063 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1064 foreach($CFG->config_php_settings as $n=>$v) {
1065 if (is_null($v) or is_array($v) or is_object($v)) {
1066 // we do not want any extra mess here, just real settings that could be saved in db
1067 unset($localcfg[$n]);
1069 //convert to string as if it went through the DB
1070 $localcfg[$n] = (string)$v;
1073 return (object)$localcfg;
1078 * Removes a key from global configuration
1080 * @param string $name the key to set
1081 * @param string $plugin (optional) the plugin scope
1083 * @return boolean whether the operation succeeded.
1085 function unset_config($name, $plugin=NULL) {
1088 if (empty($plugin)) {
1090 $DB->delete_records('config', array('name'=>$name));
1092 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1099 * Remove all the config variables for a given plugin.
1101 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1102 * @return boolean whether the operation succeeded.
1104 function unset_all_config_for_plugin($plugin) {
1106 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1107 $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
1112 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1114 * All users are verified if they still have the necessary capability.
1116 * @param string $value the value of the config setting.
1117 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1118 * @param bool $include admins, include administrators
1119 * @return array of user objects.
1121 function get_users_from_config($value, $capability, $includeadmins = true) {
1124 if (empty($value) or $value === '$@NONE@$') {
1128 // we have to make sure that users still have the necessary capability,
1129 // it should be faster to fetch them all first and then test if they are present
1130 // instead of validating them one-by-one
1131 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1132 if ($includeadmins) {
1133 $admins = get_admins();
1134 foreach ($admins as $admin) {
1135 $users[$admin->id] = $admin;
1139 if ($value === '$@ALL@$') {
1143 $result = array(); // result in correct order
1144 $allowed = explode(',', $value);
1145 foreach ($allowed as $uid) {
1146 if (isset($users[$uid])) {
1147 $user = $users[$uid];
1148 $result[$user->id] = $user;
1157 * Invalidates browser caches and cached data in temp
1160 function purge_all_caches() {
1163 reset_text_filters_cache();
1164 js_reset_all_caches();
1165 theme_reset_all_caches();
1166 get_string_manager()->reset_caches();
1168 // purge all other caches: rss, simplepie, etc.
1169 remove_dir($CFG->dataroot.'/cache', true);
1171 // make sure cache dir is writable, throws exception if not
1172 make_upload_directory('cache');
1178 * Get volatile flags
1180 * @param string $type
1181 * @param int $changedsince default null
1182 * @return records array
1184 function get_cache_flags($type, $changedsince=NULL) {
1187 $params = array('type'=>$type, 'expiry'=>time());
1188 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1189 if ($changedsince !== NULL) {
1190 $params['changedsince'] = $changedsince;
1191 $sqlwhere .= " AND timemodified > :changedsince";
1195 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1196 foreach ($flags as $flag) {
1197 $cf[$flag->name] = $flag->value;
1204 * Get volatile flags
1206 * @param string $type
1207 * @param string $name
1208 * @param int $changedsince default null
1209 * @return records array
1211 function get_cache_flag($type, $name, $changedsince=NULL) {
1214 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1216 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1217 if ($changedsince !== NULL) {
1218 $params['changedsince'] = $changedsince;
1219 $sqlwhere .= " AND timemodified > :changedsince";
1222 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1226 * Set a volatile flag
1228 * @param string $type the "type" namespace for the key
1229 * @param string $name the key to set
1230 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1231 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1232 * @return bool Always returns true
1234 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1237 $timemodified = time();
1238 if ($expiry===NULL || $expiry < $timemodified) {
1239 $expiry = $timemodified + 24 * 60 * 60;
1241 $expiry = (int)$expiry;
1244 if ($value === NULL) {
1245 unset_cache_flag($type,$name);
1249 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1250 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1251 return true; //no need to update; helps rcache too
1254 $f->expiry = $expiry;
1255 $f->timemodified = $timemodified;
1256 $DB->update_record('cache_flags', $f);
1258 $f = new stdClass();
1259 $f->flagtype = $type;
1262 $f->expiry = $expiry;
1263 $f->timemodified = $timemodified;
1264 $DB->insert_record('cache_flags', $f);
1270 * Removes a single volatile flag
1273 * @param string $type the "type" namespace for the key
1274 * @param string $name the key to set
1277 function unset_cache_flag($type, $name) {
1279 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1284 * Garbage-collect volatile flags
1286 * @return bool Always returns true
1288 function gc_cache_flags() {
1290 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1294 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1297 * Refresh user preference cache. This is used most often for $USER
1298 * object that is stored in session, but it also helps with performance in cron script.
1300 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1302 * @param stdClass $user user object, preferences are preloaded into ->preference property
1303 * @param int $cachelifetime cache life time on the current page (ins seconds)
1306 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1308 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1310 if (!isset($user->id)) {
1311 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1314 if (empty($user->id) or isguestuser($user->id)) {
1315 // No permanent storage for not-logged-in users and guest
1316 if (!isset($user->preference)) {
1317 $user->preference = array();
1324 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1325 // Already loaded at least once on this page. Are we up to date?
1326 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1327 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1330 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1331 // no change since the lastcheck on this page
1332 $user->preference['_lastloaded'] = $timenow;
1337 // OK, so we have to reload all preferences
1338 $loadedusers[$user->id] = true;
1339 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1340 $user->preference['_lastloaded'] = $timenow;
1344 * Called from set/delete_user_preferences, so that the prefs can
1345 * be correctly reloaded in different sessions.
1347 * NOTE: internal function, do not call from other code.
1349 * @param integer $userid the user whose prefs were changed.
1352 function mark_user_preferences_changed($userid) {
1355 if (empty($userid) or isguestuser($userid)) {
1356 // no cache flags for guest and not-logged-in users
1360 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1364 * Sets a preference for the specified user.
1366 * If user object submitted, 'preference' property contains the preferences cache.
1368 * @param string $name The key to set as preference for the specified user
1369 * @param string $value The value to set for the $name key in the specified user's record,
1370 * null means delete current value
1371 * @param stdClass|int $user A moodle user object or id, null means current user
1372 * @return bool always true or exception
1374 function set_user_preference($name, $value, $user = null) {
1377 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1378 throw new coding_exception('Invalid preference name in set_user_preference() call');
1381 if (is_null($value)) {
1382 // null means delete current
1383 return unset_user_preference($name, $user);
1384 } else if (is_object($value)) {
1385 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1386 } else if (is_array($value)) {
1387 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1389 $value = (string)$value;
1391 if (is_null($user)) {
1393 } else if (isset($user->id)) {
1394 // $user is valid object
1395 } else if (is_numeric($user)) {
1396 $user = (object)array('id'=>(int)$user);
1398 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1401 check_user_preferences_loaded($user);
1403 if (empty($user->id) or isguestuser($user->id)) {
1404 // no permanent storage for not-logged-in users and guest
1405 $user->preference[$name] = $value;
1409 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1410 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1411 // preference already set to this value
1414 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1417 $preference = new stdClass();
1418 $preference->userid = $user->id;
1419 $preference->name = $name;
1420 $preference->value = $value;
1421 $DB->insert_record('user_preferences', $preference);
1424 // update value in cache
1425 $user->preference[$name] = $value;
1427 // set reload flag for other sessions
1428 mark_user_preferences_changed($user->id);
1434 * Sets a whole array of preferences for the current user
1436 * If user object submitted, 'preference' property contains the preferences cache.
1438 * @param array $prefarray An array of key/value pairs to be set
1439 * @param stdClass|int $user A moodle user object or id, null means current user
1440 * @return bool always true or exception
1442 function set_user_preferences(array $prefarray, $user = null) {
1443 foreach ($prefarray as $name => $value) {
1444 set_user_preference($name, $value, $user);
1450 * Unsets a preference completely by deleting it from the database
1452 * If user object submitted, 'preference' property contains the preferences cache.
1454 * @param string $name The key to unset as preference for the specified user
1455 * @param stdClass|int $user A moodle user object or id, null means current user
1456 * @return bool always true or exception
1458 function unset_user_preference($name, $user = null) {
1461 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1462 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1465 if (is_null($user)) {
1467 } else if (isset($user->id)) {
1468 // $user is valid object
1469 } else if (is_numeric($user)) {
1470 $user = (object)array('id'=>(int)$user);
1472 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1475 check_user_preferences_loaded($user);
1477 if (empty($user->id) or isguestuser($user->id)) {
1478 // no permanent storage for not-logged-in user and guest
1479 unset($user->preference[$name]);
1484 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1486 // delete the preference from cache
1487 unset($user->preference[$name]);
1489 // set reload flag for other sessions
1490 mark_user_preferences_changed($user->id);
1496 * Used to fetch user preference(s)
1498 * If no arguments are supplied this function will return
1499 * all of the current user preferences as an array.
1501 * If a name is specified then this function
1502 * attempts to return that particular preference value. If
1503 * none is found, then the optional value $default is returned,
1506 * If user object submitted, 'preference' property contains the preferences cache.
1508 * @param string $name Name of the key to use in finding a preference value
1509 * @param mixed $default Value to be returned if the $name key is not set in the user preferences
1510 * @param stdClass|int $user A moodle user object or id, null means current user
1511 * @return mixed string value or default
1513 function get_user_preferences($name = null, $default = null, $user = null) {
1516 if (is_null($name)) {
1518 } else if (is_numeric($name) or $name === '_lastloaded') {
1519 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1522 if (is_null($user)) {
1524 } else if (isset($user->id)) {
1525 // $user is valid object
1526 } else if (is_numeric($user)) {
1527 $user = (object)array('id'=>(int)$user);
1529 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1532 check_user_preferences_loaded($user);
1535 return $user->preference; // All values
1536 } else if (isset($user->preference[$name])) {
1537 return $user->preference[$name]; // The single string value
1539 return $default; // Default value (null if not specified)
1543 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1546 * Given date parts in user time produce a GMT timestamp.
1548 * @todo Finish documenting this function
1549 * @param int $year The year part to create timestamp of
1550 * @param int $month The month part to create timestamp of
1551 * @param int $day The day part to create timestamp of
1552 * @param int $hour The hour part to create timestamp of
1553 * @param int $minute The minute part to create timestamp of
1554 * @param int $second The second part to create timestamp of
1555 * @param float $timezone Timezone modifier
1556 * @param bool $applydst Toggle Daylight Saving Time, default true
1557 * @return int timestamp
1559 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1561 $strtimezone = NULL;
1562 if (!is_numeric($timezone)) {
1563 $strtimezone = $timezone;
1566 $timezone = get_user_timezone_offset($timezone);
1568 if (abs($timezone) > 13) {
1569 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1571 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1572 $time = usertime($time, $timezone);
1574 $time -= dst_offset_on($time, $strtimezone);
1583 * Format a date/time (seconds) as weeks, days, hours etc as needed
1585 * Given an amount of time in seconds, returns string
1586 * formatted nicely as weeks, days, hours etc as needed
1592 * @param int $totalsecs Time in seconds
1593 * @param object $str Should be a time object
1594 * @return string A nicely formatted date/time string
1596 function format_time($totalsecs, $str=NULL) {
1598 $totalsecs = abs($totalsecs);
1600 if (!$str) { // Create the str structure the slow way
1601 $str->day = get_string('day');
1602 $str->days = get_string('days');
1603 $str->hour = get_string('hour');
1604 $str->hours = get_string('hours');
1605 $str->min = get_string('min');
1606 $str->mins = get_string('mins');
1607 $str->sec = get_string('sec');
1608 $str->secs = get_string('secs');
1609 $str->year = get_string('year');
1610 $str->years = get_string('years');
1614 $years = floor($totalsecs/YEARSECS);
1615 $remainder = $totalsecs - ($years*YEARSECS);
1616 $days = floor($remainder/DAYSECS);
1617 $remainder = $totalsecs - ($days*DAYSECS);
1618 $hours = floor($remainder/HOURSECS);
1619 $remainder = $remainder - ($hours*HOURSECS);
1620 $mins = floor($remainder/MINSECS);
1621 $secs = $remainder - ($mins*MINSECS);
1623 $ss = ($secs == 1) ? $str->sec : $str->secs;
1624 $sm = ($mins == 1) ? $str->min : $str->mins;
1625 $sh = ($hours == 1) ? $str->hour : $str->hours;
1626 $sd = ($days == 1) ? $str->day : $str->days;
1627 $sy = ($years == 1) ? $str->year : $str->years;
1635 if ($years) $oyears = $years .' '. $sy;
1636 if ($days) $odays = $days .' '. $sd;
1637 if ($hours) $ohours = $hours .' '. $sh;
1638 if ($mins) $omins = $mins .' '. $sm;
1639 if ($secs) $osecs = $secs .' '. $ss;
1641 if ($years) return trim($oyears .' '. $odays);
1642 if ($days) return trim($odays .' '. $ohours);
1643 if ($hours) return trim($ohours .' '. $omins);
1644 if ($mins) return trim($omins .' '. $osecs);
1645 if ($secs) return $osecs;
1646 return get_string('now');
1650 * Returns a formatted string that represents a date in user time
1652 * Returns a formatted string that represents a date in user time
1653 * <b>WARNING: note that the format is for strftime(), not date().</b>
1654 * Because of a bug in most Windows time libraries, we can't use
1655 * the nicer %e, so we have to use %d which has leading zeroes.
1656 * A lot of the fuss in the function is just getting rid of these leading
1657 * zeroes as efficiently as possible.
1659 * If parameter fixday = true (default), then take off leading
1660 * zero from %d, else maintain it.
1662 * @param int $date the timestamp in UTC, as obtained from the database.
1663 * @param string $format strftime format. You should probably get this using
1664 * get_string('strftime...', 'langconfig');
1665 * @param float $timezone by default, uses the user's time zone.
1666 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1667 * If false then the leading zero is maintained.
1668 * @return string the formatted date/time.
1670 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1674 $strtimezone = NULL;
1675 if (!is_numeric($timezone)) {
1676 $strtimezone = $timezone;
1679 if (empty($format)) {
1680 $format = get_string('strftimedaydatetime', 'langconfig');
1683 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1685 } else if ($fixday) {
1686 $formatnoday = str_replace('%d', 'DD', $format);
1687 $fixday = ($formatnoday != $format);
1690 $date += dst_offset_on($date, $strtimezone);
1692 $timezone = get_user_timezone_offset($timezone);
1694 if (abs($timezone) > 13) { /// Server time
1696 $datestring = strftime($formatnoday, $date);
1697 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
1698 $datestring = str_replace('DD', $daystring, $datestring);
1700 $datestring = strftime($format, $date);
1703 $date += (int)($timezone * 3600);
1705 $datestring = gmstrftime($formatnoday, $date);
1706 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
1707 $datestring = str_replace('DD', $daystring, $datestring);
1709 $datestring = gmstrftime($format, $date);
1713 /// If we are running under Windows convert from windows encoding to UTF-8
1714 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1716 if ($CFG->ostype == 'WINDOWS') {
1717 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1718 $textlib = textlib_get_instance();
1719 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1727 * Given a $time timestamp in GMT (seconds since epoch),
1728 * returns an array that represents the date in user time
1730 * @todo Finish documenting this function
1732 * @param int $time Timestamp in GMT
1733 * @param float $timezone ?
1734 * @return array An array that represents the date in user time
1736 function usergetdate($time, $timezone=99) {
1738 $strtimezone = NULL;
1739 if (!is_numeric($timezone)) {
1740 $strtimezone = $timezone;
1743 $timezone = get_user_timezone_offset($timezone);
1745 if (abs($timezone) > 13) { // Server time
1746 return getdate($time);
1749 // There is no gmgetdate so we use gmdate instead
1750 $time += dst_offset_on($time, $strtimezone);
1751 $time += intval((float)$timezone * HOURSECS);
1753 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
1755 //be careful to ensure the returned array matches that produced by getdate() above
1758 $getdate['weekday'],
1765 $getdate['minutes'],
1767 ) = explode('_', $datestring);
1773 * Given a GMT timestamp (seconds since epoch), offsets it by
1774 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1777 * @param int $date Timestamp in GMT
1778 * @param float $timezone
1781 function usertime($date, $timezone=99) {
1783 $timezone = get_user_timezone_offset($timezone);
1785 if (abs($timezone) > 13) {
1788 return $date - (int)($timezone * HOURSECS);
1792 * Given a time, return the GMT timestamp of the most recent midnight
1793 * for the current user.
1795 * @param int $date Timestamp in GMT
1796 * @param float $timezone Defaults to user's timezone
1797 * @return int Returns a GMT timestamp
1799 function usergetmidnight($date, $timezone=99) {
1801 $userdate = usergetdate($date, $timezone);
1803 // Time of midnight of this user's day, in GMT
1804 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1809 * Returns a string that prints the user's timezone
1811 * @param float $timezone The user's timezone
1814 function usertimezone($timezone=99) {
1816 $tz = get_user_timezone($timezone);
1818 if (!is_float($tz)) {
1822 if(abs($tz) > 13) { // Server time
1823 return get_string('serverlocaltime');
1826 if($tz == intval($tz)) {
1827 // Don't show .0 for whole hours
1844 * Returns a float which represents the user's timezone difference from GMT in hours
1845 * Checks various settings and picks the most dominant of those which have a value
1849 * @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
1852 function get_user_timezone_offset($tz = 99) {
1856 $tz = get_user_timezone($tz);
1858 if (is_float($tz)) {
1861 $tzrecord = get_timezone_record($tz);
1862 if (empty($tzrecord)) {
1865 return (float)$tzrecord->gmtoff / HOURMINS;
1870 * Returns an int which represents the systems's timezone difference from GMT in seconds
1873 * @param mixed $tz timezone
1874 * @return int if found, false is timezone 99 or error
1876 function get_timezone_offset($tz) {
1883 if (is_numeric($tz)) {
1884 return intval($tz * 60*60);
1887 if (!$tzrecord = get_timezone_record($tz)) {
1890 return intval($tzrecord->gmtoff * 60);
1894 * Returns a float or a string which denotes the user's timezone
1895 * 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)
1896 * means that for this timezone there are also DST rules to be taken into account
1897 * Checks various settings and picks the most dominant of those which have a value
1901 * @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
1904 function get_user_timezone($tz = 99) {
1909 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1910 isset($USER->timezone) ? $USER->timezone : 99,
1911 isset($CFG->timezone) ? $CFG->timezone : 99,
1916 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
1917 $tz = $next['value'];
1920 return is_numeric($tz) ? (float) $tz : $tz;
1924 * Returns cached timezone record for given $timezonename
1928 * @param string $timezonename
1929 * @return mixed timezonerecord object or false
1931 function get_timezone_record($timezonename) {
1933 static $cache = NULL;
1935 if ($cache === NULL) {
1939 if (isset($cache[$timezonename])) {
1940 return $cache[$timezonename];
1943 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
1944 WHERE name = ? ORDER BY year DESC', array($timezonename), true);
1948 * Build and store the users Daylight Saving Time (DST) table
1953 * @param mixed $from_year Start year for the table, defaults to 1971
1954 * @param mixed $to_year End year for the table, defaults to 2035
1955 * @param mixed $strtimezone
1958 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
1959 global $CFG, $SESSION, $DB;
1961 $usertz = get_user_timezone($strtimezone);
1963 if (is_float($usertz)) {
1964 // Trivial timezone, no DST
1968 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1969 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1970 unset($SESSION->dst_offsets);
1971 unset($SESSION->dst_range);
1974 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1975 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1976 // This will be the return path most of the time, pretty light computationally
1980 // Reaching here means we either need to extend our table or create it from scratch
1982 // Remember which TZ we calculated these changes for
1983 $SESSION->dst_offsettz = $usertz;
1985 if(empty($SESSION->dst_offsets)) {
1986 // If we 're creating from scratch, put the two guard elements in there
1987 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1989 if(empty($SESSION->dst_range)) {
1990 // If creating from scratch
1991 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1992 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1994 // Fill in the array with the extra years we need to process
1995 $yearstoprocess = array();
1996 for($i = $from; $i <= $to; ++$i) {
1997 $yearstoprocess[] = $i;
2000 // Take note of which years we have processed for future calls
2001 $SESSION->dst_range = array($from, $to);
2004 // If needing to extend the table, do the same
2005 $yearstoprocess = array();
2007 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2008 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2010 if($from < $SESSION->dst_range[0]) {
2011 // Take note of which years we need to process and then note that we have processed them for future calls
2012 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2013 $yearstoprocess[] = $i;
2015 $SESSION->dst_range[0] = $from;
2017 if($to > $SESSION->dst_range[1]) {
2018 // Take note of which years we need to process and then note that we have processed them for future calls
2019 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2020 $yearstoprocess[] = $i;
2022 $SESSION->dst_range[1] = $to;
2026 if(empty($yearstoprocess)) {
2027 // This means that there was a call requesting a SMALLER range than we have already calculated
2031 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2032 // Also, the array is sorted in descending timestamp order!
2036 static $presets_cache = array();
2037 if (!isset($presets_cache[$usertz])) {
2038 $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');
2040 if(empty($presets_cache[$usertz])) {
2044 // Remove ending guard (first element of the array)
2045 reset($SESSION->dst_offsets);
2046 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2048 // Add all required change timestamps
2049 foreach($yearstoprocess as $y) {
2050 // Find the record which is in effect for the year $y
2051 foreach($presets_cache[$usertz] as $year => $preset) {
2057 $changes = dst_changes_for_year($y, $preset);
2059 if($changes === NULL) {
2062 if($changes['dst'] != 0) {
2063 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2065 if($changes['std'] != 0) {
2066 $SESSION->dst_offsets[$changes['std']] = 0;
2070 // Put in a guard element at the top
2071 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2072 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2075 krsort($SESSION->dst_offsets);
2081 * Calculates the required DST change and returns a Timestamp Array
2085 * @param mixed $year Int or String Year to focus on
2086 * @param object $timezone Instatiated Timezone object
2087 * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
2089 function dst_changes_for_year($year, $timezone) {
2091 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2095 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2096 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2098 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2099 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2101 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2102 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2104 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2105 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2106 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2108 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2109 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2111 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2115 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2118 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2121 function dst_offset_on($time, $strtimezone = NULL) {
2124 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2128 reset($SESSION->dst_offsets);
2129 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2130 if($from <= $time) {
2135 // This is the normal return path
2136 if($offset !== NULL) {
2140 // Reaching this point means we haven't calculated far enough, do it now:
2141 // Calculate extra DST changes if needed and recurse. The recursion always
2142 // moves toward the stopping condition, so will always end.
2145 // We need a year smaller than $SESSION->dst_range[0]
2146 if($SESSION->dst_range[0] == 1971) {
2149 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2150 return dst_offset_on($time, $strtimezone);
2153 // We need a year larger than $SESSION->dst_range[1]
2154 if($SESSION->dst_range[1] == 2035) {
2157 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2158 return dst_offset_on($time, $strtimezone);
2165 * @todo Document what this function does
2166 * @param int $startday
2167 * @param int $weekday
2172 function find_day_in_month($startday, $weekday, $month, $year) {
2174 $daysinmonth = days_in_month($month, $year);
2176 if($weekday == -1) {
2177 // Don't care about weekday, so return:
2178 // abs($startday) if $startday != -1
2179 // $daysinmonth otherwise
2180 return ($startday == -1) ? $daysinmonth : abs($startday);
2183 // From now on we 're looking for a specific weekday
2185 // Give "end of month" its actual value, since we know it
2186 if($startday == -1) {
2187 $startday = -1 * $daysinmonth;
2190 // Starting from day $startday, the sign is the direction
2194 $startday = abs($startday);
2195 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2197 // This is the last such weekday of the month
2198 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2199 if($lastinmonth > $daysinmonth) {
2203 // Find the first such weekday <= $startday
2204 while($lastinmonth > $startday) {
2208 return $lastinmonth;
2213 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2215 $diff = $weekday - $indexweekday;
2220 // This is the first such weekday of the month equal to or after $startday
2221 $firstfromindex = $startday + $diff;
2223 return $firstfromindex;
2229 * Calculate the number of days in a given month
2231 * @param int $month The month whose day count is sought
2232 * @param int $year The year of the month whose day count is sought
2235 function days_in_month($month, $year) {
2236 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2240 * Calculate the position in the week of a specific calendar day
2242 * @param int $day The day of the date whose position in the week is sought
2243 * @param int $month The month of the date whose position in the week is sought
2244 * @param int $year The year of the date whose position in the week is sought
2247 function dayofweek($day, $month, $year) {
2248 // I wonder if this is any different from
2249 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2250 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2253 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2256 * Returns full login url.
2258 * @return string login url
2260 function get_login_url() {
2263 $url = "$CFG->wwwroot/login/index.php";
2265 if (!empty($CFG->loginhttps)) {
2266 $url = str_replace('http:', 'https:', $url);
2273 * This function checks that the current user is logged in and has the
2274 * required privileges
2276 * This function checks that the current user is logged in, and optionally
2277 * whether they are allowed to be in a particular course and view a particular
2279 * If they are not logged in, then it redirects them to the site login unless
2280 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2281 * case they are automatically logged in as guests.
2282 * If $courseid is given and the user is not enrolled in that course then the
2283 * user is redirected to the course enrolment page.
2284 * If $cm is given and the course module is hidden and the user is not a teacher
2285 * in the course then the user is redirected to the course home page.
2287 * When $cm parameter specified, this function sets page layout to 'module'.
2288 * You need to change it manually later if some other layout needed.
2290 * @param mixed $courseorid id of the course or course object
2291 * @param bool $autologinguest default true
2292 * @param object $cm course module object
2293 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2294 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2295 * in order to keep redirects working properly. MDL-14495
2296 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2297 * @return mixed Void, exit, and die depending on path
2299 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2300 global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2302 // setup global $COURSE, themes, language and locale
2303 if (!empty($courseorid)) {
2304 if (is_object($courseorid)) {
2305 $course = $courseorid;
2306 } else if ($courseorid == SITEID) {
2307 $course = clone($SITE);
2309 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2312 if ($cm->course != $course->id) {
2313 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2315 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2316 $PAGE->set_pagelayout('incourse');
2318 $PAGE->set_course($course); // set's up global $COURSE
2321 // do not touch global $COURSE via $PAGE->set_course(),
2322 // the reasons is we need to be able to call require_login() at any time!!
2325 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2329 // If the user is not even logged in yet then make sure they are
2330 if (!isloggedin()) {
2331 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2332 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2333 // misconfigured site guest, just redirect to login page
2334 redirect(get_login_url());
2335 exit; // never reached
2337 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2338 complete_user_login($guest, false);
2339 $USER->autologinguest = true;
2340 $SESSION->lang = $lang;
2342 //NOTE: $USER->site check was obsoleted by session test cookie,
2343 // $USER->confirmed test is in login/index.php
2344 if ($preventredirect) {
2345 throw new require_login_exception('You are not logged in');
2348 if ($setwantsurltome) {
2349 // TODO: switch to PAGE->url
2350 $SESSION->wantsurl = $FULLME;
2352 if (!empty($_SERVER['HTTP_REFERER'])) {
2353 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2355 redirect(get_login_url());
2356 exit; // never reached
2360 // loginas as redirection if needed
2361 if ($course->id != SITEID and session_is_loggedinas()) {
2362 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2363 if ($USER->loginascontext->instanceid != $course->id) {
2364 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2369 // check whether the user should be changing password (but only if it is REALLY them)
2370 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2371 $userauth = get_auth_plugin($USER->auth);
2372 if ($userauth->can_change_password() and !$preventredirect) {
2373 $SESSION->wantsurl = $FULLME;
2374 if ($changeurl = $userauth->change_password_url()) {
2375 //use plugin custom url
2376 redirect($changeurl);
2378 //use moodle internal method
2379 if (empty($CFG->loginhttps)) {
2380 redirect($CFG->wwwroot .'/login/change_password.php');
2382 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2383 redirect($wwwroot .'/login/change_password.php');
2387 print_error('nopasswordchangeforced', 'auth');
2391 // Check that the user account is properly set up
2392 if (user_not_fully_set_up($USER)) {
2393 if ($preventredirect) {
2394 throw new require_login_exception('User not fully set-up');
2396 $SESSION->wantsurl = $FULLME;
2397 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2400 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2403 // Do not bother admins with any formalities
2404 if (is_siteadmin()) {
2405 //set accesstime or the user will appear offline which messes up messaging
2406 user_accesstime_log($course->id);
2410 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2411 if (!$USER->policyagreed and !is_siteadmin()) {
2412 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2413 if ($preventredirect) {
2414 throw new require_login_exception('Policy not agreed');
2416 $SESSION->wantsurl = $FULLME;
2417 redirect($CFG->wwwroot .'/user/policy.php');
2418 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2419 if ($preventredirect) {
2420 throw new require_login_exception('Policy not agreed');
2422 $SESSION->wantsurl = $FULLME;
2423 redirect($CFG->wwwroot .'/user/policy.php');
2427 // Fetch the system context, the course context, and prefetch its child contexts
2428 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2429 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2431 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2436 // If the site is currently under maintenance, then print a message
2437 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2438 if ($preventredirect) {
2439 throw new require_login_exception('Maintenance in progress');
2442 print_maintenance_message();
2445 // make sure the course itself is not hidden
2446 if ($course->id == SITEID) {
2447 // frontpage can not be hidden
2449 if (is_role_switched($course->id)) {
2450 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2452 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2453 // originally there was also test of parent category visibility,
2454 // BUT is was very slow in complex queries involving "my courses"
2455 // now it is also possible to simply hide all courses user is not enrolled in :-)
2456 if ($preventredirect) {
2457 throw new require_login_exception('Course is hidden');
2459 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2464 // is the user enrolled?
2465 if ($course->id == SITEID) {
2466 // everybody is enrolled on the frontpage
2469 if (session_is_loggedinas()) {
2470 // Make sure the REAL person can access this course first
2471 $realuser = session_get_realuser();
2472 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2473 if ($preventredirect) {
2474 throw new require_login_exception('Invalid course login-as access');
2476 echo $OUTPUT->header();
2477 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2481 // very simple enrolment caching - changes in course setting are not reflected immediately
2482 if (!isset($USER->enrol)) {
2483 $USER->enrol = array();
2484 $USER->enrol['enrolled'] = array();
2485 $USER->enrol['tempguest'] = array();
2490 if (is_viewing($coursecontext, $USER)) {
2491 // ok, no need to mess with enrol
2495 if (isset($USER->enrol['enrolled'][$course->id])) {
2496 if ($USER->enrol['enrolled'][$course->id] == 0) {
2498 } else if ($USER->enrol['enrolled'][$course->id] > time()) {
2502 unset($USER->enrol['enrolled'][$course->id]);
2505 if (isset($USER->enrol['tempguest'][$course->id])) {
2506 if ($USER->enrol['tempguest'][$course->id] == 0) {
2508 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2512 unset($USER->enrol['tempguest'][$course->id]);
2513 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2519 } else if (is_enrolled($coursecontext, $USER, '', true)) {
2520 // active participants may always access
2521 // TODO: refactor this into some new function
2523 $sql = "SELECT MAX(ue.timeend)
2524 FROM {user_enrolments} ue
2525 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2526 JOIN {user} u ON u.id = ue.userid
2527 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0
2528 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
2529 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE,
2530 'userid'=>$USER->id, 'courseid'=>$coursecontext->instanceid, 'now1'=>$now, 'now2'=>$now);
2531 $until = $DB->get_field_sql($sql, $params);
2532 if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) {
2533 $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD;
2536 $USER->enrol['enrolled'][$course->id] = $until;
2539 // remove traces of previous temp guest access
2540 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2543 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2544 $enrols = enrol_get_plugins(true);
2545 // first ask all enabled enrol instances in course if they want to auto enrol user
2546 foreach($instances as $instance) {
2547 if (!isset($enrols[$instance->enrol])) {
2550 // Get a duration for the guestaccess, a timestamp in the future or false.
2551 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2552 if ($until !== false) {
2553 $USER->enrol['enrolled'][$course->id] = $until;
2554 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2559 // if not enrolled yet try to gain temporary guest access
2561 foreach($instances as $instance) {
2562 if (!isset($enrols[$instance->enrol])) {
2565 // Get a duration for the guestaccess, a timestamp in the future or false.
2566 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2567 if ($until !== false) {
2568 $USER->enrol['tempguest'][$course->id] = $until;
2578 if ($preventredirect) {
2579 throw new require_login_exception('Not enrolled');
2581 $SESSION->wantsurl = $FULLME;
2582 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2587 if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2588 if ($preventredirect) {
2589 throw new require_login_exception('Activity is hidden');
2591 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2594 // groupmembersonly access control
2595 if (!empty($CFG->enablegroupmembersonly) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2596 if (isguestuser() or !groups_has_membership($cm)) {
2597 if ($preventredirect) {
2598 throw new require_login_exception('Not member of a group');
2600 print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
2604 // Conditional activity access control
2605 if (!empty($CFG->enableavailability) and $cm) {
2606 // TODO: this is going to work with login-as-user, sorry!
2607 // We cache conditional access in session
2608 if (!isset($SESSION->conditionaccessok)) {
2609 $SESSION->conditionaccessok = array();
2611 // If you have been allowed into the module once then you are allowed
2612 // in for rest of session, no need to do conditional checks
2613 if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
2614 // Get condition info (does a query for the availability table)
2615 require_once($CFG->libdir.'/conditionlib.php');
2616 $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
2617 // Check condition for user (this will do a query if the availability
2618 // information depends on grade or completion information)
2619 if ($ci->is_available($junk) || has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2620 $SESSION->conditionaccessok[$cm->id] = true;
2622 print_error('activityiscurrentlyhidden');
2627 // Finally access granted, update lastaccess times
2628 user_accesstime_log($course->id);
2633 * This function just makes sure a user is logged out.
2637 function require_logout() {
2643 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2645 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2646 foreach($authsequence as $authname) {
2647 $authplugin = get_auth_plugin($authname);
2648 $authplugin->prelogout_hook();
2652 events_trigger('user_logout', $params);
2653 session_get_instance()->terminate_current();
2658 * Weaker version of require_login()
2660 * This is a weaker version of {@link require_login()} which only requires login
2661 * when called from within a course rather than the site page, unless
2662 * the forcelogin option is turned on.
2663 * @see require_login()
2666 * @param mixed $courseorid The course object or id in question
2667 * @param bool $autologinguest Allow autologin guests if that is wanted
2668 * @param object $cm Course activity module if known
2669 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2670 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2671 * in order to keep redirects working properly. MDL-14495
2672 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2675 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2676 global $CFG, $PAGE, $SITE;
2677 if (!empty($CFG->forcelogin)) {
2678 // login required for both SITE and courses
2679 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2681 } else if (!empty($cm) and !$cm->visible) {
2682 // always login for hidden activities
2683 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2685 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2686 or (!is_object($courseorid) and $courseorid == SITEID)) {
2687 //login for SITE not required
2688 if ($cm and empty($cm->visible)) {
2689 // hidden activities are not accessible without login
2690 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2691 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2692 // not-logged-in users do not have any group membership
2693 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2695 // We still need to instatiate PAGE vars properly so that things
2696 // that rely on it like navigation function correctly.
2697 if (!empty($courseorid)) {
2698 if (is_object($courseorid)) {
2699 $course = $courseorid;
2701 $course = clone($SITE);
2704 if ($cm->course != $course->id) {
2705 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2707 $PAGE->set_cm($cm, $course);
2708 $PAGE->set_pagelayout('incourse');
2710 $PAGE->set_course($course);
2713 // If $PAGE->course, and hence $PAGE->context, have not already been set
2714 // up properly, set them up now.
2715 $PAGE->set_course($PAGE->course);
2717 //TODO: verify conditional activities here
2718 user_accesstime_log(SITEID);
2723 // course login always required
2724 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2729 * Require key login. Function terminates with error if key not found or incorrect.
2735 * @uses NO_MOODLE_COOKIES
2736 * @uses PARAM_ALPHANUM
2737 * @param string $script unique script identifier
2738 * @param int $instance optional instance id
2739 * @return int Instance ID
2741 function require_user_key_login($script, $instance=null) {
2742 global $USER, $SESSION, $CFG, $DB;
2744 if (!NO_MOODLE_COOKIES) {
2745 print_error('sessioncookiesdisable');
2749 @session_write_close();
2751 $keyvalue = required_param('key', PARAM_ALPHANUM);
2753 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2754 print_error('invalidkey');
2757 if (!empty($key->validuntil) and $key->validuntil < time()) {
2758 print_error('expiredkey');
2761 if ($key->iprestriction) {
2762 $remoteaddr = getremoteaddr(null);
2763 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2764 print_error('ipmismatch');
2768 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2769 print_error('invaliduserid');
2772 /// emulate normal session
2773 session_set_user($user);
2775 /// note we are not using normal login
2776 if (!defined('USER_KEY_LOGIN')) {
2777 define('USER_KEY_LOGIN', true);
2780 /// return instance id - it might be empty
2781 return $key->instance;
2785 * Creates a new private user access key.
2788 * @param string $script unique target identifier
2789 * @param int $userid
2790 * @param int $instance optional instance id
2791 * @param string $iprestriction optional ip restricted access
2792 * @param timestamp $validuntil key valid only until given data
2793 * @return string access key value
2795 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2798 $key = new stdClass();
2799 $key->script = $script;
2800 $key->userid = $userid;
2801 $key->instance = $instance;
2802 $key->iprestriction = $iprestriction;
2803 $key->validuntil = $validuntil;
2804 $key->timecreated = time();
2806 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
2807 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
2809 $key->value = md5($userid.'_'.time().random_string(40));
2811 $DB->insert_record('user_private_key', $key);
2816 * Delete the user's new private user access keys for a particular script.
2819 * @param string $script unique target identifier
2820 * @param int $userid
2823 function delete_user_key($script,$userid) {
2825 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
2829 * Gets a private user access key (and creates one if one doesn't exist).
2832 * @param string $script unique target identifier
2833 * @param int $userid
2834 * @param int $instance optional instance id
2835 * @param string $iprestriction optional ip restricted access
2836 * @param timestamp $validuntil key valid only until given data
2837 * @return string access key value
2839 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2842 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
2843 'instance'=>$instance, 'iprestriction'=>$iprestriction,
2844 'validuntil'=>$validuntil))) {
2847 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
2853 * Modify the user table by setting the currently logged in user's
2854 * last login to now.
2858 * @return bool Always returns true
2860 function update_user_login_times() {
2863 $user = new stdClass();
2864 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2865 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2867 $user->id = $USER->id;
2869 $DB->update_record('user', $user);
2874 * Determines if a user has completed setting up their account.
2876 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
2879 function user_not_fully_set_up($user) {
2880 if (isguestuser($user)) {
2883 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
2887 * Check whether the user has exceeded the bounce threshold
2891 * @param user $user A {@link $USER} object
2892 * @return bool true=>User has exceeded bounce threshold
2894 function over_bounce_threshold($user) {
2897 if (empty($CFG->handlebounces)) {
2901 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2905 // set sensible defaults
2906 if (empty($CFG->minbounces)) {
2907 $CFG->minbounces = 10;
2909 if (empty($CFG->bounceratio)) {
2910 $CFG->bounceratio = .20;
2914 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2915 $bouncecount = $bounce->value;
2917 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2918 $sendcount = $send->value;
2920 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2924 * Used to increment or reset email sent count
2927 * @param user $user object containing an id
2928 * @param bool $reset will reset the count to 0
2931 function set_send_count($user,$reset=false) {
2934 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2938 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2939 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2940 $DB->update_record('user_preferences', $pref);
2942 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2944 $pref = new stdClass();
2945 $pref->name = 'email_send_count';
2947 $pref->userid = $user->id;
2948 $DB->insert_record('user_preferences', $pref, false);
2953 * Increment or reset user's email bounce count
2956 * @param user $user object containing an id
2957 * @param bool $reset will reset the count to 0
2959 function set_bounce_count($user,$reset=false) {
2962 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2963 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2964 $DB->update_record('user_preferences', $pref);
2966 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2968 $pref = new stdClass();
2969 $pref->name = 'email_bounce_count';
2971 $pref->userid = $user->id;
2972 $DB->insert_record('user_preferences', $pref, false);
2977 * Keeps track of login attempts
2981 function update_login_count() {
2986 if (empty($SESSION->logincount)) {
2987 $SESSION->logincount = 1;
2989 $SESSION->logincount++;
2992 if ($SESSION->logincount > $max_logins) {
2993 unset($SESSION->wantsurl);
2994 print_error('errortoomanylogins');
2999 * Resets login attempts
3003 function reset_login_count() {
3006 $SESSION->logincount = 0;
3010 * Returns reference to full info about modules in course (including visibility).
3011 * Cached and as fast as possible (0 or 1 db query).
3016 * @uses CONTEXT_MODULE
3017 * @uses MAX_MODINFO_CACHE_SIZE
3018 * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
3019 * @param int $userid Defaults to current user id
3020 * @return mixed courseinfo object or nothing if resetting
3022 function &get_fast_modinfo(&$course, $userid=0) {
3023 global $CFG, $USER, $DB;
3024 require_once($CFG->dirroot.'/course/lib.php');
3026 if (!empty($CFG->enableavailability)) {
3027 require_once($CFG->libdir.'/conditionlib.php');
3030 static $cache = array();
3032 if ($course === 'reset') {
3035 return $nothing; // we must return some reference
3038 if (empty($userid)) {
3039 $userid = $USER->id;
3042 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
3043 return $cache[$course->id];
3046 if (!property_exists($course, 'modinfo')) {
3047 debugging('Coding problem - missing course modinfo property in get_fast_modinfo() call');
3050 if (empty($course->modinfo)) {
3051 // no modinfo yet - load it
3052 rebuild_course_cache($course->id);
3053 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
3056 $modinfo = new stdClass();
3057 $modinfo->courseid = $course->id;
3058 $modinfo->userid = $userid;
3059 $modinfo->sections = array();
3060 $modinfo->cms = array();
3061 $modinfo->instances = array();
3062 $modinfo->groups = null; // loaded only when really needed - the only one db query
3064 $info = unserialize($course->modinfo);
3065 if (!is_array($info)) {
3066 // hmm, something is wrong - lets try to fix it
3067 rebuild_course_cache($course->id);
3068 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
3069 $info = unserialize($course->modinfo);
3070 if (!is_array($info)) {
3076 // detect if upgrade required
3077 $first = reset($info);
3078 if (!isset($first->id)) {
3079 rebuild_course_cache($course->id);
3080 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
3081 $info = unserialize($course->modinfo);
3082 if (!is_array($info)) {
3088 $modlurals = array();
3090 // If we haven't already preloaded contexts for the course, do it now
3091 preload_course_contexts($course->id);
3093 foreach ($info as $mod) {
3094 if (empty($mod->name)) {
3095 // something is wrong here
3098 // reconstruct minimalistic $cm
3099 $cm = new stdClass();
3101 $cm->instance = $mod->id;
3102 $cm->course = $course->id;
3103 $cm->modname = $mod->mod;
3104 $cm->idnumber = $mod->idnumber;
3105 $cm->name = $mod->name;
3106 $cm->visible = $mod->visible;
3107 $cm->sectionnum = $mod->section;
3108 $cm->groupmode = $mod->groupmode;
3109 $cm->groupingid = $mod->groupingid;
3110 $cm->groupmembersonly = $mod->groupmembersonly;
3111 $cm->indent = $mod->indent;
3112 $cm->completion = $mod->completion;
3113 $cm->extra = isset($mod->extra) ? $mod->extra : '';
3114 $cm->icon = isset($mod->icon) ? $mod->icon : '';
3115 $cm->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
3116 $cm->uservisible = true;
3117 if (!empty($CFG->enableavailability)) {
3118 // We must have completion information from modinfo. If it's not
3119 // there, cache needs rebuilding
3120 if(!isset($mod->availablefrom)) {
3121 debugging('enableavailability option was changed; rebuilding '.
3122 'cache for course '.$course->id);
3123 rebuild_course_cache($course->id,true);
3124 // Re-enter this routine to do it all properly
3125 return get_fast_modinfo($course, $userid);
3127 $cm->availablefrom = $mod->availablefrom;
3128 $cm->availableuntil = $mod->availableuntil;
3129 $cm->showavailability = $mod->showavailability;
3130 $cm->conditionscompletion = $mod->conditionscompletion;
3131 $cm->conditionsgrade = $mod->conditionsgrade;
3134 // preload long names plurals and also check module is installed properly
3135 if (!isset($modlurals[$cm->modname])) {
3136 if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
3139 $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
3141 $cm->modplural = $modlurals[$cm->modname];
3142 $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id);
3144 if (!empty($CFG->enableavailability)) {
3145 // Unfortunately the next call really wants to call
3146 // get_fast_modinfo, but that would be recursive, so we fake up a
3147 // modinfo for it already
3148 if (empty($minimalmodinfo)) { //TODO: this is suspicious (skodak)
3149 $minimalmodinfo = new stdClass();
3150 $minimalmodinfo->cms = array();
3151 foreach($info as $mod) {
3152 if (empty($mod->name)) {
3153 // something is wrong here
3156 $minimalcm = new stdClass();
3157 $minimalcm->id = $mod->cm;
3158 $minimalcm->name = $mod->name;
3159 $minimalmodinfo->cms[$minimalcm->id]=$minimalcm;
3163 // Get availability information
3164 $ci = new condition_info($cm);
3165 $cm->available = $ci->is_available($cm->availableinfo, true, $userid, $minimalmodinfo);
3167 $cm->available = true;
3169 if ((!$cm->visible or !$cm->available) and !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
3170 $cm->uservisible = false;
3172 } else if (!empty($CFG->enablegroupmembersonly) and !empty($cm->groupmembersonly)
3173 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
3174 if (is_null($modinfo->groups)) {
3175 $modinfo->groups = groups_get_user_groups($course->id, $userid);
3177 if (empty($modinfo->groups[$cm->groupingid])) {
3178 $cm->uservisible = false;
3182 if (!isset($modinfo->instances[$cm->modname])) {
3183 $modinfo->instances[$cm->modname] = array();
3185 $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
3186 $modinfo->cms[$cm->id] =& $cm;
3188 // reconstruct sections
3189 if (!isset($modinfo->sections[$cm->sectionnum])) {
3190 $modinfo->sections[$cm->sectionnum] = array();
3192 $modinfo->sections[$cm->sectionnum][] = $cm->id;
3197 unset($cache[$course->id]); // prevent potential reference problems when switching users
3198 $cache[$course->id] = $modinfo;
3200 // Ensure cache does not use too much RAM
3201 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
3204 unset($cache[$key]);
3207 return $cache[$course->id];
3211 * Determines if the currently logged in user is in editing mode.
3212 * Note: originally this function had $userid parameter - it was not usable anyway
3214 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3215 * @todo Deprecated function remove when ready
3218 * @uses DEBUG_DEVELOPER
3221 function isediting() {
3223 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3224 return $PAGE->user_is_editing();
3228 * Determines if the logged in user is currently moving an activity
3231 * @param int $courseid The id of the course being tested
3234 function ismoving($courseid) {
3237 if (!empty($USER->activitycopy)) {
3238 return ($USER->activitycopycourse == $courseid);
3244 * Returns a persons full name
3246 * Given an object containing firstname and lastname
3247 * values, this function returns a string with the
3248 * full name of the person.
3249 * The result may depend on system settings
3250 * or language. 'override' will force both names
3251 * to be used even if system settings specify one.
3255 * @param object $user A {@link $USER} object to get full name of
3256 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3259 function fullname($user, $override=false) {
3260 global $CFG, $SESSION;
3262 if (!isset($user->firstname) and !isset($user->lastname)) {
3267 if (!empty($CFG->forcefirstname)) {
3268 $user->firstname = $CFG->forcefirstname;
3270 if (!empty($CFG->forcelastname)) {
3271 $user->lastname = $CFG->forcelastname;
3275 if (!empty($SESSION->fullnamedisplay)) {
3276 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3279 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3280 return $user->firstname .' '. $user->lastname;
3282 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3283 return $user->lastname .' '. $user->firstname;
3285 } else if ($CFG->fullnamedisplay == 'firstname') {
3287 return get_string('fullnamedisplay', '', $user);
3289 return $user->firstname;
3293 return get_string('fullnamedisplay', '', $user);
3297 * Returns whether a given authentication plugin exists.
3300 * @param string $auth Form of authentication to check for. Defaults to the
3301 * global setting in {@link $CFG}.
3302 * @return boolean Whether the plugin is available.
3304 function exists_auth_plugin($auth) {
3307 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3308 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3314 * Checks if a given plugin is in the list of enabled authentication plugins.
3316 * @param string $auth Authentication plugin.
3317 * @return boolean Whether the plugin is enabled.
3319 function is_enabled_auth($auth) {
3324 $enabled = get_enabled_auth_plugins();
3326 return in_array($auth, $enabled);
3330 * Returns an authentication plugin instance.
3333 * @param string $auth name of authentication plugin
3334 * @return auth_plugin_base An instance of the required authentication plugin.
3336 function get_auth_plugin($auth) {
3339 // check the plugin exists first
3340 if (! exists_auth_plugin($auth)) {
3341 print_error('authpluginnotfound', 'debug', '', $auth);
3344 // return auth plugin instance
3345 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3346 $class = "auth_plugin_$auth";
3351 * Returns array of active auth plugins.
3353 * @param bool $fix fix $CFG->auth if needed
3356 function get_enabled_auth_plugins($fix=false) {
3359 $default = array('manual', 'nologin');
3361 if (empty($CFG->auth)) {
3364 $auths = explode(',', $CFG->auth);
3368 $auths = array_unique($auths);
3369 foreach($auths as $k=>$authname) {
3370 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3374 $newconfig = implode(',', $auths);
3375 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3376 set_config('auth', $newconfig);
3380 return (array_merge($default, $auths));
3384 * Returns true if an internal authentication method is being used.
3385 * if method not specified then, global default is assumed
3387 * @param string $auth Form of authentication required
3390 function is_internal_auth($auth) {
3391 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3392 return $authplugin->is_internal();
3396 * Returns true if the user is a 'restored' one
3398 * Used in the login process to inform the user
3399 * and allow him/her to reset the password
3403 * @param string $username username to be checked
3406 function is_restored_user($username) {
3409 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3413 * Returns an array of user fields
3415 * @return array User field/column names
3417 function get_user_fieldnames() {
3420 $fieldarray = $DB->get_columns('user');
3421 unset($fieldarray['id']);
3422 $fieldarray = array_keys($fieldarray);
3428 * Creates a bare-bones user record
3430 * @todo Outline auth types and provide code example
3432 * @param string $username New user's username to add to record
3433 * @param string $password New user's password to add to record
3434 * @param string $auth Form of authentication required
3435 * @return stdClass A complete user object
3437 function create_user_record($username, $password, $auth = 'manual') {
3440 //just in case check text case
3441 $username = trim(moodle_strtolower($username));
3443 $authplugin = get_auth_plugin($auth);
3445 $newuser = new stdClass();
3447 if ($newinfo = $authplugin->get_userinfo($username)) {
3448 $newinfo = truncate_userinfo($newinfo);
3449 foreach ($newinfo as $key => $value){
3450 $newuser->$key = $value;
3454 if (!empty($newuser->email)) {
3455 if (email_is_not_allowed($newuser->email)) {
3456 unset($newuser->email);
3460 if (!isset($newuser->city)) {
3461 $newuser->city = '';
3464 $newuser->auth = $auth;
3465 $newuser->username = $username;
3468 // user CFG lang for user if $newuser->lang is empty
3469 // or $user->lang is not an installed language
3470 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3471 $newuser->lang = $CFG->lang;
3473 $newuser->confirmed = 1;
3474 $newuser->lastip = getremoteaddr();
3475 $newuser->timemodified = time();
3476 $newuser->mnethostid = $CFG->mnet_localhost_id;
3478 $newuser->id = $DB->insert_record('user', $newuser);
3479 $user = get_complete_user_data('id', $newuser->id);
3480 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3481 set_user_preference('auth_forcepasswordchange', 1, $user);
3483 update_internal_user_password($user, $password);
3485 // fetch full user record for the event, the complete user data contains too much info
3486 // and we want to be consistent with other places that trigger this event
3487 events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
3493 * Will update a local user record from an external source.
3494 * (MNET users can not be updated using this method!)
3496 * @param string $username user's username to update the record
3497 * @return stdClass A complete user object
3499 function update_user_record($username) {
3502 $username = trim(moodle_strtolower($username)); /// just in case check text case
3504 $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
3506 $userauth = get_auth_plugin($oldinfo->auth);
3508 if ($newinfo = $userauth->get_userinfo($username)) {
3509 $newinfo = truncate_userinfo($newinfo);
3510 foreach ($newinfo as $key => $value){
3511 $key = strtolower($key);
3512 if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id'
3513 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3514 // unknown or must not be changed
3517 $confval = $userauth->config->{'field_updatelocal_' . $key};
3518 $lockval = $userauth->config->{'field_lock_' . $key};
3519 if (empty($confval) || empty($lockval)) {
3522 if ($confval === 'onlogin') {
3523 // MDL-4207 Don't overwrite modified user profile values with
3524 // empty LDAP values when 'unlocked if empty' is set. The purpose
3525 // of the setting 'unlocked if empty' is to allow the user to fill
3526 // in a value for the selected field _if LDAP is giving
3527 // nothing_ for this field. Thus it makes sense to let this value
3528 // stand in until LDAP is giving a value for this field.
3529 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3530 if ((string)$oldinfo->$key !== (string)$value) {
3531 $newuser[$key] = (string)$value;
3537 $newuser['id'] = $oldinfo->id;
3538 $DB->update_record('user', $newuser);
3539 // fetch full user record for the event, the complete user data contains too much info
3540 // and we want to be consistent with other places that trigger this event
3541 events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id)));
3545 return get_complete_user_data('id', $oldinfo->id);
3549 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3550 * which may have large fields
3552 * @todo Add vartype handling to ensure $info is an array
3554 * @param array $info Array of user properties to truncate if needed
3555 * @return array The now truncated information that was passed in
3557 function truncate_userinfo($info) {
3558 // define the limits
3568 'institution' => 40,
3576 $textlib = textlib_get_instance();
3577 // apply where needed
3578 foreach (array_keys($info) as $key) {
3579 if (!empty($limit[$key])) {
3580 $info[$key] = trim($textlib->substr($info[$key],0, $limit[$key]));
3588 * Marks user deleted in internal user database and notifies the auth plugin.
3589 * Also unenrols user from all roles and does other cleanup.
3591 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3593 * @param object $user User object before delete
3594 * @return boolean always true
3596 function delete_user($user) {
3598 require_once($CFG->libdir.'/grouplib.php');
3599 require_once($CFG->libdir.'/gradelib.php');
3600 require_once($CFG->dirroot.'/message/lib.php');
3601 require_once($CFG->dirroot.'/tag/lib.php');
3603 // delete all grades - backup is kept in grade_grades_history table
3604 grade_user_delete($user->id);
3606 //move unread messages from this user to read
3607 message_move_userfrom_unread2read($user->id);
3609 // TODO: remove from cohorts using standard API here
3612 tag_set('user', $user->id, array());
3614 // unconditionally unenrol from all courses
3615 enrol_user_delete($user);
3617 // unenrol from all roles in all contexts
3618 role_unassign_all(array('userid'=>$user->id)); // this might be slow but it is really needed - modules might do some extra cleanup!
3620 //now do a brute force cleanup
3622 // remove from all cohorts
3623 $DB->delete_records('cohort_members', array('userid'=>$user->id));
3625 // remove from all groups
3626 $DB->delete_records('groups_members', array('userid'=>$user->id));
3628 // brute force unenrol from all courses
3629 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
3631 // purge user preferences
3632 $DB->delete_records('user_preferences', array('userid'=>$user->id));
3634 // purge user extra profile info
3635 $DB->delete_records('user_info_data', array('userid'=>$user->id));
3637 // last course access not necessary either
3638 $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
3640 // now do a final accesslib cleanup - removes all role assignments in user context and context itself
3641 delete_context(CONTEXT_USER, $user->id);
3643 // workaround for bulk deletes of users with the same email address
3644 $delname = "$user->email.".time();
3645 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3649 // mark internal user record as "deleted"
3650 $updateuser = new stdClass();
3651 $updateuser->id = $user->id;
3652 $updateuser->deleted = 1;
3653 $updateuser->username = $delname; // Remember it just in case
3654 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
3655 $updateuser->idnumber = ''; // Clear this field to free it up
3656 $updateuser->timemodified = time();
3658 $DB->update_record('user', $updateuser);
3660 // notify auth plugin - do not block the delete even when plugin fails
3661 $authplugin = get_auth_plugin($user->auth);
3662 $authplugin->user_delete($user);
3664 // any plugin that needs to cleanup should register this event
3665 events_trigger('user_deleted', $user);
3671 * Retrieve the guest user object
3675 * @return user A {@link $USER} object
3677 function guest_user() {
3680 if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
3681 $newuser->confirmed = 1;
3682 $newuser->lang = $CFG->lang;
3683 $newuser->lastip = getremoteaddr();