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 except the discarding of the invalid utf-8 characters
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_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
277 * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
278 * America/Port-au-Prince)
280 define('PARAM_TIMEZONE', 'timezone');
283 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
285 define('PARAM_CLEANFILE', 'file');
290 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
292 define('VALUE_REQUIRED', 1);
295 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
297 define('VALUE_OPTIONAL', 2);
300 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
302 define('VALUE_DEFAULT', 0);
305 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
307 define('NULL_NOT_ALLOWED', false);
310 * NULL_ALLOWED - the parameter can be set to null in the database
312 define('NULL_ALLOWED', true);
316 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
318 define('PAGE_COURSE_VIEW', 'course-view');
320 /** Get remote addr constant */
321 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
322 /** Get remote addr constant */
323 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
325 /// Blog access level constant declaration ///
326 define ('BLOG_USER_LEVEL', 1);
327 define ('BLOG_GROUP_LEVEL', 2);
328 define ('BLOG_COURSE_LEVEL', 3);
329 define ('BLOG_SITE_LEVEL', 4);
330 define ('BLOG_GLOBAL_LEVEL', 5);
335 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
336 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
337 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
339 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
341 define('TAG_MAX_LENGTH', 50);
343 /// Password policy constants ///
344 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
345 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
346 define ('PASSWORD_DIGITS', '0123456789');
347 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
349 /// Feature constants ///
350 // Used for plugin_supports() to report features that are, or are not, supported by a module.
352 /** True if module can provide a grade */
353 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
354 /** True if module supports outcomes */
355 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
357 /** True if module has code to track whether somebody viewed it */
358 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
359 /** True if module has custom completion rules */
360 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
362 /** True if module has no 'view' page (like label) */
363 define('FEATURE_NO_VIEW_LINK', 'viewlink');
364 /** True if module supports outcomes */
365 define('FEATURE_IDNUMBER', 'idnumber');
366 /** True if module supports groups */
367 define('FEATURE_GROUPS', 'groups');
368 /** True if module supports groupings */
369 define('FEATURE_GROUPINGS', 'groupings');
370 /** True if module supports groupmembersonly */
371 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
373 /** Type of module */
374 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
375 /** True if module supports intro editor */
376 define('FEATURE_MOD_INTRO', 'mod_intro');
377 /** True if module has default completion */
378 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
380 define('FEATURE_COMMENT', 'comment');
382 define('FEATURE_RATE', 'rate');
383 /** True if module supports backup/restore of moodle2 format */
384 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
386 /** Unspecified module archetype */
387 define('MOD_ARCHETYPE_OTHER', 0);
388 /** Resource-like type module */
389 define('MOD_ARCHETYPE_RESOURCE', 1);
390 /** Assignment module archetype */
391 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
394 * Security token used for allowing access
395 * from external application such as web services.
396 * Scripts do not use any session, performance is relatively
397 * low because we need to load access info in each request.
398 * Scripts are executed in parallel.
400 define('EXTERNAL_TOKEN_PERMANENT', 0);
403 * Security token used for allowing access
404 * of embedded applications, the code is executed in the
405 * active user session. Token is invalidated after user logs out.
406 * Scripts are executed serially - normal session locking is used.
408 define('EXTERNAL_TOKEN_EMBEDDED', 1);
411 * The home page should be the site home
413 define('HOMEPAGE_SITE', 0);
415 * The home page should be the users my page
417 define('HOMEPAGE_MY', 1);
419 * The home page can be chosen by the user
421 define('HOMEPAGE_USER', 2);
424 * Hub directory url (should be moodle.org)
426 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
430 * Moodle.org url (should be moodle.org)
432 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
435 * Moodle mobile app service name
437 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
439 /// PARAMETER HANDLING ////////////////////////////////////////////////////
442 * Returns a particular value for the named variable, taken from
443 * POST or GET. If the parameter doesn't exist then an error is
444 * thrown because we require this variable.
446 * This function should be used to initialise all required values
447 * in a script that are based on parameters. Usually it will be
449 * $id = required_param('id', PARAM_INT);
451 * Please note the $type parameter is now required,
452 * for now PARAM_CLEAN is used for backwards compatibility only.
454 * @param string $parname the name of the page parameter we want
455 * @param string $type expected type of parameter
458 function required_param($parname, $type) {
460 debugging('required_param() requires $type to be specified.');
461 $type = PARAM_CLEAN; // for now let's use this deprecated type
463 if (isset($_POST[$parname])) { // POST has precedence
464 $param = $_POST[$parname];
465 } else if (isset($_GET[$parname])) {
466 $param = $_GET[$parname];
468 print_error('missingparam', '', '', $parname);
471 return clean_param($param, $type);
475 * Returns a particular value for the named variable, taken from
476 * POST or GET, otherwise returning a given default.
478 * This function should be used to initialise all optional values
479 * in a script that are based on parameters. Usually it will be
481 * $name = optional_param('name', 'Fred', PARAM_TEXT);
483 * Please note $default and $type parameters are now required,
484 * for now PARAM_CLEAN is used for backwards compatibility only.
486 * @param string $parname the name of the page parameter we want
487 * @param mixed $default the default value to return if nothing is found
488 * @param string $type expected type of parameter
491 function optional_param($parname, $default, $type) {
493 debugging('optional_param() requires $default and $type to be specified.');
494 $type = PARAM_CLEAN; // for now let's use this deprecated type
496 if (!isset($default)) {
500 if (isset($_POST[$parname])) { // POST has precedence
501 $param = $_POST[$parname];
502 } else if (isset($_GET[$parname])) {
503 $param = $_GET[$parname];
508 return clean_param($param, $type);
512 * Strict validation of parameter values, the values are only converted
513 * to requested PHP type. Internally it is using clean_param, the values
514 * before and after cleaning must be equal - otherwise
515 * an invalid_parameter_exception is thrown.
516 * Objects and classes are not accepted.
518 * @param mixed $param
519 * @param int $type PARAM_ constant
520 * @param bool $allownull are nulls valid value?
521 * @param string $debuginfo optional debug information
522 * @return mixed the $param value converted to PHP type or invalid_parameter_exception
524 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
525 if (is_null($param)) {
526 if ($allownull == NULL_ALLOWED) {
529 throw new invalid_parameter_exception($debuginfo);
532 if (is_array($param) or is_object($param)) {
533 throw new invalid_parameter_exception($debuginfo);
536 $cleaned = clean_param($param, $type);
537 if ((string)$param !== (string)$cleaned) {
538 // conversion to string is usually lossless
539 throw new invalid_parameter_exception($debuginfo);
546 * Used by {@link optional_param()} and {@link required_param()} to
547 * clean the variables and/or cast to specific types, based on
550 * $course->format = clean_param($course->format, PARAM_ALPHA);
551 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
554 * @param mixed $param the variable we are cleaning
555 * @param int $type expected format of param after cleaning.
558 function clean_param($param, $type) {
562 if (is_array($param)) { // Let's loop
564 foreach ($param as $key => $value) {
565 $newparam[$key] = clean_param($value, $type);
571 case PARAM_RAW: // no cleaning at all
572 $param = fix_utf8($param);
575 case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
576 $param = fix_utf8($param);
579 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
580 // this is deprecated!, please use more specific type instead
581 if (is_numeric($param)) {
584 $param = fix_utf8($param);
585 return clean_text($param); // Sweep for scripts, etc
587 case PARAM_CLEANHTML: // clean html fragment
588 $param = fix_utf8($param);
589 $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
593 return (int)$param; // Convert to integer
597 return (float)$param; // Convert to float
599 case PARAM_ALPHA: // Remove everything not a-z
600 return preg_replace('/[^a-zA-Z]/i', '', $param);
602 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
603 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
605 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
606 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
608 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
609 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
611 case PARAM_SEQUENCE: // Remove everything not 0-9,
612 return preg_replace('/[^0-9,]/i', '', $param);
614 case PARAM_BOOL: // Convert to 1 or 0
615 $tempstr = strtolower($param);
616 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
618 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
621 $param = empty($param) ? 0 : 1;
625 case PARAM_NOTAGS: // Strip all tags
626 $param = fix_utf8($param);
627 return strip_tags($param);
629 case PARAM_TEXT: // leave only tags needed for multilang
630 $param = fix_utf8($param);
631 // if the multilang syntax is not correct we strip all tags
632 // because it would break xhtml strict which is required for accessibility standards
633 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
635 if (strpos($param, '</lang>') !== false) {
636 // old and future mutilang syntax
637 $param = strip_tags($param, '<lang>');
638 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
642 foreach ($matches[0] as $match) {
643 if ($match === '</lang>') {
651 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
662 } else if (strpos($param, '</span>') !== false) {
663 // current problematic multilang syntax
664 $param = strip_tags($param, '<span>');
665 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
669 foreach ($matches[0] as $match) {
670 if ($match === '</span>') {
678 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
690 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
691 return strip_tags($param);
693 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
694 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
696 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
697 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
699 case PARAM_FILE: // Strip all suspicious characters from filename
700 $param = fix_utf8($param);
701 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
702 $param = preg_replace('~\.\.+~', '', $param);
703 if ($param === '.') {
708 case PARAM_PATH: // Strip all suspicious characters from file path
709 $param = fix_utf8($param);
710 $param = str_replace('\\', '/', $param);
711 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
712 $param = preg_replace('~\.\.+~', '', $param);
713 $param = preg_replace('~//+~', '/', $param);
714 return preg_replace('~/(\./)+~', '/', $param);
716 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
717 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
718 // match ipv4 dotted quad
719 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
720 // confirm values are ok
724 || $match[4] > 255 ) {
725 // hmmm, what kind of dotted quad is this?
728 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
729 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
730 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
732 // all is ok - $param is respected
739 case PARAM_URL: // allow safe ftp, http, mailto urls
740 $param = fix_utf8($param);
741 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
742 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
743 // all is ok, param is respected
745 $param =''; // not really ok
749 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
750 $param = clean_param($param, PARAM_URL);
751 if (!empty($param)) {
752 if (preg_match(':^/:', $param)) {
753 // root-relative, ok!
754 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
755 // absolute, and matches our wwwroot
757 // relative - let's make sure there are no tricks
758 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
768 $param = trim($param);
769 // PEM formatted strings may contain letters/numbers and the symbols
773 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
774 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
775 list($wholething, $body) = $matches;
776 unset($wholething, $matches);
777 $b64 = clean_param($body, PARAM_BASE64);
779 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
787 if (!empty($param)) {
788 // PEM formatted strings may contain letters/numbers and the symbols
792 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
795 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
796 // Each line of base64 encoded data must be 64 characters in
797 // length, except for the last line which may be less than (or
798 // equal to) 64 characters long.
799 for ($i=0, $j=count($lines); $i < $j; $i++) {
801 if (64 < strlen($lines[$i])) {
807 if (64 != strlen($lines[$i])) {
811 return implode("\n",$lines);
817 $param = fix_utf8($param);
818 // Please note it is not safe to use the tag name directly anywhere,
819 // it must be processed with s(), urlencode() before embedding anywhere.
820 // remove some nasties
821 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
822 //convert many whitespace chars into one
823 $param = preg_replace('/\s+/', ' ', $param);
824 $textlib = textlib_get_instance();
825 $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
829 $param = fix_utf8($param);
830 $tags = explode(',', $param);
832 foreach ($tags as $tag) {
833 $res = clean_param($tag, PARAM_TAG);
839 return implode(',', $result);
844 case PARAM_CAPABILITY:
845 if (get_capability_info($param)) {
851 case PARAM_PERMISSION:
852 $param = (int)$param;
853 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
860 $param = clean_param($param, PARAM_SAFEDIR);
861 if (exists_auth_plugin($param)) {
868 $param = clean_param($param, PARAM_SAFEDIR);
869 if (get_string_manager()->translation_exists($param)) {
872 return ''; // Specified language is not installed or param malformed
876 $param = clean_param($param, PARAM_SAFEDIR);
877 if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
879 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
882 return ''; // Specified theme is not installed
886 $param = fix_utf8($param);
887 $param = str_replace(" " , "", $param);
888 $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
889 if (empty($CFG->extendedusernamechars)) {
890 // regular expression, eliminate all chars EXCEPT:
891 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
892 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
897 $param = fix_utf8($param);
898 if (validate_email($param)) {
905 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
911 case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
912 $param = fix_utf8($param);
913 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
914 if (preg_match($timezonepattern, $param)) {
920 default: // throw error, switched parameters in optional_param or another serious problem
921 print_error("unknownparamtype", '', '', $type);
926 * Makes sure the data is using valid utf8, invalid characters are discarded.
928 * Note: this function is not intended for full objects with methods and private properties.
930 * @param mixed $value
931 * @return mixed with proper utf-8 encoding
933 function fix_utf8($value) {
934 if (is_null($value) or $value === '') {
937 } else if (is_string($value)) {
938 if ((string)(int)$value === $value) {
942 return iconv('UTF-8', 'UTF-8//IGNORE', $value);
944 } else if (is_array($value)) {
945 foreach ($value as $k=>$v) {
946 $value[$k] = fix_utf8($v);
950 } else if (is_object($value)) {
951 $value = clone($value); // do not modify original
952 foreach ($value as $k=>$v) {
953 $value->$k = fix_utf8($v);
958 // this is some other type, no utf-8 here
964 * Return true if given value is integer or string with integer value
966 * @param mixed $value String or Int
967 * @return bool true if number, false if not
969 function is_number($value) {
970 if (is_int($value)) {
972 } else if (is_string($value)) {
973 return ((string)(int)$value) === $value;
980 * Returns host part from url
981 * @param string $url full url
982 * @return string host, null if not found
984 function get_host_from_url($url) {
985 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
993 * Tests whether anything was returned by text editor
995 * This function is useful for testing whether something you got back from
996 * the HTML editor actually contains anything. Sometimes the HTML editor
997 * appear to be empty, but actually you get back a <br> tag or something.
999 * @param string $string a string containing HTML.
1000 * @return boolean does the string contain any actual content - that is text,
1001 * images, objects, etc.
1003 function html_is_blank($string) {
1004 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1008 * Set a key in global configuration
1010 * Set a key/value pair in both this session's {@link $CFG} global variable
1011 * and in the 'config' database table for future sessions.
1013 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1014 * In that case it doesn't affect $CFG.
1016 * A NULL value will delete the entry.
1020 * @param string $name the key to set
1021 * @param string $value the value to set (without magic quotes)
1022 * @param string $plugin (optional) the plugin scope, default NULL
1023 * @return bool true or exception
1025 function set_config($name, $value, $plugin=NULL) {
1028 if (empty($plugin)) {
1029 if (!array_key_exists($name, $CFG->config_php_settings)) {
1030 // So it's defined for this invocation at least
1031 if (is_null($value)) {
1034 $CFG->$name = (string)$value; // settings from db are always strings
1038 if ($DB->get_field('config', 'name', array('name'=>$name))) {
1039 if ($value === null) {
1040 $DB->delete_records('config', array('name'=>$name));
1042 $DB->set_field('config', 'value', $value, array('name'=>$name));
1045 if ($value !== null) {
1046 $config = new stdClass();
1047 $config->name = $name;
1048 $config->value = $value;
1049 $DB->insert_record('config', $config, false);
1053 } else { // plugin scope
1054 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1055 if ($value===null) {
1056 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1058 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1061 if ($value !== null) {
1062 $config = new stdClass();
1063 $config->plugin = $plugin;
1064 $config->name = $name;
1065 $config->value = $value;
1066 $DB->insert_record('config_plugins', $config, false);
1075 * Get configuration values from the global config table
1076 * or the config_plugins table.
1078 * If called with one parameter, it will load all the config
1079 * variables for one plugin, and return them as an object.
1081 * If called with 2 parameters it will return a string single
1082 * value or false if the value is not found.
1084 * @param string $plugin full component name
1085 * @param string $name default NULL
1086 * @return mixed hash-like object or single value, return false no config found
1088 function get_config($plugin, $name = NULL) {
1091 // normalise component name
1092 if ($plugin === 'moodle' or $plugin === 'core') {
1096 if (!empty($name)) { // the user is asking for a specific value
1097 if (!empty($plugin)) {
1098 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1099 // setting forced in config file
1100 return $CFG->forced_plugin_settings[$plugin][$name];
1102 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1105 if (array_key_exists($name, $CFG->config_php_settings)) {
1106 // setting force in config file
1107 return $CFG->config_php_settings[$name];
1109 return $DB->get_field('config', 'value', array('name'=>$name));
1114 // the user is after a recordset
1116 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1117 if (isset($CFG->forced_plugin_settings[$plugin])) {
1118 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1119 if (is_null($v) or is_array($v) or is_object($v)) {
1120 // we do not want any extra mess here, just real settings that could be saved in db
1121 unset($localcfg[$n]);
1123 //convert to string as if it went through the DB
1124 $localcfg[$n] = (string)$v;
1129 return (object)$localcfg;
1135 // this part is not really used any more, but anyway...
1136 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1137 foreach($CFG->config_php_settings as $n=>$v) {
1138 if (is_null($v) or is_array($v) or is_object($v)) {
1139 // we do not want any extra mess here, just real settings that could be saved in db
1140 unset($localcfg[$n]);
1142 //convert to string as if it went through the DB
1143 $localcfg[$n] = (string)$v;
1146 return (object)$localcfg;
1151 * Removes a key from global configuration
1153 * @param string $name the key to set
1154 * @param string $plugin (optional) the plugin scope
1156 * @return boolean whether the operation succeeded.
1158 function unset_config($name, $plugin=NULL) {
1161 if (empty($plugin)) {
1163 $DB->delete_records('config', array('name'=>$name));
1165 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1172 * Remove all the config variables for a given plugin.
1174 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1175 * @return boolean whether the operation succeeded.
1177 function unset_all_config_for_plugin($plugin) {
1179 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1180 $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
1185 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1187 * All users are verified if they still have the necessary capability.
1189 * @param string $value the value of the config setting.
1190 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1191 * @param bool $include admins, include administrators
1192 * @return array of user objects.
1194 function get_users_from_config($value, $capability, $includeadmins = true) {
1197 if (empty($value) or $value === '$@NONE@$') {
1201 // we have to make sure that users still have the necessary capability,
1202 // it should be faster to fetch them all first and then test if they are present
1203 // instead of validating them one-by-one
1204 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1205 if ($includeadmins) {
1206 $admins = get_admins();
1207 foreach ($admins as $admin) {
1208 $users[$admin->id] = $admin;
1212 if ($value === '$@ALL@$') {
1216 $result = array(); // result in correct order
1217 $allowed = explode(',', $value);
1218 foreach ($allowed as $uid) {
1219 if (isset($users[$uid])) {
1220 $user = $users[$uid];
1221 $result[$user->id] = $user;
1230 * Invalidates browser caches and cached data in temp
1233 function purge_all_caches() {
1236 reset_text_filters_cache();
1237 js_reset_all_caches();
1238 theme_reset_all_caches();
1239 get_string_manager()->reset_caches();
1241 // purge all other caches: rss, simplepie, etc.
1242 remove_dir($CFG->dataroot.'/cache', true);
1244 // make sure cache dir is writable, throws exception if not
1245 make_upload_directory('cache');
1247 // hack: this script may get called after the purifier was initialised,
1248 // but we do not want to verify repeatedly this exists in each call
1249 make_upload_directory('cache/htmlpurifier');
1255 * Get volatile flags
1257 * @param string $type
1258 * @param int $changedsince default null
1259 * @return records array
1261 function get_cache_flags($type, $changedsince=NULL) {
1264 $params = array('type'=>$type, 'expiry'=>time());
1265 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1266 if ($changedsince !== NULL) {
1267 $params['changedsince'] = $changedsince;
1268 $sqlwhere .= " AND timemodified > :changedsince";
1272 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1273 foreach ($flags as $flag) {
1274 $cf[$flag->name] = $flag->value;
1281 * Get volatile flags
1283 * @param string $type
1284 * @param string $name
1285 * @param int $changedsince default null
1286 * @return records array
1288 function get_cache_flag($type, $name, $changedsince=NULL) {
1291 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1293 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1294 if ($changedsince !== NULL) {
1295 $params['changedsince'] = $changedsince;
1296 $sqlwhere .= " AND timemodified > :changedsince";
1299 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1303 * Set a volatile flag
1305 * @param string $type the "type" namespace for the key
1306 * @param string $name the key to set
1307 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1308 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1309 * @return bool Always returns true
1311 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1314 $timemodified = time();
1315 if ($expiry===NULL || $expiry < $timemodified) {
1316 $expiry = $timemodified + 24 * 60 * 60;
1318 $expiry = (int)$expiry;
1321 if ($value === NULL) {
1322 unset_cache_flag($type,$name);
1326 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1327 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1328 return true; //no need to update; helps rcache too
1331 $f->expiry = $expiry;
1332 $f->timemodified = $timemodified;
1333 $DB->update_record('cache_flags', $f);
1335 $f = new stdClass();
1336 $f->flagtype = $type;
1339 $f->expiry = $expiry;
1340 $f->timemodified = $timemodified;
1341 $DB->insert_record('cache_flags', $f);
1347 * Removes a single volatile flag
1350 * @param string $type the "type" namespace for the key
1351 * @param string $name the key to set
1354 function unset_cache_flag($type, $name) {
1356 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1361 * Garbage-collect volatile flags
1363 * @return bool Always returns true
1365 function gc_cache_flags() {
1367 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1371 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1374 * Refresh user preference cache. This is used most often for $USER
1375 * object that is stored in session, but it also helps with performance in cron script.
1377 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1379 * @param stdClass $user user object, preferences are preloaded into ->preference property
1380 * @param int $cachelifetime cache life time on the current page (ins seconds)
1383 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1385 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1387 if (!isset($user->id)) {
1388 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1391 if (empty($user->id) or isguestuser($user->id)) {
1392 // No permanent storage for not-logged-in users and guest
1393 if (!isset($user->preference)) {
1394 $user->preference = array();
1401 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1402 // Already loaded at least once on this page. Are we up to date?
1403 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1404 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1407 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1408 // no change since the lastcheck on this page
1409 $user->preference['_lastloaded'] = $timenow;
1414 // OK, so we have to reload all preferences
1415 $loadedusers[$user->id] = true;
1416 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1417 $user->preference['_lastloaded'] = $timenow;
1421 * Called from set/delete_user_preferences, so that the prefs can
1422 * be correctly reloaded in different sessions.
1424 * NOTE: internal function, do not call from other code.
1426 * @param integer $userid the user whose prefs were changed.
1429 function mark_user_preferences_changed($userid) {
1432 if (empty($userid) or isguestuser($userid)) {
1433 // no cache flags for guest and not-logged-in users
1437 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1441 * Sets a preference for the specified user.
1443 * If user object submitted, 'preference' property contains the preferences cache.
1445 * @param string $name The key to set as preference for the specified user
1446 * @param string $value The value to set for the $name key in the specified user's record,
1447 * null means delete current value
1448 * @param stdClass|int $user A moodle user object or id, null means current user
1449 * @return bool always true or exception
1451 function set_user_preference($name, $value, $user = null) {
1454 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1455 throw new coding_exception('Invalid preference name in set_user_preference() call');
1458 if (is_null($value)) {
1459 // null means delete current
1460 return unset_user_preference($name, $user);
1461 } else if (is_object($value)) {
1462 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1463 } else if (is_array($value)) {
1464 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1466 $value = (string)$value;
1468 if (is_null($user)) {
1470 } else if (isset($user->id)) {
1471 // $user is valid object
1472 } else if (is_numeric($user)) {
1473 $user = (object)array('id'=>(int)$user);
1475 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1478 check_user_preferences_loaded($user);
1480 if (empty($user->id) or isguestuser($user->id)) {
1481 // no permanent storage for not-logged-in users and guest
1482 $user->preference[$name] = $value;
1486 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1487 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1488 // preference already set to this value
1491 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1494 $preference = new stdClass();
1495 $preference->userid = $user->id;
1496 $preference->name = $name;
1497 $preference->value = $value;
1498 $DB->insert_record('user_preferences', $preference);
1501 // update value in cache
1502 $user->preference[$name] = $value;
1504 // set reload flag for other sessions
1505 mark_user_preferences_changed($user->id);
1511 * Sets a whole array of preferences for the current user
1513 * If user object submitted, 'preference' property contains the preferences cache.
1515 * @param array $prefarray An array of key/value pairs to be set
1516 * @param stdClass|int $user A moodle user object or id, null means current user
1517 * @return bool always true or exception
1519 function set_user_preferences(array $prefarray, $user = null) {
1520 foreach ($prefarray as $name => $value) {
1521 set_user_preference($name, $value, $user);
1527 * Unsets a preference completely by deleting it from the database
1529 * If user object submitted, 'preference' property contains the preferences cache.
1531 * @param string $name The key to unset as preference for the specified user
1532 * @param stdClass|int $user A moodle user object or id, null means current user
1533 * @return bool always true or exception
1535 function unset_user_preference($name, $user = null) {
1538 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1539 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1542 if (is_null($user)) {
1544 } else if (isset($user->id)) {
1545 // $user is valid object
1546 } else if (is_numeric($user)) {
1547 $user = (object)array('id'=>(int)$user);
1549 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1552 check_user_preferences_loaded($user);
1554 if (empty($user->id) or isguestuser($user->id)) {
1555 // no permanent storage for not-logged-in user and guest
1556 unset($user->preference[$name]);
1561 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1563 // delete the preference from cache
1564 unset($user->preference[$name]);
1566 // set reload flag for other sessions
1567 mark_user_preferences_changed($user->id);
1573 * Used to fetch user preference(s)
1575 * If no arguments are supplied this function will return
1576 * all of the current user preferences as an array.
1578 * If a name is specified then this function
1579 * attempts to return that particular preference value. If
1580 * none is found, then the optional value $default is returned,
1583 * If user object submitted, 'preference' property contains the preferences cache.
1585 * @param string $name Name of the key to use in finding a preference value
1586 * @param mixed $default Value to be returned if the $name key is not set in the user preferences
1587 * @param stdClass|int $user A moodle user object or id, null means current user
1588 * @return mixed string value or default
1590 function get_user_preferences($name = null, $default = null, $user = null) {
1593 if (is_null($name)) {
1595 } else if (is_numeric($name) or $name === '_lastloaded') {
1596 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1599 if (is_null($user)) {
1601 } else if (isset($user->id)) {
1602 // $user is valid object
1603 } else if (is_numeric($user)) {
1604 $user = (object)array('id'=>(int)$user);
1606 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1609 check_user_preferences_loaded($user);
1612 return $user->preference; // All values
1613 } else if (isset($user->preference[$name])) {
1614 return $user->preference[$name]; // The single string value
1616 return $default; // Default value (null if not specified)
1620 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1623 * Given date parts in user time produce a GMT timestamp.
1625 * @todo Finish documenting this function
1626 * @param int $year The year part to create timestamp of
1627 * @param int $month The month part to create timestamp of
1628 * @param int $day The day part to create timestamp of
1629 * @param int $hour The hour part to create timestamp of
1630 * @param int $minute The minute part to create timestamp of
1631 * @param int $second The second part to create timestamp of
1632 * @param mixed $timezone Timezone modifier, if 99 then use default user's timezone
1633 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1634 * applied only if timezone is 99 or string.
1635 * @return int timestamp
1637 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1639 //save input timezone, required for dst offset check.
1640 $passedtimezone = $timezone;
1642 $timezone = get_user_timezone_offset($timezone);
1644 if (abs($timezone) > 13) { //server time
1645 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1647 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1648 $time = usertime($time, $timezone);
1650 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1651 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1652 $time -= dst_offset_on($time, $passedtimezone);
1661 * Format a date/time (seconds) as weeks, days, hours etc as needed
1663 * Given an amount of time in seconds, returns string
1664 * formatted nicely as weeks, days, hours etc as needed
1670 * @param int $totalsecs Time in seconds
1671 * @param object $str Should be a time object
1672 * @return string A nicely formatted date/time string
1674 function format_time($totalsecs, $str=NULL) {
1676 $totalsecs = abs($totalsecs);
1678 if (!$str) { // Create the str structure the slow way
1679 $str->day = get_string('day');
1680 $str->days = get_string('days');
1681 $str->hour = get_string('hour');
1682 $str->hours = get_string('hours');
1683 $str->min = get_string('min');
1684 $str->mins = get_string('mins');
1685 $str->sec = get_string('sec');
1686 $str->secs = get_string('secs');
1687 $str->year = get_string('year');
1688 $str->years = get_string('years');
1692 $years = floor($totalsecs/YEARSECS);
1693 $remainder = $totalsecs - ($years*YEARSECS);
1694 $days = floor($remainder/DAYSECS);
1695 $remainder = $totalsecs - ($days*DAYSECS);
1696 $hours = floor($remainder/HOURSECS);
1697 $remainder = $remainder - ($hours*HOURSECS);
1698 $mins = floor($remainder/MINSECS);
1699 $secs = $remainder - ($mins*MINSECS);
1701 $ss = ($secs == 1) ? $str->sec : $str->secs;
1702 $sm = ($mins == 1) ? $str->min : $str->mins;
1703 $sh = ($hours == 1) ? $str->hour : $str->hours;
1704 $sd = ($days == 1) ? $str->day : $str->days;
1705 $sy = ($years == 1) ? $str->year : $str->years;
1713 if ($years) $oyears = $years .' '. $sy;
1714 if ($days) $odays = $days .' '. $sd;
1715 if ($hours) $ohours = $hours .' '. $sh;
1716 if ($mins) $omins = $mins .' '. $sm;
1717 if ($secs) $osecs = $secs .' '. $ss;
1719 if ($years) return trim($oyears .' '. $odays);
1720 if ($days) return trim($odays .' '. $ohours);
1721 if ($hours) return trim($ohours .' '. $omins);
1722 if ($mins) return trim($omins .' '. $osecs);
1723 if ($secs) return $osecs;
1724 return get_string('now');
1728 * Returns a formatted string that represents a date in user time
1730 * Returns a formatted string that represents a date in user time
1731 * <b>WARNING: note that the format is for strftime(), not date().</b>
1732 * Because of a bug in most Windows time libraries, we can't use
1733 * the nicer %e, so we have to use %d which has leading zeroes.
1734 * A lot of the fuss in the function is just getting rid of these leading
1735 * zeroes as efficiently as possible.
1737 * If parameter fixday = true (default), then take off leading
1738 * zero from %d, else maintain it.
1740 * @param int $date the timestamp in UTC, as obtained from the database.
1741 * @param string $format strftime format. You should probably get this using
1742 * get_string('strftime...', 'langconfig');
1743 * @param mixed $timezone by default, uses the user's time zone. if numeric and
1744 * not 99 then daylight saving will not be added.
1745 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1746 * If false then the leading zero is maintained.
1747 * @return string the formatted date/time.
1749 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1753 if (empty($format)) {
1754 $format = get_string('strftimedaydatetime', 'langconfig');
1757 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1759 } else if ($fixday) {
1760 $formatnoday = str_replace('%d', 'DD', $format);
1761 $fixday = ($formatnoday != $format);
1764 //add daylight saving offset for string timezones only, as we can't get dst for
1765 //float values. if timezone is 99 (user default timezone), then try update dst.
1766 if ((99 == $timezone) || !is_numeric($timezone)) {
1767 $date += dst_offset_on($date, $timezone);
1770 $timezone = get_user_timezone_offset($timezone);
1772 if (abs($timezone) > 13) { /// Server time
1774 $datestring = strftime($formatnoday, $date);
1775 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
1776 $datestring = str_replace('DD', $daystring, $datestring);
1778 $datestring = strftime($format, $date);
1781 $date += (int)($timezone * 3600);
1783 $datestring = gmstrftime($formatnoday, $date);
1784 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
1785 $datestring = str_replace('DD', $daystring, $datestring);
1787 $datestring = gmstrftime($format, $date);
1791 /// If we are running under Windows convert from windows encoding to UTF-8
1792 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1794 if ($CFG->ostype == 'WINDOWS') {
1795 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1796 $textlib = textlib_get_instance();
1797 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1805 * Given a $time timestamp in GMT (seconds since epoch),
1806 * returns an array that represents the date in user time
1808 * @todo Finish documenting this function
1810 * @param int $time Timestamp in GMT
1811 * @param mixed $timezone offset time with timezone, if float and not 99, then no
1812 * dst offset is applyed
1813 * @return array An array that represents the date in user time
1815 function usergetdate($time, $timezone=99) {
1817 //save input timezone, required for dst offset check.
1818 $passedtimezone = $timezone;
1820 $timezone = get_user_timezone_offset($timezone);
1822 if (abs($timezone) > 13) { // Server time
1823 return getdate($time);
1826 //add daylight saving offset for string timezones only, as we can't get dst for
1827 //float values. if timezone is 99 (user default timezone), then try update dst.
1828 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
1829 $time += dst_offset_on($time, $passedtimezone);
1832 $time += intval((float)$timezone * HOURSECS);
1834 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
1836 //be careful to ensure the returned array matches that produced by getdate() above
1839 $getdate['weekday'],
1846 $getdate['minutes'],
1848 ) = explode('_', $datestring);
1854 * Given a GMT timestamp (seconds since epoch), offsets it by
1855 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1858 * @param int $date Timestamp in GMT
1859 * @param float $timezone
1862 function usertime($date, $timezone=99) {
1864 $timezone = get_user_timezone_offset($timezone);
1866 if (abs($timezone) > 13) {
1869 return $date - (int)($timezone * HOURSECS);
1873 * Given a time, return the GMT timestamp of the most recent midnight
1874 * for the current user.
1876 * @param int $date Timestamp in GMT
1877 * @param float $timezone Defaults to user's timezone
1878 * @return int Returns a GMT timestamp
1880 function usergetmidnight($date, $timezone=99) {
1882 $userdate = usergetdate($date, $timezone);
1884 // Time of midnight of this user's day, in GMT
1885 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1890 * Returns a string that prints the user's timezone
1892 * @param float $timezone The user's timezone
1895 function usertimezone($timezone=99) {
1897 $tz = get_user_timezone($timezone);
1899 if (!is_float($tz)) {
1903 if(abs($tz) > 13) { // Server time
1904 return get_string('serverlocaltime');
1907 if($tz == intval($tz)) {
1908 // Don't show .0 for whole hours
1925 * Returns a float which represents the user's timezone difference from GMT in hours
1926 * Checks various settings and picks the most dominant of those which have a value
1930 * @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
1933 function get_user_timezone_offset($tz = 99) {
1937 $tz = get_user_timezone($tz);
1939 if (is_float($tz)) {
1942 $tzrecord = get_timezone_record($tz);
1943 if (empty($tzrecord)) {
1946 return (float)$tzrecord->gmtoff / HOURMINS;
1951 * Returns an int which represents the systems's timezone difference from GMT in seconds
1954 * @param mixed $tz timezone
1955 * @return int if found, false is timezone 99 or error
1957 function get_timezone_offset($tz) {
1964 if (is_numeric($tz)) {
1965 return intval($tz * 60*60);
1968 if (!$tzrecord = get_timezone_record($tz)) {
1971 return intval($tzrecord->gmtoff * 60);
1975 * Returns a float or a string which denotes the user's timezone
1976 * 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)
1977 * means that for this timezone there are also DST rules to be taken into account
1978 * Checks various settings and picks the most dominant of those which have a value
1982 * @param mixed $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
1985 function get_user_timezone($tz = 99) {
1990 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1991 isset($USER->timezone) ? $USER->timezone : 99,
1992 isset($CFG->timezone) ? $CFG->timezone : 99,
1997 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
1998 $tz = $next['value'];
2001 return is_numeric($tz) ? (float) $tz : $tz;
2005 * Returns cached timezone record for given $timezonename
2009 * @param string $timezonename
2010 * @return mixed timezonerecord object or false
2012 function get_timezone_record($timezonename) {
2014 static $cache = NULL;
2016 if ($cache === NULL) {
2020 if (isset($cache[$timezonename])) {
2021 return $cache[$timezonename];
2024 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2025 WHERE name = ? ORDER BY year DESC', array($timezonename), true);
2029 * Build and store the users Daylight Saving Time (DST) table
2034 * @param mixed $from_year Start year for the table, defaults to 1971
2035 * @param mixed $to_year End year for the table, defaults to 2035
2036 * @param mixed $strtimezone, if null or 99 then user's default timezone is used
2039 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2040 global $CFG, $SESSION, $DB;
2042 $usertz = get_user_timezone($strtimezone);
2044 if (is_float($usertz)) {
2045 // Trivial timezone, no DST
2049 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2050 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2051 unset($SESSION->dst_offsets);
2052 unset($SESSION->dst_range);
2055 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2056 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2057 // This will be the return path most of the time, pretty light computationally
2061 // Reaching here means we either need to extend our table or create it from scratch
2063 // Remember which TZ we calculated these changes for
2064 $SESSION->dst_offsettz = $usertz;
2066 if(empty($SESSION->dst_offsets)) {
2067 // If we 're creating from scratch, put the two guard elements in there
2068 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2070 if(empty($SESSION->dst_range)) {
2071 // If creating from scratch
2072 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2073 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2075 // Fill in the array with the extra years we need to process
2076 $yearstoprocess = array();
2077 for($i = $from; $i <= $to; ++$i) {
2078 $yearstoprocess[] = $i;
2081 // Take note of which years we have processed for future calls
2082 $SESSION->dst_range = array($from, $to);
2085 // If needing to extend the table, do the same
2086 $yearstoprocess = array();
2088 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2089 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2091 if($from < $SESSION->dst_range[0]) {
2092 // Take note of which years we need to process and then note that we have processed them for future calls
2093 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2094 $yearstoprocess[] = $i;
2096 $SESSION->dst_range[0] = $from;
2098 if($to > $SESSION->dst_range[1]) {
2099 // Take note of which years we need to process and then note that we have processed them for future calls
2100 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2101 $yearstoprocess[] = $i;
2103 $SESSION->dst_range[1] = $to;
2107 if(empty($yearstoprocess)) {
2108 // This means that there was a call requesting a SMALLER range than we have already calculated
2112 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2113 // Also, the array is sorted in descending timestamp order!
2117 static $presets_cache = array();
2118 if (!isset($presets_cache[$usertz])) {
2119 $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');
2121 if(empty($presets_cache[$usertz])) {
2125 // Remove ending guard (first element of the array)
2126 reset($SESSION->dst_offsets);
2127 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2129 // Add all required change timestamps
2130 foreach($yearstoprocess as $y) {
2131 // Find the record which is in effect for the year $y
2132 foreach($presets_cache[$usertz] as $year => $preset) {
2138 $changes = dst_changes_for_year($y, $preset);
2140 if($changes === NULL) {
2143 if($changes['dst'] != 0) {
2144 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2146 if($changes['std'] != 0) {
2147 $SESSION->dst_offsets[$changes['std']] = 0;
2151 // Put in a guard element at the top
2152 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2153 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2156 krsort($SESSION->dst_offsets);
2162 * Calculates the required DST change and returns a Timestamp Array
2166 * @param mixed $year Int or String Year to focus on
2167 * @param object $timezone Instatiated Timezone object
2168 * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
2170 function dst_changes_for_year($year, $timezone) {
2172 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2176 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2177 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2179 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2180 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2182 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2183 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2185 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2186 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2187 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2189 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2190 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2192 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2196 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2197 * - Note: Daylight saving only works for string timezones and not for float.
2200 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2201 * @param mixed $strtimezone timezone for which offset is expected, if 99 or null
2202 * then user's default timezone is used.
2205 function dst_offset_on($time, $strtimezone = NULL) {
2208 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2212 reset($SESSION->dst_offsets);
2213 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2214 if($from <= $time) {
2219 // This is the normal return path
2220 if($offset !== NULL) {
2224 // Reaching this point means we haven't calculated far enough, do it now:
2225 // Calculate extra DST changes if needed and recurse. The recursion always
2226 // moves toward the stopping condition, so will always end.
2229 // We need a year smaller than $SESSION->dst_range[0]
2230 if($SESSION->dst_range[0] == 1971) {
2233 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2234 return dst_offset_on($time, $strtimezone);
2237 // We need a year larger than $SESSION->dst_range[1]
2238 if($SESSION->dst_range[1] == 2035) {
2241 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2242 return dst_offset_on($time, $strtimezone);
2249 * @todo Document what this function does
2250 * @param int $startday
2251 * @param int $weekday
2256 function find_day_in_month($startday, $weekday, $month, $year) {
2258 $daysinmonth = days_in_month($month, $year);
2260 if($weekday == -1) {
2261 // Don't care about weekday, so return:
2262 // abs($startday) if $startday != -1
2263 // $daysinmonth otherwise
2264 return ($startday == -1) ? $daysinmonth : abs($startday);
2267 // From now on we 're looking for a specific weekday
2269 // Give "end of month" its actual value, since we know it
2270 if($startday == -1) {
2271 $startday = -1 * $daysinmonth;
2274 // Starting from day $startday, the sign is the direction
2278 $startday = abs($startday);
2279 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2281 // This is the last such weekday of the month
2282 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2283 if($lastinmonth > $daysinmonth) {
2287 // Find the first such weekday <= $startday
2288 while($lastinmonth > $startday) {
2292 return $lastinmonth;
2297 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2299 $diff = $weekday - $indexweekday;
2304 // This is the first such weekday of the month equal to or after $startday
2305 $firstfromindex = $startday + $diff;
2307 return $firstfromindex;
2313 * Calculate the number of days in a given month
2315 * @param int $month The month whose day count is sought
2316 * @param int $year The year of the month whose day count is sought
2319 function days_in_month($month, $year) {
2320 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2324 * Calculate the position in the week of a specific calendar day
2326 * @param int $day The day of the date whose position in the week is sought
2327 * @param int $month The month of the date whose position in the week is sought
2328 * @param int $year The year of the date whose position in the week is sought
2331 function dayofweek($day, $month, $year) {
2332 // I wonder if this is any different from
2333 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2334 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2337 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2340 * Returns full login url.
2342 * @return string login url
2344 function get_login_url() {
2347 $url = "$CFG->wwwroot/login/index.php";
2349 if (!empty($CFG->loginhttps)) {
2350 $url = str_replace('http:', 'https:', $url);
2357 * This function checks that the current user is logged in and has the
2358 * required privileges
2360 * This function checks that the current user is logged in, and optionally
2361 * whether they are allowed to be in a particular course and view a particular
2363 * If they are not logged in, then it redirects them to the site login unless
2364 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2365 * case they are automatically logged in as guests.
2366 * If $courseid is given and the user is not enrolled in that course then the
2367 * user is redirected to the course enrolment page.
2368 * If $cm is given and the course module is hidden and the user is not a teacher
2369 * in the course then the user is redirected to the course home page.
2371 * When $cm parameter specified, this function sets page layout to 'module'.
2372 * You need to change it manually later if some other layout needed.
2374 * @param mixed $courseorid id of the course or course object
2375 * @param bool $autologinguest default true
2376 * @param object $cm course module object
2377 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2378 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2379 * in order to keep redirects working properly. MDL-14495
2380 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2381 * @return mixed Void, exit, and die depending on path
2383 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2384 global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2386 // setup global $COURSE, themes, language and locale
2387 if (!empty($courseorid)) {
2388 if (is_object($courseorid)) {
2389 $course = $courseorid;
2390 } else if ($courseorid == SITEID) {
2391 $course = clone($SITE);
2393 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2396 if ($cm->course != $course->id) {
2397 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2399 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2400 if (!($cm instanceof cm_info)) {
2401 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2402 // db queries so this is not really a performance concern, however it is obviously
2403 // better if you use get_fast_modinfo to get the cm before calling this.
2404 $modinfo = get_fast_modinfo($course);
2405 $cm = $modinfo->get_cm($cm->id);
2407 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2408 $PAGE->set_pagelayout('incourse');
2410 $PAGE->set_course($course); // set's up global $COURSE
2413 // do not touch global $COURSE via $PAGE->set_course(),
2414 // the reasons is we need to be able to call require_login() at any time!!
2417 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2421 // If the user is not even logged in yet then make sure they are
2422 if (!isloggedin()) {
2423 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2424 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2425 // misconfigured site guest, just redirect to login page
2426 redirect(get_login_url());
2427 exit; // never reached
2429 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2430 complete_user_login($guest);
2431 $USER->autologinguest = true;
2432 $SESSION->lang = $lang;
2434 //NOTE: $USER->site check was obsoleted by session test cookie,
2435 // $USER->confirmed test is in login/index.php
2436 if ($preventredirect) {
2437 throw new require_login_exception('You are not logged in');
2440 if ($setwantsurltome) {
2441 // TODO: switch to PAGE->url
2442 $SESSION->wantsurl = $FULLME;
2444 if (!empty($_SERVER['HTTP_REFERER'])) {
2445 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2447 redirect(get_login_url());
2448 exit; // never reached
2452 // loginas as redirection if needed
2453 if ($course->id != SITEID and session_is_loggedinas()) {
2454 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2455 if ($USER->loginascontext->instanceid != $course->id) {
2456 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2461 // check whether the user should be changing password (but only if it is REALLY them)
2462 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2463 $userauth = get_auth_plugin($USER->auth);
2464 if ($userauth->can_change_password() and !$preventredirect) {
2465 $SESSION->wantsurl = $FULLME;
2466 if ($changeurl = $userauth->change_password_url()) {
2467 //use plugin custom url
2468 redirect($changeurl);
2470 //use moodle internal method
2471 if (empty($CFG->loginhttps)) {
2472 redirect($CFG->wwwroot .'/login/change_password.php');
2474 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2475 redirect($wwwroot .'/login/change_password.php');
2479 print_error('nopasswordchangeforced', 'auth');
2483 // Check that the user account is properly set up
2484 if (user_not_fully_set_up($USER)) {
2485 if ($preventredirect) {
2486 throw new require_login_exception('User not fully set-up');
2488 $SESSION->wantsurl = $FULLME;
2489 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2492 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2495 // Do not bother admins with any formalities
2496 if (is_siteadmin()) {
2497 //set accesstime or the user will appear offline which messes up messaging
2498 user_accesstime_log($course->id);
2502 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2503 if (!$USER->policyagreed and !is_siteadmin()) {
2504 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2505 if ($preventredirect) {
2506 throw new require_login_exception('Policy not agreed');
2508 $SESSION->wantsurl = $FULLME;
2509 redirect($CFG->wwwroot .'/user/policy.php');
2510 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2511 if ($preventredirect) {
2512 throw new require_login_exception('Policy not agreed');
2514 $SESSION->wantsurl = $FULLME;
2515 redirect($CFG->wwwroot .'/user/policy.php');
2519 // Fetch the system context, the course context, and prefetch its child contexts
2520 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2521 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2523 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2528 // If the site is currently under maintenance, then print a message
2529 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2530 if ($preventredirect) {
2531 throw new require_login_exception('Maintenance in progress');
2534 print_maintenance_message();
2537 // make sure the course itself is not hidden
2538 if ($course->id == SITEID) {
2539 // frontpage can not be hidden
2541 if (is_role_switched($course->id)) {
2542 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2544 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2545 // originally there was also test of parent category visibility,
2546 // BUT is was very slow in complex queries involving "my courses"
2547 // now it is also possible to simply hide all courses user is not enrolled in :-)
2548 if ($preventredirect) {
2549 throw new require_login_exception('Course is hidden');
2551 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2556 // is the user enrolled?
2557 if ($course->id == SITEID) {
2558 // everybody is enrolled on the frontpage
2561 if (session_is_loggedinas()) {
2562 // Make sure the REAL person can access this course first
2563 $realuser = session_get_realuser();
2564 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2565 if ($preventredirect) {
2566 throw new require_login_exception('Invalid course login-as access');
2568 echo $OUTPUT->header();
2569 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2573 // very simple enrolment caching - changes in course setting are not reflected immediately
2574 if (!isset($USER->enrol)) {
2575 $USER->enrol = array();
2576 $USER->enrol['enrolled'] = array();
2577 $USER->enrol['tempguest'] = array();
2582 if (is_viewing($coursecontext, $USER)) {
2583 // ok, no need to mess with enrol
2587 if (isset($USER->enrol['enrolled'][$course->id])) {
2588 if ($USER->enrol['enrolled'][$course->id] == 0) {
2590 } else if ($USER->enrol['enrolled'][$course->id] > time()) {
2594 unset($USER->enrol['enrolled'][$course->id]);
2597 if (isset($USER->enrol['tempguest'][$course->id])) {
2598 if ($USER->enrol['tempguest'][$course->id] == 0) {
2600 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2604 unset($USER->enrol['tempguest'][$course->id]);
2605 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2611 } else if (is_enrolled($coursecontext, $USER, '', true)) {
2612 // active participants may always access
2613 // TODO: refactor this into some new function
2615 $sql = "SELECT MAX(ue.timeend)
2616 FROM {user_enrolments} ue
2617 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2618 JOIN {user} u ON u.id = ue.userid
2619 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0
2620 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
2621 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE,
2622 'userid'=>$USER->id, 'courseid'=>$coursecontext->instanceid, 'now1'=>$now, 'now2'=>$now);
2623 $until = $DB->get_field_sql($sql, $params);
2624 if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) {
2625 $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD;
2628 $USER->enrol['enrolled'][$course->id] = $until;
2631 // remove traces of previous temp guest access
2632 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2635 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2636 $enrols = enrol_get_plugins(true);
2637 // first ask all enabled enrol instances in course if they want to auto enrol user
2638 foreach($instances as $instance) {
2639 if (!isset($enrols[$instance->enrol])) {
2642 // Get a duration for the guestaccess, a timestamp in the future or false.
2643 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2644 if ($until !== false) {
2645 $USER->enrol['enrolled'][$course->id] = $until;
2646 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2651 // if not enrolled yet try to gain temporary guest access
2653 foreach($instances as $instance) {
2654 if (!isset($enrols[$instance->enrol])) {
2657 // Get a duration for the guestaccess, a timestamp in the future or false.
2658 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2659 if ($until !== false) {
2660 $USER->enrol['tempguest'][$course->id] = $until;
2670 if ($preventredirect) {
2671 throw new require_login_exception('Not enrolled');
2673 $SESSION->wantsurl = $FULLME;
2674 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2678 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
2679 // conditional availability, etc
2680 if ($cm && !$cm->uservisible) {
2681 if ($preventredirect) {
2682 throw new require_login_exception('Activity is hidden');
2684 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2687 // Finally access granted, update lastaccess times
2688 user_accesstime_log($course->id);
2693 * This function just makes sure a user is logged out.
2697 function require_logout() {
2703 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2705 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2706 foreach($authsequence as $authname) {
2707 $authplugin = get_auth_plugin($authname);
2708 $authplugin->prelogout_hook();
2712 events_trigger('user_logout', $params);
2713 session_get_instance()->terminate_current();
2718 * Weaker version of require_login()
2720 * This is a weaker version of {@link require_login()} which only requires login
2721 * when called from within a course rather than the site page, unless
2722 * the forcelogin option is turned on.
2723 * @see require_login()
2726 * @param mixed $courseorid The course object or id in question
2727 * @param bool $autologinguest Allow autologin guests if that is wanted
2728 * @param object $cm Course activity module if known
2729 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2730 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2731 * in order to keep redirects working properly. MDL-14495
2732 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2735 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2736 global $CFG, $PAGE, $SITE;
2737 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
2738 or (!is_object($courseorid) and $courseorid == SITEID);
2739 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2740 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2741 // db queries so this is not really a performance concern, however it is obviously
2742 // better if you use get_fast_modinfo to get the cm before calling this.
2743 if (is_object($courseorid)) {
2744 $course = $courseorid;
2746 $course = clone($SITE);
2748 $modinfo = get_fast_modinfo($course);
2749 $cm = $modinfo->get_cm($cm->id);
2751 if (!empty($CFG->forcelogin)) {
2752 // login required for both SITE and courses
2753 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2755 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2756 // always login for hidden activities
2757 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2759 } else if ($issite) {
2760 //login for SITE not required
2761 if ($cm and empty($cm->visible)) {
2762 // hidden activities are not accessible without login
2763 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2764 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2765 // not-logged-in users do not have any group membership
2766 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2768 // We still need to instatiate PAGE vars properly so that things
2769 // that rely on it like navigation function correctly.
2770 if (!empty($courseorid)) {
2771 if (is_object($courseorid)) {
2772 $course = $courseorid;
2774 $course = clone($SITE);
2777 if ($cm->course != $course->id) {
2778 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2780 $PAGE->set_cm($cm, $course);
2781 $PAGE->set_pagelayout('incourse');
2783 $PAGE->set_course($course);
2786 // If $PAGE->course, and hence $PAGE->context, have not already been set
2787 // up properly, set them up now.
2788 $PAGE->set_course($PAGE->course);
2790 //TODO: verify conditional activities here
2791 user_accesstime_log(SITEID);
2796 // course login always required
2797 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2802 * Require key login. Function terminates with error if key not found or incorrect.
2808 * @uses NO_MOODLE_COOKIES
2809 * @uses PARAM_ALPHANUM
2810 * @param string $script unique script identifier
2811 * @param int $instance optional instance id
2812 * @return int Instance ID
2814 function require_user_key_login($script, $instance=null) {
2815 global $USER, $SESSION, $CFG, $DB;
2817 if (!NO_MOODLE_COOKIES) {
2818 print_error('sessioncookiesdisable');
2822 @session_write_close();
2824 $keyvalue = required_param('key', PARAM_ALPHANUM);
2826 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2827 print_error('invalidkey');
2830 if (!empty($key->validuntil) and $key->validuntil < time()) {
2831 print_error('expiredkey');
2834 if ($key->iprestriction) {
2835 $remoteaddr = getremoteaddr(null);
2836 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2837 print_error('ipmismatch');
2841 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2842 print_error('invaliduserid');
2845 /// emulate normal session
2846 session_set_user($user);
2848 /// note we are not using normal login
2849 if (!defined('USER_KEY_LOGIN')) {
2850 define('USER_KEY_LOGIN', true);
2853 /// return instance id - it might be empty
2854 return $key->instance;
2858 * Creates a new private user access key.
2861 * @param string $script unique target identifier
2862 * @param int $userid
2863 * @param int $instance optional instance id
2864 * @param string $iprestriction optional ip restricted access
2865 * @param timestamp $validuntil key valid only until given data
2866 * @return string access key value
2868 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2871 $key = new stdClass();
2872 $key->script = $script;
2873 $key->userid = $userid;
2874 $key->instance = $instance;
2875 $key->iprestriction = $iprestriction;
2876 $key->validuntil = $validuntil;
2877 $key->timecreated = time();
2879 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
2880 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
2882 $key->value = md5($userid.'_'.time().random_string(40));
2884 $DB->insert_record('user_private_key', $key);
2889 * Delete the user's new private user access keys for a particular script.
2892 * @param string $script unique target identifier
2893 * @param int $userid
2896 function delete_user_key($script,$userid) {
2898 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
2902 * Gets a private user access key (and creates one if one doesn't exist).
2905 * @param string $script unique target identifier
2906 * @param int $userid
2907 * @param int $instance optional instance id
2908 * @param string $iprestriction optional ip restricted access
2909 * @param timestamp $validuntil key valid only until given data
2910 * @return string access key value
2912 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2915 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
2916 'instance'=>$instance, 'iprestriction'=>$iprestriction,
2917 'validuntil'=>$validuntil))) {
2920 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
2926 * Modify the user table by setting the currently logged in user's
2927 * last login to now.
2931 * @return bool Always returns true
2933 function update_user_login_times() {
2936 $user = new stdClass();
2937 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2938 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2940 $user->id = $USER->id;
2942 $DB->update_record('user', $user);
2947 * Determines if a user has completed setting up their account.
2949 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
2952 function user_not_fully_set_up($user) {
2953 if (isguestuser($user)) {
2956 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
2960 * Check whether the user has exceeded the bounce threshold
2964 * @param user $user A {@link $USER} object
2965 * @return bool true=>User has exceeded bounce threshold
2967 function over_bounce_threshold($user) {
2970 if (empty($CFG->handlebounces)) {
2974 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2978 // set sensible defaults
2979 if (empty($CFG->minbounces)) {
2980 $CFG->minbounces = 10;
2982 if (empty($CFG->bounceratio)) {
2983 $CFG->bounceratio = .20;
2987 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2988 $bouncecount = $bounce->value;
2990 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2991 $sendcount = $send->value;
2993 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2997 * Used to increment or reset email sent count
3000 * @param user $user object containing an id
3001 * @param bool $reset will reset the count to 0
3004 function set_send_count($user,$reset=false) {
3007 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3011 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3012 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3013 $DB->update_record('user_preferences', $pref);
3015 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3017 $pref = new stdClass();
3018 $pref->name = 'email_send_count';
3020 $pref->userid = $user->id;
3021 $DB->insert_record('user_preferences', $pref, false);
3026 * Increment or reset user's email bounce count
3029 * @param user $user object containing an id
3030 * @param bool $reset will reset the count to 0
3032 function set_bounce_count($user,$reset=false) {
3035 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3036 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3037 $DB->update_record('user_preferences', $pref);
3039 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3041 $pref = new stdClass();
3042 $pref->name = 'email_bounce_count';
3044 $pref->userid = $user->id;
3045 $DB->insert_record('user_preferences', $pref, false);
3050 * Keeps track of login attempts
3054 function update_login_count() {
3059 if (empty($SESSION->logincount)) {
3060 $SESSION->logincount = 1;
3062 $SESSION->logincount++;
3065 if ($SESSION->logincount > $max_logins) {
3066 unset($SESSION->wantsurl);
3067 print_error('errortoomanylogins');
3072 * Resets login attempts
3076 function reset_login_count() {
3079 $SESSION->logincount = 0;
3083 * Determines if the currently logged in user is in editing mode.
3084 * Note: originally this function had $userid parameter - it was not usable anyway
3086 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3087 * @todo Deprecated function remove when ready
3090 * @uses DEBUG_DEVELOPER
3093 function isediting() {
3095 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3096 return $PAGE->user_is_editing();
3100 * Determines if the logged in user is currently moving an activity
3103 * @param int $courseid The id of the course being tested
3106 function ismoving($courseid) {
3109 if (!empty($USER->activitycopy)) {
3110 return ($USER->activitycopycourse == $courseid);
3116 * Returns a persons full name
3118 * Given an object containing firstname and lastname
3119 * values, this function returns a string with the
3120 * full name of the person.
3121 * The result may depend on system settings
3122 * or language. 'override' will force both names
3123 * to be used even if system settings specify one.
3127 * @param object $user A {@link $USER} object to get full name of
3128 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3131 function fullname($user, $override=false) {
3132 global $CFG, $SESSION;
3134 if (!isset($user->firstname) and !isset($user->lastname)) {
3139 if (!empty($CFG->forcefirstname)) {
3140 $user->firstname = $CFG->forcefirstname;
3142 if (!empty($CFG->forcelastname)) {
3143 $user->lastname = $CFG->forcelastname;
3147 if (!empty($SESSION->fullnamedisplay)) {
3148 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3151 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3152 return $user->firstname .' '. $user->lastname;
3154 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3155 return $user->lastname .' '. $user->firstname;
3157 } else if ($CFG->fullnamedisplay == 'firstname') {
3159 return get_string('fullnamedisplay', '', $user);
3161 return $user->firstname;
3165 return get_string('fullnamedisplay', '', $user);
3169 * Returns whether a given authentication plugin exists.
3172 * @param string $auth Form of authentication to check for. Defaults to the
3173 * global setting in {@link $CFG}.
3174 * @return boolean Whether the plugin is available.
3176 function exists_auth_plugin($auth) {
3179 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3180 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3186 * Checks if a given plugin is in the list of enabled authentication plugins.
3188 * @param string $auth Authentication plugin.
3189 * @return boolean Whether the plugin is enabled.
3191 function is_enabled_auth($auth) {
3196 $enabled = get_enabled_auth_plugins();
3198 return in_array($auth, $enabled);
3202 * Returns an authentication plugin instance.
3205 * @param string $auth name of authentication plugin
3206 * @return auth_plugin_base An instance of the required authentication plugin.
3208 function get_auth_plugin($auth) {
3211 // check the plugin exists first
3212 if (! exists_auth_plugin($auth)) {
3213 print_error('authpluginnotfound', 'debug', '', $auth);
3216 // return auth plugin instance
3217 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3218 $class = "auth_plugin_$auth";
3223 * Returns array of active auth plugins.
3225 * @param bool $fix fix $CFG->auth if needed
3228 function get_enabled_auth_plugins($fix=false) {
3231 $default = array('manual', 'nologin');
3233 if (empty($CFG->auth)) {
3236 $auths = explode(',', $CFG->auth);
3240 $auths = array_unique($auths);
3241 foreach($auths as $k=>$authname) {
3242 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3246 $newconfig = implode(',', $auths);
3247 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3248 set_config('auth', $newconfig);
3252 return (array_merge($default, $auths));
3256 * Returns true if an internal authentication method is being used.
3257 * if method not specified then, global default is assumed
3259 * @param string $auth Form of authentication required
3262 function is_internal_auth($auth) {
3263 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3264 return $authplugin->is_internal();
3268 * Returns true if the user is a 'restored' one
3270 * Used in the login process to inform the user
3271 * and allow him/her to reset the password
3275 * @param string $username username to be checked
3278 function is_restored_user($username) {
3281 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3285 * Returns an array of user fields
3287 * @return array User field/column names
3289 function get_user_fieldnames() {
3292 $fieldarray = $DB->get_columns('user');
3293 unset($fieldarray['id']);
3294 $fieldarray = array_keys($fieldarray);
3300 * Creates a bare-bones user record
3302 * @todo Outline auth types and provide code example
3304 * @param string $username New user's username to add to record
3305 * @param string $password New user's password to add to record
3306 * @param string $auth Form of authentication required
3307 * @return stdClass A complete user object
3309 function create_user_record($username, $password, $auth = 'manual') {
3312 //just in case check text case
3313 $username = trim(moodle_strtolower($username));
3315 $authplugin = get_auth_plugin($auth);
3317 $newuser = new stdClass();
3319 if ($newinfo = $authplugin->get_userinfo($username)) {
3320 $newinfo = truncate_userinfo($newinfo);
3321 foreach ($newinfo as $key => $value){
3322 $newuser->$key = $value;
3326 if (!empty($newuser->email)) {
3327 if (email_is_not_allowed($newuser->email)) {
3328 unset($newuser->email);
3332 if (!isset($newuser->city)) {
3333 $newuser->city = '';
3336 $newuser->auth = $auth;
3337 $newuser->username = $username;
3340 // user CFG lang for user if $newuser->lang is empty
3341 // or $user->lang is not an installed language
3342 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3343 $newuser->lang = $CFG->lang;
3345 $newuser->confirmed = 1;
3346 $newuser->lastip = getremoteaddr();
3347 $newuser->timemodified = time();
3348 $newuser->mnethostid = $CFG->mnet_localhost_id;
3350 $newuser->id = $DB->insert_record('user', $newuser);
3351 $user = get_complete_user_data('id', $newuser->id);
3352 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3353 set_user_preference('auth_forcepasswordchange', 1, $user);
3355 update_internal_user_password($user, $password);
3357 // fetch full user record for the event, the complete user data contains too much info
3358 // and we want to be consistent with other places that trigger this event
3359 events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
3365 * Will update a local user record from an external source.
3366 * (MNET users can not be updated using this method!)
3368 * @param string $username user's username to update the record
3369 * @return stdClass A complete user object
3371 function update_user_record($username) {
3374 $username = trim(moodle_strtolower($username)); /// just in case check text case
3376 $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
3378 $userauth = get_auth_plugin($oldinfo->auth);
3380 if ($newinfo = $userauth->get_userinfo($username)) {
3381 $newinfo = truncate_userinfo($newinfo);
3382 foreach ($newinfo as $key => $value){
3383 $key = strtolower($key);
3384 if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id'
3385 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3386 // unknown or must not be changed
3389 $confval = $userauth->config->{'field_updatelocal_' . $key};
3390 $lockval = $userauth->config->{'field_lock_' . $key};
3391 if (empty($confval) || empty($lockval)) {
3394 if ($confval === 'onlogin') {
3395 // MDL-4207 Don't overwrite modified user profile values with
3396 // empty LDAP values when 'unlocked if empty' is set. The purpose
3397 // of the setting 'unlocked if empty' is to allow the user to fill
3398 // in a value for the selected field _if LDAP is giving
3399 // nothing_ for this field. Thus it makes sense to let this value
3400 // stand in until LDAP is giving a value for this field.
3401 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3402 if ((string)$oldinfo->$key !== (string)$value) {
3403 $newuser[$key] = (string)$value;
3409 $newuser['id'] = $oldinfo->id;
3410 $DB->update_record('user', $newuser);
3411 // fetch full user record for the event, the complete user data contains too much info
3412 // and we want to be consistent with other places that trigger this event
3413 events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id)));
3417 return get_complete_user_data('id', $oldinfo->id);
3421 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3422 * which may have large fields
3424 * @todo Add vartype handling to ensure $info is an array
3426 * @param array $info Array of user properties to truncate if needed
3427 * @return array The now truncated information that was passed in
3429 function truncate_userinfo($info) {
3430 // define the limits
3440 'institution' => 40,
3448 $textlib = textlib_get_instance();
3449 // apply where needed
3450 foreach (array_keys($info) as $key) {
3451 if (!empty($limit[$key])) {
3452 $info[$key] = trim($textlib->substr($info[$key],0, $limit[$key]));
3460 * Marks user deleted in internal user database and notifies the auth plugin.
3461 * Also unenrols user from all roles and does other cleanup.
3463 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3465 * @param stdClass $user full user object before delete
3466 * @return boolean always true
3468 function delete_user($user) {
3470 require_once($CFG->libdir.'/grouplib.php');
3471 require_once($CFG->libdir.'/gradelib.php');
3472 require_once($CFG->dirroot.'/message/lib.php');
3473 require_once($CFG->dirroot.'/tag/lib.php');
3475 // delete all grades - backup is kept in grade_grades_history table
3476 grade_user_delete($user->id);
3478 //move unread messages from this user to read
3479 message_move_userfrom_unread2read($user->id);
3481 // TODO: remove from cohorts using standard API here
3484 tag_set('user', $user->id, array());
3486 // unconditionally unenrol from all courses
3487 enrol_user_delete($user);
3489 // unenrol from all roles in all contexts
3490 role_unassign_all(array('userid'=>$user->id)); // this might be slow but it is really needed - modules might do some extra cleanup!
3492 //now do a brute force cleanup
3494 // remove from all cohorts
3495 $DB->delete_records('cohort_members', array('userid'=>$user->id));
3497 // remove from all groups
3498 $DB->delete_records('groups_members', array('userid'=>$user->id));
3500 // brute force unenrol from all courses
3501 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
3503 // purge user preferences
3504 $DB->delete_records('user_preferences', array('userid'=>$user->id));
3506 // purge user extra profile info
3507 $DB->delete_records('user_info_data', array('userid'=>$user->id));
3509 // last course access not necessary either
3510 $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
3512 // force logout - may fail if file based sessions used, sorry
3513 session_kill_user($user->id);
3515 // now do a final accesslib cleanup - removes all role assignments in user context and context itself
3516 delete_context(CONTEXT_USER, $user->id);
3518 // workaround for bulk deletes of users with the same email address
3519 $delname = "$user->email.".time();
3520 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3524 // mark internal user record as "deleted"
3525 $updateuser = new stdClass();
3526 $updateuser->id = $user->id;
3527 $updateuser->deleted = 1;
3528 $updateuser->username = $delname; // Remember it just in case
3529 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
3530 $updateuser->idnumber = ''; // Clear this field to free it up
3531 $updateuser->timemodified = time();
3533 $DB->update_record('user', $updateuser);
3535 // notify auth plugin - do not block the delete even when plugin fails
3536 $authplugin = get_auth_plugin($user->auth);
3537 $authplugin->user_delete($user);
3539 // any plugin that needs to cleanup should register this event
3540 events_trigger('user_deleted', $user);
3546 * Retrieve the guest user object
3550 * @return user A {@link $USER} object
3552 function guest_user() {
3555 if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
3556 $newuser->confirmed = 1;
3557 $newuser->lang = $CFG->lang;
3558 $newuser->lastip = getremoteaddr();
3565 * Authenticates a user against the chosen authentication mechanism
3567 * Given a username and password, this function looks them
3568 * up using the currently selected authentication mechanism,
3569 * and if the authentication is successful, it returns a
3570 * valid $user object from the 'user' table.
3572 * Uses auth_ functions from the currently active auth module
3574 * After authenticate_user_login() returns success, you will need to
3575 * log that the user has logged in, and call complete_user_login() to set
3578 * Note: this function works only with non-mnet accounts!
3580 * @param string $username User's username
3581 * @param string $password User's password
3582 * @return user|flase A {@link $USER} object or false if error
3584 function authenticate_user_login($username, $password) {
3587 $authsenabled = get_enabled_auth_plugins();
3589 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
3590 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
3591 if (!empty($user->suspended)) {
3592 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3593 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3596 if ($auth=='nologin' or !is_enabled_auth($auth)) {
3597 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3598 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3601 $auths = array($auth);
3604 // check if there's a deleted record (cheaply)
3605 if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
3606 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3610 // User does not exist
3611 $auths = $authsenabled;
3612 $user = new stdClass();
3616 foreach ($auths as $auth) {
3617 $authplugin = get_auth_plugin($auth);
3619 // on auth fail fall through to the next plugin
3620 if (!$authplugin->user_login($username, $password)) {
3624 // successful authentication
3625 if ($user->id) { // User already exists in database
3626 if (empty($user->auth)) { // For some reason auth isn't set yet
3627 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
3628 $user->auth = $auth;
3630 if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3631 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
3632 $user->firstaccess = $user->timemodified;
3635 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3637 if ($authplugin->is_synchronised_with_external()) { // update user record from external DB
3638 $user = update_user_record($username);
3641 // if user not found, create him
3642 $user = create_user_record($username, $password, $auth);
3645 $authplugin->sync_roles($user);
3647 foreach ($authsenabled as $hau) {
3648 $hauth = get_auth_plugin($hau);
3649 $hauth->user_authenticated_hook($user, $username, $password);
3652 if (empty($user->id)) {
3656 if (!empty($user->suspended)) {
3657 // just in case some auth plugin suspended account
3658 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3659 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3666 // failed if all the plugins have failed
3667 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3668 if (debugging('', DEBUG_ALL)) {
3669 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3675 * Call to complete the user login process after authenticate_user_login()
3676 * has succeeded. It will setup the $USER variable and other required bits
3680 * - It will NOT log anything -- up to the caller to decide what to log.
3681 * - this function does not set any cookies any more!
3683 * @param object $user
3684 * @return object A {@link $USER} object - BC only, do not use