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 //as long as magic_quotes_gpc is used, a backslash will be a
796 //problem, so remove *all* backslash.
797 //$param = str_replace('\\', '', $param);
798 //remove some nasties
799 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
800 //convert many whitespace chars into one
801 $param = preg_replace('/\s+/', ' ', $param);
802 $textlib = textlib_get_instance();
803 $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
808 $tags = explode(',', $param);
810 foreach ($tags as $tag) {
811 $res = clean_param($tag, PARAM_TAG);
817 return implode(',', $result);
822 case PARAM_CAPABILITY:
823 if (get_capability_info($param)) {
829 case PARAM_PERMISSION:
830 $param = (int)$param;
831 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
838 $param = clean_param($param, PARAM_SAFEDIR);
839 if (exists_auth_plugin($param)) {
846 $param = clean_param($param, PARAM_SAFEDIR);
847 if (get_string_manager()->translation_exists($param)) {
850 return ''; // Specified language is not installed or param malformed
854 $param = clean_param($param, PARAM_SAFEDIR);
855 if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
857 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
860 return ''; // Specified theme is not installed
864 $param = str_replace(" " , "", $param);
865 $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
866 if (empty($CFG->extendedusernamechars)) {
867 // regular expression, eliminate all chars EXCEPT:
868 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
869 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
874 if (validate_email($param)) {
881 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
887 default: // throw error, switched parameters in optional_param or another serious problem
888 print_error("unknownparamtype", '', '', $type);
893 * Return true if given value is integer or string with integer value
895 * @param mixed $value String or Int
896 * @return bool true if number, false if not
898 function is_number($value) {
899 if (is_int($value)) {
901 } else if (is_string($value)) {
902 return ((string)(int)$value) === $value;
909 * Returns host part from url
910 * @param string $url full url
911 * @return string host, null if not found
913 function get_host_from_url($url) {
914 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
922 * Tests whether anything was returned by text editor
924 * This function is useful for testing whether something you got back from
925 * the HTML editor actually contains anything. Sometimes the HTML editor
926 * appear to be empty, but actually you get back a <br> tag or something.
928 * @param string $string a string containing HTML.
929 * @return boolean does the string contain any actual content - that is text,
930 * images, objects, etc.
932 function html_is_blank($string) {
933 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
937 * Set a key in global configuration
939 * Set a key/value pair in both this session's {@link $CFG} global variable
940 * and in the 'config' database table for future sessions.
942 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
943 * In that case it doesn't affect $CFG.
945 * A NULL value will delete the entry.
949 * @param string $name the key to set
950 * @param string $value the value to set (without magic quotes)
951 * @param string $plugin (optional) the plugin scope, default NULL
952 * @return bool true or exception
954 function set_config($name, $value, $plugin=NULL) {
957 if (empty($plugin)) {
958 if (!array_key_exists($name, $CFG->config_php_settings)) {
959 // So it's defined for this invocation at least
960 if (is_null($value)) {
963 $CFG->$name = (string)$value; // settings from db are always strings
967 if ($DB->get_field('config', 'name', array('name'=>$name))) {
968 if ($value === null) {
969 $DB->delete_records('config', array('name'=>$name));
971 $DB->set_field('config', 'value', $value, array('name'=>$name));
974 if ($value !== null) {
975 $config = new stdClass();
976 $config->name = $name;
977 $config->value = $value;
978 $DB->insert_record('config', $config, false);
982 } else { // plugin scope
983 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
985 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
987 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
990 if ($value !== null) {
991 $config = new stdClass();
992 $config->plugin = $plugin;
993 $config->name = $name;
994 $config->value = $value;
995 $DB->insert_record('config_plugins', $config, false);
1004 * Get configuration values from the global config table
1005 * or the config_plugins table.
1007 * If called with one parameter, it will load all the config
1008 * variables for one plugin, and return them as an object.
1010 * If called with 2 parameters it will return a string single
1011 * value or false if the value is not found.
1013 * @param string $plugin full component name
1014 * @param string $name default NULL
1015 * @return mixed hash-like object or single value, return false no config found
1017 function get_config($plugin, $name = NULL) {
1020 // normalise component name
1021 if ($plugin === 'moodle' or $plugin === 'core') {
1025 if (!empty($name)) { // the user is asking for a specific value
1026 if (!empty($plugin)) {
1027 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1028 // setting forced in config file
1029 return $CFG->forced_plugin_settings[$plugin][$name];
1031 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1034 if (array_key_exists($name, $CFG->config_php_settings)) {
1035 // setting force in config file
1036 return $CFG->config_php_settings[$name];
1038 return $DB->get_field('config', 'value', array('name'=>$name));
1043 // the user is after a recordset
1045 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1046 if (isset($CFG->forced_plugin_settings[$plugin])) {
1047 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1048 if (is_null($v) or is_array($v) or is_object($v)) {
1049 // we do not want any extra mess here, just real settings that could be saved in db
1050 unset($localcfg[$n]);
1052 //convert to string as if it went through the DB
1053 $localcfg[$n] = (string)$v;
1058 return (object)$localcfg;
1064 // this part is not really used any more, but anyway...
1065 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1066 foreach($CFG->config_php_settings as $n=>$v) {
1067 if (is_null($v) or is_array($v) or is_object($v)) {
1068 // we do not want any extra mess here, just real settings that could be saved in db
1069 unset($localcfg[$n]);
1071 //convert to string as if it went through the DB
1072 $localcfg[$n] = (string)$v;
1075 return (object)$localcfg;
1080 * Removes a key from global configuration
1082 * @param string $name the key to set
1083 * @param string $plugin (optional) the plugin scope
1085 * @return boolean whether the operation succeeded.
1087 function unset_config($name, $plugin=NULL) {
1090 if (empty($plugin)) {
1092 $DB->delete_records('config', array('name'=>$name));
1094 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1101 * Remove all the config variables for a given plugin.
1103 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1104 * @return boolean whether the operation succeeded.
1106 function unset_all_config_for_plugin($plugin) {
1108 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1109 $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
1114 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1116 * All users are verified if they still have the necessary capability.
1118 * @param string $value the value of the config setting.
1119 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1120 * @param bool $include admins, include administrators
1121 * @return array of user objects.
1123 function get_users_from_config($value, $capability, $includeadmins = true) {
1126 if (empty($value) or $value === '$@NONE@$') {
1130 // we have to make sure that users still have the necessary capability,
1131 // it should be faster to fetch them all first and then test if they are present
1132 // instead of validating them one-by-one
1133 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1134 if ($includeadmins) {
1135 $admins = get_admins();
1136 foreach ($admins as $admin) {
1137 $users[$admin->id] = $admin;
1141 if ($value === '$@ALL@$') {
1145 $result = array(); // result in correct order
1146 $allowed = explode(',', $value);
1147 foreach ($allowed as $uid) {
1148 if (isset($users[$uid])) {
1149 $user = $users[$uid];
1150 $result[$user->id] = $user;
1159 * Invalidates browser caches and cached data in temp
1162 function purge_all_caches() {
1165 reset_text_filters_cache();
1166 js_reset_all_caches();
1167 theme_reset_all_caches();
1168 get_string_manager()->reset_caches();
1170 // purge all other caches: rss, simplepie, etc.
1171 remove_dir($CFG->dataroot.'/cache', true);
1173 // make sure cache dir is writable, throws exception if not
1174 make_upload_directory('cache');
1180 * Get volatile flags
1182 * @param string $type
1183 * @param int $changedsince default null
1184 * @return records array
1186 function get_cache_flags($type, $changedsince=NULL) {
1189 $params = array('type'=>$type, 'expiry'=>time());
1190 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1191 if ($changedsince !== NULL) {
1192 $params['changedsince'] = $changedsince;
1193 $sqlwhere .= " AND timemodified > :changedsince";
1197 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1198 foreach ($flags as $flag) {
1199 $cf[$flag->name] = $flag->value;
1206 * Get volatile flags
1208 * @param string $type
1209 * @param string $name
1210 * @param int $changedsince default null
1211 * @return records array
1213 function get_cache_flag($type, $name, $changedsince=NULL) {
1216 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1218 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1219 if ($changedsince !== NULL) {
1220 $params['changedsince'] = $changedsince;
1221 $sqlwhere .= " AND timemodified > :changedsince";
1224 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1228 * Set a volatile flag
1230 * @param string $type the "type" namespace for the key
1231 * @param string $name the key to set
1232 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1233 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1234 * @return bool Always returns true
1236 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1239 $timemodified = time();
1240 if ($expiry===NULL || $expiry < $timemodified) {
1241 $expiry = $timemodified + 24 * 60 * 60;
1243 $expiry = (int)$expiry;
1246 if ($value === NULL) {
1247 unset_cache_flag($type,$name);
1251 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1252 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1253 return true; //no need to update; helps rcache too
1256 $f->expiry = $expiry;
1257 $f->timemodified = $timemodified;
1258 $DB->update_record('cache_flags', $f);
1260 $f = new stdClass();
1261 $f->flagtype = $type;
1264 $f->expiry = $expiry;
1265 $f->timemodified = $timemodified;
1266 $DB->insert_record('cache_flags', $f);
1272 * Removes a single volatile flag
1275 * @param string $type the "type" namespace for the key
1276 * @param string $name the key to set
1279 function unset_cache_flag($type, $name) {
1281 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1286 * Garbage-collect volatile flags
1288 * @return bool Always returns true
1290 function gc_cache_flags() {
1292 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1296 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1299 * Refresh user preference cache. This is used most often for $USER
1300 * object that is stored in session, but it also helps with performance in cron script.
1302 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1304 * @param stdClass $user user object, preferences are preloaded into ->preference property
1305 * @param int $cachelifetime cache life time on the current page (ins seconds)
1308 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1310 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1312 if (!isset($user->id)) {
1313 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1316 if (empty($user->id) or isguestuser($user->id)) {
1317 // No permanent storage for not-logged-in users and guest
1318 if (!isset($user->preference)) {
1319 $user->preference = array();
1326 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1327 // Already loaded at least once on this page. Are we up to date?
1328 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1329 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1332 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1333 // no change since the lastcheck on this page
1334 $user->preference['_lastloaded'] = $timenow;
1339 // OK, so we have to reload all preferences
1340 $loadedusers[$user->id] = true;
1341 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1342 $user->preference['_lastloaded'] = $timenow;
1346 * Called from set/delete_user_preferences, so that the prefs can
1347 * be correctly reloaded in different sessions.
1349 * NOTE: internal function, do not call from other code.
1351 * @param integer $userid the user whose prefs were changed.
1354 function mark_user_preferences_changed($userid) {
1357 if (empty($userid) or isguestuser($userid)) {
1358 // no cache flags for guest and not-logged-in users
1362 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1366 * Sets a preference for the specified user.
1368 * If user object submitted, 'preference' property contains the preferences cache.
1370 * @param string $name The key to set as preference for the specified user
1371 * @param string $value The value to set for the $name key in the specified user's record,
1372 * null means delete current value
1373 * @param stdClass|int $user A moodle user object or id, null means current user
1374 * @return bool always true or exception
1376 function set_user_preference($name, $value, $user = null) {
1379 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1380 throw new coding_exception('Invalid preference name in set_user_preference() call');
1383 if (is_null($value)) {
1384 // null means delete current
1385 return unset_user_preference($name, $user);
1386 } else if (is_object($value)) {
1387 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1388 } else if (is_array($value)) {
1389 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1391 $value = (string)$value;
1393 if (is_null($user)) {
1395 } else if (isset($user->id)) {
1396 // $user is valid object
1397 } else if (is_numeric($user)) {
1398 $user = (object)array('id'=>(int)$user);
1400 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1403 check_user_preferences_loaded($user);
1405 if (empty($user->id) or isguestuser($user->id)) {
1406 // no permanent storage for not-logged-in users and guest
1407 $user->preference[$name] = $value;
1411 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1412 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1413 // preference already set to this value
1416 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1419 $preference = new stdClass();
1420 $preference->userid = $user->id;
1421 $preference->name = $name;
1422 $preference->value = $value;
1423 $DB->insert_record('user_preferences', $preference);
1426 // update value in cache
1427 $user->preference[$name] = $value;
1429 // set reload flag for other sessions
1430 mark_user_preferences_changed($user->id);
1436 * Sets a whole array of preferences for the current user
1438 * If user object submitted, 'preference' property contains the preferences cache.
1440 * @param array $prefarray An array of key/value pairs to be set
1441 * @param stdClass|int $user A moodle user object or id, null means current user
1442 * @return bool always true or exception
1444 function set_user_preferences(array $prefarray, $user = null) {
1445 foreach ($prefarray as $name => $value) {
1446 set_user_preference($name, $value, $user);
1452 * Unsets a preference completely by deleting it from the database
1454 * If user object submitted, 'preference' property contains the preferences cache.
1456 * @param string $name The key to unset as preference for the specified user
1457 * @param stdClass|int $user A moodle user object or id, null means current user
1458 * @return bool always true or exception
1460 function unset_user_preference($name, $user = null) {
1463 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1464 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1467 if (is_null($user)) {
1469 } else if (isset($user->id)) {
1470 // $user is valid object
1471 } else if (is_numeric($user)) {
1472 $user = (object)array('id'=>(int)$user);
1474 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1477 check_user_preferences_loaded($user);
1479 if (empty($user->id) or isguestuser($user->id)) {
1480 // no permanent storage for not-logged-in user and guest
1481 unset($user->preference[$name]);
1486 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1488 // delete the preference from cache
1489 unset($user->preference[$name]);
1491 // set reload flag for other sessions
1492 mark_user_preferences_changed($user->id);
1498 * Used to fetch user preference(s)
1500 * If no arguments are supplied this function will return
1501 * all of the current user preferences as an array.
1503 * If a name is specified then this function
1504 * attempts to return that particular preference value. If
1505 * none is found, then the optional value $default is returned,
1508 * If user object submitted, 'preference' property contains the preferences cache.
1510 * @param string $name Name of the key to use in finding a preference value
1511 * @param mixed $default Value to be returned if the $name key is not set in the user preferences
1512 * @param stdClass|int $user A moodle user object or id, null means current user
1513 * @return mixed string value or default
1515 function get_user_preferences($name = null, $default = null, $user = null) {
1518 if (is_null($name)) {
1520 } else if (is_numeric($name) or $name === '_lastloaded') {
1521 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1524 if (is_null($user)) {
1526 } else if (isset($user->id)) {
1527 // $user is valid object
1528 } else if (is_numeric($user)) {
1529 $user = (object)array('id'=>(int)$user);
1531 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1534 check_user_preferences_loaded($user);
1537 return $user->preference; // All values
1538 } else if (isset($user->preference[$name])) {
1539 return $user->preference[$name]; // The single string value
1541 return $default; // Default value (null if not specified)
1545 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1548 * Given date parts in user time produce a GMT timestamp.
1550 * @todo Finish documenting this function
1551 * @param int $year The year part to create timestamp of
1552 * @param int $month The month part to create timestamp of
1553 * @param int $day The day part to create timestamp of
1554 * @param int $hour The hour part to create timestamp of
1555 * @param int $minute The minute part to create timestamp of
1556 * @param int $second The second part to create timestamp of
1557 * @param float $timezone Timezone modifier
1558 * @param bool $applydst Toggle Daylight Saving Time, default true
1559 * @return int timestamp
1561 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1563 $strtimezone = NULL;
1564 if (!is_numeric($timezone)) {
1565 $strtimezone = $timezone;
1568 $timezone = get_user_timezone_offset($timezone);
1570 if (abs($timezone) > 13) {
1571 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1573 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1574 $time = usertime($time, $timezone);
1576 $time -= dst_offset_on($time, $strtimezone);
1585 * Format a date/time (seconds) as weeks, days, hours etc as needed
1587 * Given an amount of time in seconds, returns string
1588 * formatted nicely as weeks, days, hours etc as needed
1594 * @param int $totalsecs Time in seconds
1595 * @param object $str Should be a time object
1596 * @return string A nicely formatted date/time string
1598 function format_time($totalsecs, $str=NULL) {
1600 $totalsecs = abs($totalsecs);
1602 if (!$str) { // Create the str structure the slow way
1603 $str->day = get_string('day');
1604 $str->days = get_string('days');
1605 $str->hour = get_string('hour');
1606 $str->hours = get_string('hours');
1607 $str->min = get_string('min');
1608 $str->mins = get_string('mins');
1609 $str->sec = get_string('sec');
1610 $str->secs = get_string('secs');
1611 $str->year = get_string('year');
1612 $str->years = get_string('years');
1616 $years = floor($totalsecs/YEARSECS);
1617 $remainder = $totalsecs - ($years*YEARSECS);
1618 $days = floor($remainder/DAYSECS);
1619 $remainder = $totalsecs - ($days*DAYSECS);
1620 $hours = floor($remainder/HOURSECS);
1621 $remainder = $remainder - ($hours*HOURSECS);
1622 $mins = floor($remainder/MINSECS);
1623 $secs = $remainder - ($mins*MINSECS);
1625 $ss = ($secs == 1) ? $str->sec : $str->secs;
1626 $sm = ($mins == 1) ? $str->min : $str->mins;
1627 $sh = ($hours == 1) ? $str->hour : $str->hours;
1628 $sd = ($days == 1) ? $str->day : $str->days;
1629 $sy = ($years == 1) ? $str->year : $str->years;
1637 if ($years) $oyears = $years .' '. $sy;
1638 if ($days) $odays = $days .' '. $sd;
1639 if ($hours) $ohours = $hours .' '. $sh;
1640 if ($mins) $omins = $mins .' '. $sm;
1641 if ($secs) $osecs = $secs .' '. $ss;
1643 if ($years) return trim($oyears .' '. $odays);
1644 if ($days) return trim($odays .' '. $ohours);
1645 if ($hours) return trim($ohours .' '. $omins);
1646 if ($mins) return trim($omins .' '. $osecs);
1647 if ($secs) return $osecs;
1648 return get_string('now');
1652 * Returns a formatted string that represents a date in user time
1654 * Returns a formatted string that represents a date in user time
1655 * <b>WARNING: note that the format is for strftime(), not date().</b>
1656 * Because of a bug in most Windows time libraries, we can't use
1657 * the nicer %e, so we have to use %d which has leading zeroes.
1658 * A lot of the fuss in the function is just getting rid of these leading
1659 * zeroes as efficiently as possible.
1661 * If parameter fixday = true (default), then take off leading
1662 * zero from %d, else maintain it.
1664 * @param int $date the timestamp in UTC, as obtained from the database.
1665 * @param string $format strftime format. You should probably get this using
1666 * get_string('strftime...', 'langconfig');
1667 * @param float $timezone by default, uses the user's time zone.
1668 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1669 * If false then the leading zero is maintained.
1670 * @return string the formatted date/time.
1672 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1676 $strtimezone = NULL;
1677 if (!is_numeric($timezone)) {
1678 $strtimezone = $timezone;
1681 if (empty($format)) {
1682 $format = get_string('strftimedaydatetime', 'langconfig');
1685 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1687 } else if ($fixday) {
1688 $formatnoday = str_replace('%d', 'DD', $format);
1689 $fixday = ($formatnoday != $format);
1692 $date += dst_offset_on($date, $strtimezone);
1694 $timezone = get_user_timezone_offset($timezone);
1696 if (abs($timezone) > 13) { /// Server time
1698 $datestring = strftime($formatnoday, $date);
1699 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
1700 $datestring = str_replace('DD', $daystring, $datestring);
1702 $datestring = strftime($format, $date);
1705 $date += (int)($timezone * 3600);
1707 $datestring = gmstrftime($formatnoday, $date);
1708 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
1709 $datestring = str_replace('DD', $daystring, $datestring);
1711 $datestring = gmstrftime($format, $date);
1715 /// If we are running under Windows convert from windows encoding to UTF-8
1716 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1718 if ($CFG->ostype == 'WINDOWS') {
1719 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1720 $textlib = textlib_get_instance();
1721 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1729 * Given a $time timestamp in GMT (seconds since epoch),
1730 * returns an array that represents the date in user time
1732 * @todo Finish documenting this function
1734 * @param int $time Timestamp in GMT
1735 * @param float $timezone ?
1736 * @return array An array that represents the date in user time
1738 function usergetdate($time, $timezone=99) {
1740 $strtimezone = NULL;
1741 if (!is_numeric($timezone)) {
1742 $strtimezone = $timezone;
1745 $timezone = get_user_timezone_offset($timezone);
1747 if (abs($timezone) > 13) { // Server time
1748 return getdate($time);
1751 // There is no gmgetdate so we use gmdate instead
1752 $time += dst_offset_on($time, $strtimezone);
1753 $time += intval((float)$timezone * HOURSECS);
1755 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
1757 //be careful to ensure the returned array matches that produced by getdate() above
1760 $getdate['weekday'],
1767 $getdate['minutes'],
1769 ) = explode('_', $datestring);
1775 * Given a GMT timestamp (seconds since epoch), offsets it by
1776 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1779 * @param int $date Timestamp in GMT
1780 * @param float $timezone
1783 function usertime($date, $timezone=99) {
1785 $timezone = get_user_timezone_offset($timezone);
1787 if (abs($timezone) > 13) {
1790 return $date - (int)($timezone * HOURSECS);
1794 * Given a time, return the GMT timestamp of the most recent midnight
1795 * for the current user.
1797 * @param int $date Timestamp in GMT
1798 * @param float $timezone Defaults to user's timezone
1799 * @return int Returns a GMT timestamp
1801 function usergetmidnight($date, $timezone=99) {
1803 $userdate = usergetdate($date, $timezone);
1805 // Time of midnight of this user's day, in GMT
1806 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1811 * Returns a string that prints the user's timezone
1813 * @param float $timezone The user's timezone
1816 function usertimezone($timezone=99) {
1818 $tz = get_user_timezone($timezone);
1820 if (!is_float($tz)) {
1824 if(abs($tz) > 13) { // Server time
1825 return get_string('serverlocaltime');
1828 if($tz == intval($tz)) {
1829 // Don't show .0 for whole hours
1846 * Returns a float which represents the user's timezone difference from GMT in hours
1847 * Checks various settings and picks the most dominant of those which have a value
1851 * @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
1854 function get_user_timezone_offset($tz = 99) {
1858 $tz = get_user_timezone($tz);
1860 if (is_float($tz)) {
1863 $tzrecord = get_timezone_record($tz);
1864 if (empty($tzrecord)) {
1867 return (float)$tzrecord->gmtoff / HOURMINS;
1872 * Returns an int which represents the systems's timezone difference from GMT in seconds
1875 * @param mixed $tz timezone
1876 * @return int if found, false is timezone 99 or error
1878 function get_timezone_offset($tz) {
1885 if (is_numeric($tz)) {
1886 return intval($tz * 60*60);
1889 if (!$tzrecord = get_timezone_record($tz)) {
1892 return intval($tzrecord->gmtoff * 60);
1896 * Returns a float or a string which denotes the user's timezone
1897 * 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)
1898 * means that for this timezone there are also DST rules to be taken into account
1899 * Checks various settings and picks the most dominant of those which have a value
1903 * @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
1906 function get_user_timezone($tz = 99) {
1911 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1912 isset($USER->timezone) ? $USER->timezone : 99,
1913 isset($CFG->timezone) ? $CFG->timezone : 99,
1918 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
1919 $tz = $next['value'];
1922 return is_numeric($tz) ? (float) $tz : $tz;
1926 * Returns cached timezone record for given $timezonename
1930 * @param string $timezonename
1931 * @return mixed timezonerecord object or false
1933 function get_timezone_record($timezonename) {
1935 static $cache = NULL;
1937 if ($cache === NULL) {
1941 if (isset($cache[$timezonename])) {
1942 return $cache[$timezonename];
1945 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
1946 WHERE name = ? ORDER BY year DESC', array($timezonename), true);
1950 * Build and store the users Daylight Saving Time (DST) table
1955 * @param mixed $from_year Start year for the table, defaults to 1971
1956 * @param mixed $to_year End year for the table, defaults to 2035
1957 * @param mixed $strtimezone
1960 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
1961 global $CFG, $SESSION, $DB;
1963 $usertz = get_user_timezone($strtimezone);
1965 if (is_float($usertz)) {
1966 // Trivial timezone, no DST
1970 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1971 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1972 unset($SESSION->dst_offsets);
1973 unset($SESSION->dst_range);
1976 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1977 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1978 // This will be the return path most of the time, pretty light computationally
1982 // Reaching here means we either need to extend our table or create it from scratch
1984 // Remember which TZ we calculated these changes for
1985 $SESSION->dst_offsettz = $usertz;
1987 if(empty($SESSION->dst_offsets)) {
1988 // If we 're creating from scratch, put the two guard elements in there
1989 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1991 if(empty($SESSION->dst_range)) {
1992 // If creating from scratch
1993 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1994 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1996 // Fill in the array with the extra years we need to process
1997 $yearstoprocess = array();
1998 for($i = $from; $i <= $to; ++$i) {
1999 $yearstoprocess[] = $i;
2002 // Take note of which years we have processed for future calls
2003 $SESSION->dst_range = array($from, $to);
2006 // If needing to extend the table, do the same
2007 $yearstoprocess = array();
2009 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2010 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2012 if($from < $SESSION->dst_range[0]) {
2013 // Take note of which years we need to process and then note that we have processed them for future calls
2014 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2015 $yearstoprocess[] = $i;
2017 $SESSION->dst_range[0] = $from;
2019 if($to > $SESSION->dst_range[1]) {
2020 // Take note of which years we need to process and then note that we have processed them for future calls
2021 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2022 $yearstoprocess[] = $i;
2024 $SESSION->dst_range[1] = $to;
2028 if(empty($yearstoprocess)) {
2029 // This means that there was a call requesting a SMALLER range than we have already calculated
2033 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2034 // Also, the array is sorted in descending timestamp order!
2038 static $presets_cache = array();
2039 if (!isset($presets_cache[$usertz])) {
2040 $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');
2042 if(empty($presets_cache[$usertz])) {
2046 // Remove ending guard (first element of the array)
2047 reset($SESSION->dst_offsets);
2048 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2050 // Add all required change timestamps
2051 foreach($yearstoprocess as $y) {
2052 // Find the record which is in effect for the year $y
2053 foreach($presets_cache[$usertz] as $year => $preset) {
2059 $changes = dst_changes_for_year($y, $preset);
2061 if($changes === NULL) {
2064 if($changes['dst'] != 0) {
2065 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2067 if($changes['std'] != 0) {
2068 $SESSION->dst_offsets[$changes['std']] = 0;
2072 // Put in a guard element at the top
2073 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2074 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2077 krsort($SESSION->dst_offsets);
2083 * Calculates the required DST change and returns a Timestamp Array
2087 * @param mixed $year Int or String Year to focus on
2088 * @param object $timezone Instatiated Timezone object
2089 * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
2091 function dst_changes_for_year($year, $timezone) {
2093 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2097 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2098 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2100 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2101 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2103 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2104 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2106 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2107 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2108 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2110 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2111 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2113 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2117 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2120 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2123 function dst_offset_on($time, $strtimezone = NULL) {
2126 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2130 reset($SESSION->dst_offsets);
2131 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2132 if($from <= $time) {
2137 // This is the normal return path
2138 if($offset !== NULL) {
2142 // Reaching this point means we haven't calculated far enough, do it now:
2143 // Calculate extra DST changes if needed and recurse. The recursion always
2144 // moves toward the stopping condition, so will always end.
2147 // We need a year smaller than $SESSION->dst_range[0]
2148 if($SESSION->dst_range[0] == 1971) {
2151 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2152 return dst_offset_on($time, $strtimezone);
2155 // We need a year larger than $SESSION->dst_range[1]
2156 if($SESSION->dst_range[1] == 2035) {
2159 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2160 return dst_offset_on($time, $strtimezone);
2167 * @todo Document what this function does
2168 * @param int $startday
2169 * @param int $weekday
2174 function find_day_in_month($startday, $weekday, $month, $year) {
2176 $daysinmonth = days_in_month($month, $year);
2178 if($weekday == -1) {
2179 // Don't care about weekday, so return:
2180 // abs($startday) if $startday != -1
2181 // $daysinmonth otherwise
2182 return ($startday == -1) ? $daysinmonth : abs($startday);
2185 // From now on we 're looking for a specific weekday
2187 // Give "end of month" its actual value, since we know it
2188 if($startday == -1) {
2189 $startday = -1 * $daysinmonth;
2192 // Starting from day $startday, the sign is the direction
2196 $startday = abs($startday);
2197 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2199 // This is the last such weekday of the month
2200 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2201 if($lastinmonth > $daysinmonth) {
2205 // Find the first such weekday <= $startday
2206 while($lastinmonth > $startday) {
2210 return $lastinmonth;
2215 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2217 $diff = $weekday - $indexweekday;
2222 // This is the first such weekday of the month equal to or after $startday
2223 $firstfromindex = $startday + $diff;
2225 return $firstfromindex;
2231 * Calculate the number of days in a given month
2233 * @param int $month The month whose day count is sought
2234 * @param int $year The year of the month whose day count is sought
2237 function days_in_month($month, $year) {
2238 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2242 * Calculate the position in the week of a specific calendar day
2244 * @param int $day The day of the date whose position in the week is sought
2245 * @param int $month The month of the date whose position in the week is sought
2246 * @param int $year The year of the date whose position in the week is sought
2249 function dayofweek($day, $month, $year) {
2250 // I wonder if this is any different from
2251 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2252 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2255 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2258 * Returns full login url.
2260 * @return string login url
2262 function get_login_url() {
2265 $url = "$CFG->wwwroot/login/index.php";
2267 if (!empty($CFG->loginhttps)) {
2268 $url = str_replace('http:', 'https:', $url);
2275 * This function checks that the current user is logged in and has the
2276 * required privileges
2278 * This function checks that the current user is logged in, and optionally
2279 * whether they are allowed to be in a particular course and view a particular
2281 * If they are not logged in, then it redirects them to the site login unless
2282 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2283 * case they are automatically logged in as guests.
2284 * If $courseid is given and the user is not enrolled in that course then the
2285 * user is redirected to the course enrolment page.
2286 * If $cm is given and the course module is hidden and the user is not a teacher
2287 * in the course then the user is redirected to the course home page.
2289 * When $cm parameter specified, this function sets page layout to 'module'.
2290 * You need to change it manually later if some other layout needed.
2292 * @param mixed $courseorid id of the course or course object
2293 * @param bool $autologinguest default true
2294 * @param object $cm course module object
2295 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2296 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2297 * in order to keep redirects working properly. MDL-14495
2298 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2299 * @return mixed Void, exit, and die depending on path
2301 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2302 global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2304 // setup global $COURSE, themes, language and locale
2305 if (!empty($courseorid)) {
2306 if (is_object($courseorid)) {
2307 $course = $courseorid;
2308 } else if ($courseorid == SITEID) {
2309 $course = clone($SITE);
2311 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2314 if ($cm->course != $course->id) {
2315 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2317 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2318 $PAGE->set_pagelayout('incourse');
2320 $PAGE->set_course($course); // set's up global $COURSE
2323 // do not touch global $COURSE via $PAGE->set_course(),
2324 // the reasons is we need to be able to call require_login() at any time!!
2327 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2331 // If the user is not even logged in yet then make sure they are
2332 if (!isloggedin()) {
2333 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2334 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2335 // misconfigured site guest, just redirect to login page
2336 redirect(get_login_url());
2337 exit; // never reached
2339 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2340 complete_user_login($guest, false);
2341 $USER->autologinguest = true;
2342 $SESSION->lang = $lang;
2344 //NOTE: $USER->site check was obsoleted by session test cookie,
2345 // $USER->confirmed test is in login/index.php
2346 if ($preventredirect) {
2347 throw new require_login_exception('You are not logged in');
2350 if ($setwantsurltome) {
2351 // TODO: switch to PAGE->url
2352 $SESSION->wantsurl = $FULLME;
2354 if (!empty($_SERVER['HTTP_REFERER'])) {
2355 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2357 redirect(get_login_url());
2358 exit; // never reached
2362 // loginas as redirection if needed
2363 if ($course->id != SITEID and session_is_loggedinas()) {
2364 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2365 if ($USER->loginascontext->instanceid != $course->id) {
2366 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2371 // check whether the user should be changing password (but only if it is REALLY them)
2372 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2373 $userauth = get_auth_plugin($USER->auth);
2374 if ($userauth->can_change_password() and !$preventredirect) {
2375 $SESSION->wantsurl = $FULLME;
2376 if ($changeurl = $userauth->change_password_url()) {
2377 //use plugin custom url
2378 redirect($changeurl);
2380 //use moodle internal method
2381 if (empty($CFG->loginhttps)) {
2382 redirect($CFG->wwwroot .'/login/change_password.php');
2384 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2385 redirect($wwwroot .'/login/change_password.php');
2389 print_error('nopasswordchangeforced', 'auth');
2393 // Check that the user account is properly set up
2394 if (user_not_fully_set_up($USER)) {
2395 if ($preventredirect) {
2396 throw new require_login_exception('User not fully set-up');
2398 $SESSION->wantsurl = $FULLME;
2399 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2402 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2405 // Do not bother admins with any formalities
2406 if (is_siteadmin()) {
2407 //set accesstime or the user will appear offline which messes up messaging
2408 user_accesstime_log($course->id);
2412 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2413 if (!$USER->policyagreed and !is_siteadmin()) {
2414 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2415 if ($preventredirect) {
2416 throw new require_login_exception('Policy not agreed');
2418 $SESSION->wantsurl = $FULLME;
2419 redirect($CFG->wwwroot .'/user/policy.php');
2420 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2421 if ($preventredirect) {
2422 throw new require_login_exception('Policy not agreed');
2424 $SESSION->wantsurl = $FULLME;
2425 redirect($CFG->wwwroot .'/user/policy.php');
2429 // Fetch the system context, the course context, and prefetch its child contexts
2430 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2431 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2433 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2438 // If the site is currently under maintenance, then print a message
2439 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2440 if ($preventredirect) {
2441 throw new require_login_exception('Maintenance in progress');
2444 print_maintenance_message();
2447 // make sure the course itself is not hidden
2448 if ($course->id == SITEID) {
2449 // frontpage can not be hidden
2451 if (is_role_switched($course->id)) {
2452 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2454 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2455 // originally there was also test of parent category visibility,
2456 // BUT is was very slow in complex queries involving "my courses"
2457 // now it is also possible to simply hide all courses user is not enrolled in :-)
2458 if ($preventredirect) {
2459 throw new require_login_exception('Course is hidden');
2461 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2466 // is the user enrolled?
2467 if ($course->id == SITEID) {
2468 // everybody is enrolled on the frontpage
2471 if (session_is_loggedinas()) {
2472 // Make sure the REAL person can access this course first
2473 $realuser = session_get_realuser();
2474 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2475 if ($preventredirect) {
2476 throw new require_login_exception('Invalid course login-as access');
2478 echo $OUTPUT->header();
2479 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2483 // very simple enrolment caching - changes in course setting are not reflected immediately
2484 if (!isset($USER->enrol)) {
2485 $USER->enrol = array();
2486 $USER->enrol['enrolled'] = array();
2487 $USER->enrol['tempguest'] = array();
2492 if (is_viewing($coursecontext, $USER)) {
2493 // ok, no need to mess with enrol
2497 if (isset($USER->enrol['enrolled'][$course->id])) {
2498 if ($USER->enrol['enrolled'][$course->id] == 0) {
2500 } else if ($USER->enrol['enrolled'][$course->id] > time()) {
2504 unset($USER->enrol['enrolled'][$course->id]);
2507 if (isset($USER->enrol['tempguest'][$course->id])) {
2508 if ($USER->enrol['tempguest'][$course->id] == 0) {
2510 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2514 unset($USER->enrol['tempguest'][$course->id]);
2515 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2521 } else if (is_enrolled($coursecontext, $USER, '', true)) {
2522 // active participants may always access
2523 // TODO: refactor this into some new function
2525 $sql = "SELECT MAX(ue.timeend)
2526 FROM {user_enrolments} ue
2527 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2528 JOIN {user} u ON u.id = ue.userid
2529 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0
2530 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
2531 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE,
2532 'userid'=>$USER->id, 'courseid'=>$coursecontext->instanceid, 'now1'=>$now, 'now2'=>$now);
2533 $until = $DB->get_field_sql($sql, $params);
2534 if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) {
2535 $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD;
2538 $USER->enrol['enrolled'][$course->id] = $until;
2541 // remove traces of previous temp guest access
2542 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2545 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2546 $enrols = enrol_get_plugins(true);
2547 // first ask all enabled enrol instances in course if they want to auto enrol user
2548 foreach($instances as $instance) {
2549 if (!isset($enrols[$instance->enrol])) {
2552 // Get a duration for the guestaccess, a timestamp in the future or false.
2553 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2554 if ($until !== false) {
2555 $USER->enrol['enrolled'][$course->id] = $until;
2556 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2561 // if not enrolled yet try to gain temporary guest access
2563 foreach($instances as $instance) {
2564 if (!isset($enrols[$instance->enrol])) {
2567 // Get a duration for the guestaccess, a timestamp in the future or false.
2568 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2569 if ($until !== false) {
2570 $USER->enrol['tempguest'][$course->id] = $until;
2580 if ($preventredirect) {
2581 throw new require_login_exception('Not enrolled');
2583 $SESSION->wantsurl = $FULLME;
2584 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2589 if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2590 if ($preventredirect) {
2591 throw new require_login_exception('Activity is hidden');
2593 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2596 // groupmembersonly access control
2597 if (!empty($CFG->enablegroupmembersonly) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2598 if (isguestuser() or !groups_has_membership($cm)) {
2599 if ($preventredirect) {
2600 throw new require_login_exception('Not member of a group');
2602 print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
2606 // Conditional activity access control
2607 if (!empty($CFG->enableavailability) and $cm) {
2608 // TODO: this is going to work with login-as-user, sorry!
2609 // We cache conditional access in session
2610 if (!isset($SESSION->conditionaccessok)) {
2611 $SESSION->conditionaccessok = array();
2613 // If you have been allowed into the module once then you are allowed
2614 // in for rest of session, no need to do conditional checks
2615 if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
2616 // Get condition info (does a query for the availability table)
2617 require_once($CFG->libdir.'/conditionlib.php');
2618 $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
2619 // Check condition for user (this will do a query if the availability
2620 // information depends on grade or completion information)
2621 if ($ci->is_available($junk) || has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2622 $SESSION->conditionaccessok[$cm->id] = true;
2624 print_error('activityiscurrentlyhidden');
2629 // Finally access granted, update lastaccess times
2630 user_accesstime_log($course->id);
2635 * This function just makes sure a user is logged out.
2639 function require_logout() {
2645 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2647 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2648 foreach($authsequence as $authname) {
2649 $authplugin = get_auth_plugin($authname);
2650 $authplugin->prelogout_hook();
2654 events_trigger('user_logout', $params);
2655 session_get_instance()->terminate_current();
2660 * Weaker version of require_login()
2662 * This is a weaker version of {@link require_login()} which only requires login
2663 * when called from within a course rather than the site page, unless
2664 * the forcelogin option is turned on.
2665 * @see require_login()
2668 * @param mixed $courseorid The course object or id in question
2669 * @param bool $autologinguest Allow autologin guests if that is wanted
2670 * @param object $cm Course activity module if known
2671 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2672 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2673 * in order to keep redirects working properly. MDL-14495
2674 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2677 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2678 global $CFG, $PAGE, $SITE;
2679 if (!empty($CFG->forcelogin)) {
2680 // login required for both SITE and courses
2681 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2683 } else if (!empty($cm) and !$cm->visible) {
2684 // always login for hidden activities
2685 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2687 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2688 or (!is_object($courseorid) and $courseorid == SITEID)) {
2689 //login for SITE not required
2690 if ($cm and empty($cm->visible)) {
2691 // hidden activities are not accessible without login
2692 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2693 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2694 // not-logged-in users do not have any group membership
2695 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2697 // We still need to instatiate PAGE vars properly so that things
2698 // that rely on it like navigation function correctly.
2699 if (!empty($courseorid)) {
2700 if (is_object($courseorid)) {
2701 $course = $courseorid;
2703 $course = clone($SITE);
2706 if ($cm->course != $course->id) {
2707 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2709 $PAGE->set_cm($cm, $course);
2710 $PAGE->set_pagelayout('incourse');
2712 $PAGE->set_course($course);
2715 // If $PAGE->course, and hence $PAGE->context, have not already been set
2716 // up properly, set them up now.
2717 $PAGE->set_course($PAGE->course);
2719 //TODO: verify conditional activities here
2720 user_accesstime_log(SITEID);
2725 // course login always required
2726 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2731 * Require key login. Function terminates with error if key not found or incorrect.
2737 * @uses NO_MOODLE_COOKIES
2738 * @uses PARAM_ALPHANUM
2739 * @param string $script unique script identifier
2740 * @param int $instance optional instance id
2741 * @return int Instance ID
2743 function require_user_key_login($script, $instance=null) {
2744 global $USER, $SESSION, $CFG, $DB;
2746 if (!NO_MOODLE_COOKIES) {
2747 print_error('sessioncookiesdisable');
2751 @session_write_close();
2753 $keyvalue = required_param('key', PARAM_ALPHANUM);
2755 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2756 print_error('invalidkey');
2759 if (!empty($key->validuntil) and $key->validuntil < time()) {
2760 print_error('expiredkey');
2763 if ($key->iprestriction) {
2764 $remoteaddr = getremoteaddr(null);
2765 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2766 print_error('ipmismatch');
2770 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2771 print_error('invaliduserid');
2774 /// emulate normal session
2775 session_set_user($user);
2777 /// note we are not using normal login
2778 if (!defined('USER_KEY_LOGIN')) {
2779 define('USER_KEY_LOGIN', true);
2782 /// return instance id - it might be empty
2783 return $key->instance;
2787 * Creates a new private user access key.
2790 * @param string $script unique target identifier
2791 * @param int $userid
2792 * @param int $instance optional instance id
2793 * @param string $iprestriction optional ip restricted access
2794 * @param timestamp $validuntil key valid only until given data
2795 * @return string access key value
2797 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2800 $key = new stdClass();
2801 $key->script = $script;
2802 $key->userid = $userid;
2803 $key->instance = $instance;
2804 $key->iprestriction = $iprestriction;
2805 $key->validuntil = $validuntil;
2806 $key->timecreated = time();
2808 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
2809 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
2811 $key->value = md5($userid.'_'.time().random_string(40));
2813 $DB->insert_record('user_private_key', $key);
2818 * Delete the user's new private user access keys for a particular script.
2821 * @param string $script unique target identifier
2822 * @param int $userid
2825 function delete_user_key($script,$userid) {
2827 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
2831 * Gets a private user access key (and creates one if one doesn't exist).
2834 * @param string $script unique target identifier
2835 * @param int $userid
2836 * @param int $instance optional instance id
2837 * @param string $iprestriction optional ip restricted access
2838 * @param timestamp $validuntil key valid only until given data
2839 * @return string access key value
2841 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2844 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
2845 'instance'=>$instance, 'iprestriction'=>$iprestriction,
2846 'validuntil'=>$validuntil))) {
2849 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
2855 * Modify the user table by setting the currently logged in user's
2856 * last login to now.
2860 * @return bool Always returns true
2862 function update_user_login_times() {
2865 $user = new stdClass();
2866 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2867 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2869 $user->id = $USER->id;
2871 $DB->update_record('user', $user);
2876 * Determines if a user has completed setting up their account.
2878 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
2881 function user_not_fully_set_up($user) {
2882 if (isguestuser($user)) {
2885 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
2889 * Check whether the user has exceeded the bounce threshold
2893 * @param user $user A {@link $USER} object
2894 * @return bool true=>User has exceeded bounce threshold
2896 function over_bounce_threshold($user) {
2899 if (empty($CFG->handlebounces)) {
2903 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2907 // set sensible defaults
2908 if (empty($CFG->minbounces)) {
2909 $CFG->minbounces = 10;
2911 if (empty($CFG->bounceratio)) {
2912 $CFG->bounceratio = .20;
2916 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2917 $bouncecount = $bounce->value;
2919 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2920 $sendcount = $send->value;
2922 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2926 * Used to increment or reset email sent count
2929 * @param user $user object containing an id
2930 * @param bool $reset will reset the count to 0
2933 function set_send_count($user,$reset=false) {
2936 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2940 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2941 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2942 $DB->update_record('user_preferences', $pref);
2944 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2946 $pref = new stdClass();
2947 $pref->name = 'email_send_count';
2949 $pref->userid = $user->id;
2950 $DB->insert_record('user_preferences', $pref, false);
2955 * Increment or reset user's email bounce count
2958 * @param user $user object containing an id
2959 * @param bool $reset will reset the count to 0
2961 function set_bounce_count($user,$reset=false) {
2964 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2965 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2966 $DB->update_record('user_preferences', $pref);
2968 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2970 $pref = new stdClass();
2971 $pref->name = 'email_bounce_count';
2973 $pref->userid = $user->id;
2974 $DB->insert_record('user_preferences', $pref, false);
2979 * Keeps track of login attempts
2983 function update_login_count() {
2988 if (empty($SESSION->logincount)) {
2989 $SESSION->logincount = 1;
2991 $SESSION->logincount++;
2994 if ($SESSION->logincount > $max_logins) {
2995 unset($SESSION->wantsurl);
2996 print_error('errortoomanylogins');
3001 * Resets login attempts
3005 function reset_login_count() {
3008 $SESSION->logincount = 0;
3012 * Returns reference to full info about modules in course (including visibility).
3013 * Cached and as fast as possible (0 or 1 db query).
3018 * @uses CONTEXT_MODULE
3019 * @uses MAX_MODINFO_CACHE_SIZE
3020 * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
3021 * @param int $userid Defaults to current user id
3022 * @return mixed courseinfo object or nothing if resetting
3024 function &get_fast_modinfo(&$course, $userid=0) {
3025 global $CFG, $USER, $DB;
3026 require_once($CFG->dirroot.'/course/lib.php');
3028 if (!empty($CFG->enableavailability)) {
3029 require_once($CFG->libdir.'/conditionlib.php');
3032 static $cache = array();
3034 if ($course === 'reset') {
3037 return $nothing; // we must return some reference
3040 if (empty($userid)) {
3041 $userid = $USER->id;
3044 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
3045 return $cache[$course->id];
3048 if (!property_exists($course, 'modinfo')) {
3049 debugging('Coding problem - missing course modinfo property in get_fast_modinfo() call');
3052 if (empty($course->modinfo)) {
3053 // no modinfo yet - load it
3054 rebuild_course_cache($course->id);
3055 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
3058 $modinfo = new stdClass();
3059 $modinfo->courseid = $course->id;
3060 $modinfo->userid = $userid;
3061 $modinfo->sections = array();
3062 $modinfo->cms = array();
3063 $modinfo->instances = array();
3064 $modinfo->groups = null; // loaded only when really needed - the only one db query
3066 $info = unserialize($course->modinfo);
3067 if (!is_array($info)) {
3068 // hmm, something is wrong - lets try to fix it
3069 rebuild_course_cache($course->id);
3070 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
3071 $info = unserialize($course->modinfo);
3072 if (!is_array($info)) {
3078 // detect if upgrade required
3079 $first = reset($info);
3080 if (!isset($first->id)) {
3081 rebuild_course_cache($course->id);
3082 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
3083 $info = unserialize($course->modinfo);
3084 if (!is_array($info)) {
3090 $modlurals = array();
3092 // If we haven't already preloaded contexts for the course, do it now
3093 preload_course_contexts($course->id);
3095 foreach ($info as $mod) {
3096 if (empty($mod->name)) {
3097 // something is wrong here
3100 // reconstruct minimalistic $cm
3101 $cm = new stdClass();
3103 $cm->instance = $mod->id;
3104 $cm->course = $course->id;
3105 $cm->modname = $mod->mod;
3106 $cm->idnumber = $mod->idnumber;
3107 $cm->name = $mod->name;
3108 $cm->visible = $mod->visible;
3109 $cm->sectionnum = $mod->section;
3110 $cm->groupmode = $mod->groupmode;
3111 $cm->groupingid = $mod->groupingid;
3112 $cm->groupmembersonly = $mod->groupmembersonly;
3113 $cm->indent = $mod->indent;
3114 $cm->completion = $mod->completion;
3115 $cm->extra = isset($mod->extra) ? $mod->extra : '';
3116 $cm->icon = isset($mod->icon) ? $mod->icon : '';
3117 $cm->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
3118 $cm->uservisible = true;
3119 if (!empty($CFG->enableavailability)) {
3120 // We must have completion information from modinfo. If it's not
3121 // there, cache needs rebuilding
3122 if(!isset($mod->availablefrom)) {
3123 debugging('enableavailability option was changed; rebuilding '.
3124 'cache for course '.$course->id);
3125 rebuild_course_cache($course->id,true);
3126 // Re-enter this routine to do it all properly
3127 return get_fast_modinfo($course, $userid);
3129 $cm->availablefrom = $mod->availablefrom;
3130 $cm->availableuntil = $mod->availableuntil;
3131 $cm->showavailability = $mod->showavailability;
3132 $cm->conditionscompletion = $mod->conditionscompletion;
3133 $cm->conditionsgrade = $mod->conditionsgrade;
3136 // preload long names plurals and also check module is installed properly
3137 if (!isset($modlurals[$cm->modname])) {
3138 if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
3141 $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
3143 $cm->modplural = $modlurals[$cm->modname];
3144 $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id);
3146 if (!empty($CFG->enableavailability)) {
3147 // Unfortunately the next call really wants to call
3148 // get_fast_modinfo, but that would be recursive, so we fake up a
3149 // modinfo for it already
3150 if (empty($minimalmodinfo)) { //TODO: this is suspicious (skodak)
3151 $minimalmodinfo = new stdClass();
3152 $minimalmodinfo->cms = array();
3153 foreach($info as $mod) {
3154 if (empty($mod->name)) {
3155 // something is wrong here
3158 $minimalcm = new stdClass();
3159 $minimalcm->id = $mod->cm;
3160 $minimalcm->name = $mod->name;
3161 $minimalmodinfo->cms[$minimalcm->id]=$minimalcm;
3165 // Get availability information
3166 $ci = new condition_info($cm);
3167 $cm->available = $ci->is_available($cm->availableinfo, true, $userid, $minimalmodinfo);
3169 $cm->available = true;
3171 if ((!$cm->visible or !$cm->available) and !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
3172 $cm->uservisible = false;
3174 } else if (!empty($CFG->enablegroupmembersonly) and !empty($cm->groupmembersonly)
3175 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
3176 if (is_null($modinfo->groups)) {
3177 $modinfo->groups = groups_get_user_groups($course->id, $userid);
3179 if (empty($modinfo->groups[$cm->groupingid])) {
3180 $cm->uservisible = false;
3184 if (!isset($modinfo->instances[$cm->modname])) {
3185 $modinfo->instances[$cm->modname] = array();
3187 $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
3188 $modinfo->cms[$cm->id] =& $cm;
3190 // reconstruct sections
3191 if (!isset($modinfo->sections[$cm->sectionnum])) {
3192 $modinfo->sections[$cm->sectionnum] = array();
3194 $modinfo->sections[$cm->sectionnum][] = $cm->id;
3199 unset($cache[$course->id]); // prevent potential reference problems when switching users
3200 $cache[$course->id] = $modinfo;
3202 // Ensure cache does not use too much RAM
3203 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
3206 unset($cache[$key]);
3209 return $cache[$course->id];
3213 * Determines if the currently logged in user is in editing mode.
3214 * Note: originally this function had $userid parameter - it was not usable anyway
3216 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3217 * @todo Deprecated function remove when ready
3220 * @uses DEBUG_DEVELOPER
3223 function isediting() {
3225 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3226 return $PAGE->user_is_editing();
3230 * Determines if the logged in user is currently moving an activity
3233 * @param int $courseid The id of the course being tested
3236 function ismoving($courseid) {
3239 if (!empty($USER->activitycopy)) {
3240 return ($USER->activitycopycourse == $courseid);
3246 * Returns a persons full name
3248 * Given an object containing firstname and lastname
3249 * values, this function returns a string with the
3250 * full name of the person.
3251 * The result may depend on system settings
3252 * or language. 'override' will force both names
3253 * to be used even if system settings specify one.
3257 * @param object $user A {@link $USER} object to get full name of
3258 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3261 function fullname($user, $override=false) {
3262 global $CFG, $SESSION;
3264 if (!isset($user->firstname) and !isset($user->lastname)) {
3269 if (!empty($CFG->forcefirstname)) {
3270 $user->firstname = $CFG->forcefirstname;
3272 if (!empty($CFG->forcelastname)) {
3273 $user->lastname = $CFG->forcelastname;
3277 if (!empty($SESSION->fullnamedisplay)) {
3278 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3281 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3282 return $user->firstname .' '. $user->lastname;
3284 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3285 return $user->lastname .' '. $user->firstname;
3287 } else if ($CFG->fullnamedisplay == 'firstname') {
3289 return get_string('fullnamedisplay', '', $user);
3291 return $user->firstname;
3295 return get_string('fullnamedisplay', '', $user);
3299 * Returns whether a given authentication plugin exists.
3302 * @param string $auth Form of authentication to check for. Defaults to the
3303 * global setting in {@link $CFG}.
3304 * @return boolean Whether the plugin is available.
3306 function exists_auth_plugin($auth) {
3309 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3310 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3316 * Checks if a given plugin is in the list of enabled authentication plugins.
3318 * @param string $auth Authentication plugin.
3319 * @return boolean Whether the plugin is enabled.
3321 function is_enabled_auth($auth) {
3326 $enabled = get_enabled_auth_plugins();
3328 return in_array($auth, $enabled);
3332 * Returns an authentication plugin instance.
3335 * @param string $auth name of authentication plugin
3336 * @return auth_plugin_base An instance of the required authentication plugin.
3338 function get_auth_plugin($auth) {
3341 // check the plugin exists first
3342 if (! exists_auth_plugin($auth)) {
3343 print_error('authpluginnotfound', 'debug', '', $auth);
3346 // return auth plugin instance
3347 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3348 $class = "auth_plugin_$auth";
3353 * Returns array of active auth plugins.
3355 * @param bool $fix fix $CFG->auth if needed
3358 function get_enabled_auth_plugins($fix=false) {
3361 $default = array('manual', 'nologin');
3363 if (empty($CFG->auth)) {
3366 $auths = explode(',', $CFG->auth);
3370 $auths = array_unique($auths);
3371 foreach($auths as $k=>$authname) {
3372 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3376 $newconfig = implode(',', $auths);
3377 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3378 set_config('auth', $newconfig);
3382 return (array_merge($default, $auths));
3386 * Returns true if an internal authentication method is being used.
3387 * if method not specified then, global default is assumed
3389 * @param string $auth Form of authentication required
3392 function is_internal_auth($auth) {
3393 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3394 return $authplugin->is_internal();
3398 * Returns true if the user is a 'restored' one
3400 * Used in the login process to inform the user
3401 * and allow him/her to reset the password
3405 * @param string $username username to be checked
3408 function is_restored_user($username) {
3411 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3415 * Returns an array of user fields
3417 * @return array User field/column names
3419 function get_user_fieldnames() {
3422 $fieldarray = $DB->get_columns('user');
3423 unset($fieldarray['id']);
3424 $fieldarray = array_keys($fieldarray);
3430 * Creates a bare-bones user record
3432 * @todo Outline auth types and provide code example
3434 * @param string $username New user's username to add to record
3435 * @param string $password New user's password to add to record
3436 * @param string $auth Form of authentication required
3437 * @return stdClass A complete user object
3439 function create_user_record($username, $password, $auth = 'manual') {
3442 //just in case check text case
3443 $username = trim(moodle_strtolower($username));
3445 $authplugin = get_auth_plugin($auth);
3447 $newuser = new stdClass();
3449 if ($newinfo = $authplugin->get_userinfo($username)) {
3450 $newinfo = truncate_userinfo($newinfo);
3451 foreach ($newinfo as $key => $value){
3452 $newuser->$key = $value;
3456 if (!empty($newuser->email)) {
3457 if (email_is_not_allowed($newuser->email)) {
3458 unset($newuser->email);
3462 if (!isset($newuser->city)) {
3463 $newuser->city = '';
3466 $newuser->auth = $auth;
3467 $newuser->username = $username;
3470 // user CFG lang for user if $newuser->lang is empty
3471 // or $user->lang is not an installed language
3472 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3473 $newuser->lang = $CFG->lang;
3475 $newuser->confirmed = 1;
3476 $newuser->lastip = getremoteaddr();
3477 $newuser->timemodified = time();
3478 $newuser->mnethostid = $CFG->mnet_localhost_id;
3480 $newuser->id = $DB->insert_record('user', $newuser);
3481 $user = get_complete_user_data('id', $newuser->id);
3482 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3483 set_user_preference('auth_forcepasswordchange', 1, $user);
3485 update_internal_user_password($user, $password);
3487 // fetch full user record for the event, the complete user data contains too much info
3488 // and we want to be consistent with other places that trigger this event
3489 events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
3495 * Will update a local user record from an external source.
3496 * (MNET users can not be updated using this method!)
3498 * @param string $username user's username to update the record
3499 * @return stdClass A complete user object
3501 function update_user_record($username) {
3504 $username = trim(moodle_strtolower($username)); /// just in case check text case
3506 $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
3508 $userauth = get_auth_plugin($oldinfo->auth);
3510 if ($newinfo = $userauth->get_userinfo($username)) {
3511 $newinfo = truncate_userinfo($newinfo);
3512 foreach ($newinfo as $key => $value){
3513 $key = strtolower($key);
3514 if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id'
3515 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3516 // unknown or must not be changed
3519 $confval = $userauth->config->{'field_updatelocal_' . $key};
3520 $lockval = $userauth->config->{'field_lock_' . $key};
3521 if (empty($confval) || empty($lockval)) {
3524 if ($confval === 'onlogin') {
3525 // MDL-4207 Don't overwrite modified user profile values with
3526 // empty LDAP values when 'unlocked if empty' is set. The purpose
3527 // of the setting 'unlocked if empty' is to allow the user to fill
3528 // in a value for the selected field _if LDAP is giving
3529 // nothing_ for this field. Thus it makes sense to let this value
3530 // stand in until LDAP is giving a value for this field.
3531 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3532 if ((string)$oldinfo->$key !== (string)$value) {
3533 $newuser[$key] = (string)$value;
3539 $newuser['id'] = $oldinfo->id;
3540 $DB->update_record('user', $newuser);
3541 // fetch full user record for the event, the complete user data contains too much info
3542 // and we want to be consistent with other places that trigger this event
3543 events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id)));
3547 return get_complete_user_data('id', $oldinfo->id);
3551 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3552 * which may have large fields
3554 * @todo Add vartype handling to ensure $info is an array
3556 * @param array $info Array of user properties to truncate if needed
3557 * @return array The now truncated information that was passed in
3559 function truncate_userinfo($info) {
3560 // define the limits
3570 'institution' => 40,
3578 $textlib = textlib_get_instance();
3579 // apply where needed
3580 foreach (array_keys($info) as $key) {
3581 if (!empty($limit[$key])) {
3582 $info[$key] = trim($textlib->substr($info[$key],0, $limit[$key]));
3590 * Marks user deleted in internal user database and notifies the auth plugin.
3591 * Also unenrols user from all roles and does other cleanup.
3593 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3595 * @param object $user User object before delete
3596 * @return boolean always true
3598 function delete_user($user) {
3600 require_once($CFG->libdir.'/grouplib.php');
3601 require_once($CFG->libdir.'/gradelib.php');
3602 require_once($CFG->dirroot.'/message/lib.php');
3603 require_once($CFG->dirroot.'/tag/lib.php');
3605 // delete all grades - backup is kept in grade_grades_history table
3606 grade_user_delete($user->id);
3608 //move unread messages from this user to read
3609 message_move_userfrom_unread2read($user->id);
3611 // TODO: remove from cohorts using standard API here
3614 tag_set('user', $user->id, array());
3616 // unconditionally unenrol from all courses
3617 enrol_user_delete($user);
3619 // unenrol from all roles in all contexts
3620 role_unassign_all(array('userid'=>$user->id)); // this might be slow but it is really needed - modules might do some extra cleanup!
3622 //now do a brute force cleanup
3624 // remove from all cohorts
3625 $DB->delete_records('cohort_members', array('userid'=>$user->id));
3627 // remove from all groups
3628 $DB->delete_records('groups_members', array('userid'=>$user->id));
3630 // brute force unenrol from all courses
3631 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
3633 // purge user preferences
3634 $DB->delete_records('user_preferences', array('userid'=>$user->id));
3636 // purge user extra profile info
3637 $DB->delete_records('user_info_data', array('userid'=>$user->id));
3639 // last course access not necessary either
3640 $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
3642 // now do a final accesslib cleanup - removes all role assignments in user context and context itself
3643 delete_context(CONTEXT_USER, $user->id);
3645 // workaround for bulk deletes of users with the same email address
3646 $delname = "$user->email.".time();
3647 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3651 // mark internal user record as "deleted"
3652 $updateuser = new stdClass();
3653 $updateuser->id = $user->id;
3654 $updateuser->deleted = 1;
3655 $updateuser->username = $delname; // Remember it just in case
3656 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
3657 $updateuser->idnumber = ''; // Clear this field to free it up
3658 $updateuser->timemodified = time();
3660 $DB->update_record('user', $updateuser);
3662 // notify auth plugin - do not block the delete even when plugin fails
3663 $authplugin = get_auth_plugin($user->auth);
3664 $authplugin->user_delete($user);
3666 // any plugin that needs to cleanup should register this event
3667 events_trigger('user_deleted', $user);
3673 * Retrieve the guest user object
3677 * @return user A {@link $USER} object
3679 function guest_user() {
3682 if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
3683 $newuser->confirmed = 1;
3684 $newuser->lang = $CFG->lang;