3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * moodlelib.php - Moodle main library
21 * Main library file of miscellaneous general-purpose Moodle functions.
22 * Other main libraries:
23 * - weblib.php - functions that produce web output
24 * - datalib.php - functions that access the database
28 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32 defined('MOODLE_INTERNAL') || die();
34 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
36 /// Date and time constants ///
38 * Time constant - the number of seconds in a year
40 define('YEARSECS', 31536000);
43 * Time constant - the number of seconds in a week
45 define('WEEKSECS', 604800);
48 * Time constant - the number of seconds in a day
50 define('DAYSECS', 86400);
53 * Time constant - the number of seconds in an hour
55 define('HOURSECS', 3600);
58 * Time constant - the number of seconds in a minute
60 define('MINSECS', 60);
63 * Time constant - the number of minutes in a day
65 define('DAYMINS', 1440);
68 * Time constant - the number of minutes in an hour
70 define('HOURMINS', 60);
72 /// Parameter constants - every call to optional_param(), required_param() ///
73 /// or clean_param() should have a specified type of parameter. //////////////
78 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
80 define('PARAM_ALPHA', 'alpha');
83 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
84 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
86 define('PARAM_ALPHAEXT', 'alphaext');
89 * PARAM_ALPHANUM - expected numbers and letters only.
91 define('PARAM_ALPHANUM', 'alphanum');
94 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
96 define('PARAM_ALPHANUMEXT', 'alphanumext');
99 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
101 define('PARAM_AUTH', 'auth');
104 * PARAM_BASE64 - Base 64 encoded format
106 define('PARAM_BASE64', 'base64');
109 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
111 define('PARAM_BOOL', 'bool');
114 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
115 * checked against the list of capabilities in the database.
117 define('PARAM_CAPABILITY', 'capability');
120 * PARAM_CLEANHTML - cleans submitted HTML code. use only for text in HTML format. This cleaning may fix xhtml strictness too.
122 define('PARAM_CLEANHTML', 'cleanhtml');
125 * PARAM_EMAIL - an email address following the RFC
127 define('PARAM_EMAIL', 'email');
130 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
132 define('PARAM_FILE', 'file');
135 * PARAM_FLOAT - a real/floating point number.
137 define('PARAM_FLOAT', 'float');
140 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
142 define('PARAM_HOST', 'host');
145 * PARAM_INT - integers only, use when expecting only numbers.
147 define('PARAM_INT', 'int');
150 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
152 define('PARAM_LANG', 'lang');
155 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
157 define('PARAM_LOCALURL', 'localurl');
160 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
162 define('PARAM_NOTAGS', 'notags');
165 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
166 * note: the leading slash is not removed, window drive letter is not allowed
168 define('PARAM_PATH', 'path');
171 * PARAM_PEM - Privacy Enhanced Mail format
173 define('PARAM_PEM', 'pem');
176 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
178 define('PARAM_PERMISSION', 'permission');
181 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way
183 define('PARAM_RAW', 'raw');
186 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
188 define('PARAM_SAFEDIR', 'safedir');
191 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
193 define('PARAM_SAFEPATH', 'safepath');
196 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
198 define('PARAM_SEQUENCE', 'sequence');
201 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
203 define('PARAM_TAG', 'tag');
206 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
208 define('PARAM_TAGLIST', 'taglist');
211 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
213 define('PARAM_TEXT', 'text');
216 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
218 define('PARAM_THEME', 'theme');
221 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
223 define('PARAM_URL', 'url');
226 * 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!!
228 define('PARAM_USERNAME', 'username');
231 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
233 define('PARAM_STRINGID', 'stringid');
235 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
237 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
238 * It was one of the first types, that is why it is abused so much ;-)
239 * @deprecated since 2.0
241 define('PARAM_CLEAN', 'clean');
244 * PARAM_INTEGER - deprecated alias for PARAM_INT
246 define('PARAM_INTEGER', 'int');
249 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
251 define('PARAM_NUMBER', 'float');
254 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
255 * NOTE: originally alias for PARAM_APLHA
257 define('PARAM_ACTION', 'alphanumext');
260 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
261 * NOTE: originally alias for PARAM_APLHA
263 define('PARAM_FORMAT', 'alphanumext');
266 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
268 define('PARAM_MULTILANG', 'text');
271 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
273 define('PARAM_CLEANFILE', 'file');
278 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
280 define('VALUE_REQUIRED', 1);
283 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
285 define('VALUE_OPTIONAL', 2);
288 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
290 define('VALUE_DEFAULT', 0);
293 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
295 define('NULL_NOT_ALLOWED', false);
298 * NULL_ALLOWED - the parameter can be set to null in the database
300 define('NULL_ALLOWED', true);
304 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
306 define('PAGE_COURSE_VIEW', 'course-view');
308 /** Get remote addr constant */
309 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
310 /** Get remote addr constant */
311 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
313 /// Blog access level constant declaration ///
314 define ('BLOG_USER_LEVEL', 1);
315 define ('BLOG_GROUP_LEVEL', 2);
316 define ('BLOG_COURSE_LEVEL', 3);
317 define ('BLOG_SITE_LEVEL', 4);
318 define ('BLOG_GLOBAL_LEVEL', 5);
323 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
324 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
325 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
327 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
329 define('TAG_MAX_LENGTH', 50);
331 /// Password policy constants ///
332 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
333 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
334 define ('PASSWORD_DIGITS', '0123456789');
335 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
337 /// Feature constants ///
338 // Used for plugin_supports() to report features that are, or are not, supported by a module.
340 /** True if module can provide a grade */
341 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
342 /** True if module supports outcomes */
343 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
345 /** True if module has code to track whether somebody viewed it */
346 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
347 /** True if module has custom completion rules */
348 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
350 /** True if module supports outcomes */
351 define('FEATURE_IDNUMBER', 'idnumber');
352 /** True if module supports groups */
353 define('FEATURE_GROUPS', 'groups');
354 /** True if module supports groupings */
355 define('FEATURE_GROUPINGS', 'groupings');
356 /** True if module supports groupmembersonly */
357 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
359 /** Type of module */
360 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
361 /** True if module supports intro editor */
362 define('FEATURE_MOD_INTRO', 'mod_intro');
363 /** True if module has default completion */
364 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
366 define('FEATURE_COMMENT', 'comment');
368 define('FEATURE_RATE', 'rate');
369 /** True if module supports backup/restore of moodle2 format */
370 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
372 /** Unspecified module archetype */
373 define('MOD_ARCHETYPE_OTHER', 0);
374 /** Resource-like type module */
375 define('MOD_ARCHETYPE_RESOURCE', 1);
376 /** Assignment module archetype */
377 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
380 * Security token used for allowing access
381 * from external application such as web services.
382 * Scripts do not use any session, performance is relatively
383 * low because we need to load access info in each request.
384 * Scripts are executed in parallel.
386 define('EXTERNAL_TOKEN_PERMANENT', 0);
389 * Security token used for allowing access
390 * of embedded applications, the code is executed in the
391 * active user session. Token is invalidated after user logs out.
392 * Scripts are executed serially - normal session locking is used.
394 define('EXTERNAL_TOKEN_EMBEDDED', 1);
397 * The home page should be the site home
399 define('HOMEPAGE_SITE', 0);
401 * The home page should be the users my page
403 define('HOMEPAGE_MY', 1);
405 * The home page can be chosen by the user
407 define('HOMEPAGE_USER', 2);
410 * Hub directory url (should be moodle.org)
412 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
416 * Moodle.org url (should be moodle.org)
418 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
421 /// PARAMETER HANDLING ////////////////////////////////////////////////////
424 * Returns a particular value for the named variable, taken from
425 * POST or GET. If the parameter doesn't exist then an error is
426 * thrown because we require this variable.
428 * This function should be used to initialise all required values
429 * in a script that are based on parameters. Usually it will be
431 * $id = required_param('id', PARAM_INT);
433 * Please note the $type parameter is now required,
434 * for now PARAM_CLEAN is used for backwards compatibility only.
436 * @param string $parname the name of the page parameter we want
437 * @param string $type expected type of parameter
440 function required_param($parname, $type) {
442 debugging('required_param() requires $type to be specified.');
443 $type = PARAM_CLEAN; // for now let's use this deprecated type
445 if (isset($_POST[$parname])) { // POST has precedence
446 $param = $_POST[$parname];
447 } else if (isset($_GET[$parname])) {
448 $param = $_GET[$parname];
450 print_error('missingparam', '', '', $parname);
453 return clean_param($param, $type);
457 * Returns a particular value for the named variable, taken from
458 * POST or GET, otherwise returning a given default.
460 * This function should be used to initialise all optional values
461 * in a script that are based on parameters. Usually it will be
463 * $name = optional_param('name', 'Fred', PARAM_TEXT);
465 * Please note $default and $type parameters are now required,
466 * for now PARAM_CLEAN is used for backwards compatibility only.
468 * @param string $parname the name of the page parameter we want
469 * @param mixed $default the default value to return if nothing is found
470 * @param string $type expected type of parameter
473 function optional_param($parname, $default, $type) {
475 debugging('optional_param() requires $default and $type to be specified.');
476 $type = PARAM_CLEAN; // for now let's use this deprecated type
478 if (!isset($default)) {
482 if (isset($_POST[$parname])) { // POST has precedence
483 $param = $_POST[$parname];
484 } else if (isset($_GET[$parname])) {
485 $param = $_GET[$parname];
490 return clean_param($param, $type);
494 * Strict validation of parameter values, the values are only converted
495 * to requested PHP type. Internally it is using clean_param, the values
496 * before and after cleaning must be equal - otherwise
497 * an invalid_parameter_exception is thrown.
498 * Objects and classes are not accepted.
500 * @param mixed $param
501 * @param int $type PARAM_ constant
502 * @param bool $allownull are nulls valid value?
503 * @param string $debuginfo optional debug information
504 * @return mixed the $param value converted to PHP type or invalid_parameter_exception
506 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
507 if (is_null($param)) {
508 if ($allownull == NULL_ALLOWED) {
511 throw new invalid_parameter_exception($debuginfo);
514 if (is_array($param) or is_object($param)) {
515 throw new invalid_parameter_exception($debuginfo);
518 $cleaned = clean_param($param, $type);
519 if ((string)$param !== (string)$cleaned) {
520 // conversion to string is usually lossless
521 throw new invalid_parameter_exception($debuginfo);
528 * Used by {@link optional_param()} and {@link required_param()} to
529 * clean the variables and/or cast to specific types, based on
532 * $course->format = clean_param($course->format, PARAM_ALPHA);
533 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
536 * @param mixed $param the variable we are cleaning
537 * @param int $type expected format of param after cleaning.
540 function clean_param($param, $type) {
544 if (is_array($param)) { // Let's loop
546 foreach ($param as $key => $value) {
547 $newparam[$key] = clean_param($value, $type);
553 case PARAM_RAW: // no cleaning at all
556 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
557 // this is deprecated!, please use more specific type instead
558 if (is_numeric($param)) {
561 return clean_text($param); // Sweep for scripts, etc
563 case PARAM_CLEANHTML: // clean html fragment
564 $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
568 return (int)$param; // Convert to integer
572 return (float)$param; // Convert to float
574 case PARAM_ALPHA: // Remove everything not a-z
575 return preg_replace('/[^a-zA-Z]/i', '', $param);
577 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
578 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
580 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
581 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
583 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
584 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
586 case PARAM_SEQUENCE: // Remove everything not 0-9,
587 return preg_replace('/[^0-9,]/i', '', $param);
589 case PARAM_BOOL: // Convert to 1 or 0
590 $tempstr = strtolower($param);
591 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
593 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
596 $param = empty($param) ? 0 : 1;
600 case PARAM_NOTAGS: // Strip all tags
601 return strip_tags($param);
603 case PARAM_TEXT: // leave only tags needed for multilang
604 // if the multilang syntax is not correct we strip all tags
605 // because it would break xhtml strict which is required for accessibility standards
606 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
608 if (strpos($param, '</lang>') !== false) {
609 // old and future mutilang syntax
610 $param = strip_tags($param, '<lang>');
611 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
615 foreach ($matches[0] as $match) {
616 if ($match === '</lang>') {
624 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
635 } else if (strpos($param, '</span>') !== false) {
636 // current problematic multilang syntax
637 $param = strip_tags($param, '<span>');
638 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
642 foreach ($matches[0] as $match) {
643 if ($match === '</span>') {
651 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
663 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
664 return strip_tags($param);
666 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
667 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
669 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
670 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
672 case PARAM_FILE: // Strip all suspicious characters from filename
673 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
674 $param = preg_replace('~\.\.+~', '', $param);
675 if ($param === '.') {
680 case PARAM_PATH: // Strip all suspicious characters from file path
681 $param = str_replace('\\', '/', $param);
682 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
683 $param = preg_replace('~\.\.+~', '', $param);
684 $param = preg_replace('~//+~', '/', $param);
685 return preg_replace('~/(\./)+~', '/', $param);
687 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
688 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
689 // match ipv4 dotted quad
690 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
691 // confirm values are ok
695 || $match[4] > 255 ) {
696 // hmmm, what kind of dotted quad is this?
699 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
700 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
701 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
703 // all is ok - $param is respected
710 case PARAM_URL: // allow safe ftp, http, mailto urls
711 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
712 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
713 // all is ok, param is respected
715 $param =''; // not really ok
719 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
720 $param = clean_param($param, PARAM_URL);
721 if (!empty($param)) {
722 if (preg_match(':^/:', $param)) {
723 // root-relative, ok!
724 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
725 // absolute, and matches our wwwroot
727 // relative - let's make sure there are no tricks
728 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
738 $param = trim($param);
739 // PEM formatted strings may contain letters/numbers and the symbols
743 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
744 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
745 list($wholething, $body) = $matches;
746 unset($wholething, $matches);
747 $b64 = clean_param($body, PARAM_BASE64);
749 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
757 if (!empty($param)) {
758 // PEM formatted strings may contain letters/numbers and the symbols
762 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
765 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
766 // Each line of base64 encoded data must be 64 characters in
767 // length, except for the last line which may be less than (or
768 // equal to) 64 characters long.
769 for ($i=0, $j=count($lines); $i < $j; $i++) {
771 if (64 < strlen($lines[$i])) {
777 if (64 != strlen($lines[$i])) {
781 return implode("\n",$lines);
787 //as long as magic_quotes_gpc is used, a backslash will be a
788 //problem, so remove *all* backslash.
789 //$param = str_replace('\\', '', $param);
790 //remove some nasties
791 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
792 //convert many whitespace chars into one
793 $param = preg_replace('/\s+/', ' ', $param);
794 $textlib = textlib_get_instance();
795 $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
800 $tags = explode(',', $param);
802 foreach ($tags as $tag) {
803 $res = clean_param($tag, PARAM_TAG);
809 return implode(',', $result);
814 case PARAM_CAPABILITY:
815 if (get_capability_info($param)) {
821 case PARAM_PERMISSION:
822 $param = (int)$param;
823 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
830 $param = clean_param($param, PARAM_SAFEDIR);
831 if (exists_auth_plugin($param)) {
838 $param = clean_param($param, PARAM_SAFEDIR);
839 if (get_string_manager()->translation_exists($param)) {
842 return ''; // Specified language is not installed or param malformed
846 $param = clean_param($param, PARAM_SAFEDIR);
847 if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
849 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
852 return ''; // Specified theme is not installed
856 $param = str_replace(" " , "", $param);
857 $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
858 if (empty($CFG->extendedusernamechars)) {
859 // regular expression, eliminate all chars EXCEPT:
860 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
861 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
866 if (validate_email($param)) {
873 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
879 default: // throw error, switched parameters in optional_param or another serious problem
880 print_error("unknownparamtype", '', '', $type);
885 * Return true if given value is integer or string with integer value
887 * @param mixed $value String or Int
888 * @return bool true if number, false if not
890 function is_number($value) {
891 if (is_int($value)) {
893 } else if (is_string($value)) {
894 return ((string)(int)$value) === $value;
901 * Returns host part from url
902 * @param string $url full url
903 * @return string host, null if not found
905 function get_host_from_url($url) {
906 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
914 * Tests whether anything was returned by text editor
916 * This function is useful for testing whether something you got back from
917 * the HTML editor actually contains anything. Sometimes the HTML editor
918 * appear to be empty, but actually you get back a <br> tag or something.
920 * @param string $string a string containing HTML.
921 * @return boolean does the string contain any actual content - that is text,
922 * images, objects, etc.
924 function html_is_blank($string) {
925 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
929 * Set a key in global configuration
931 * Set a key/value pair in both this session's {@link $CFG} global variable
932 * and in the 'config' database table for future sessions.
934 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
935 * In that case it doesn't affect $CFG.
937 * A NULL value will delete the entry.
941 * @param string $name the key to set
942 * @param string $value the value to set (without magic quotes)
943 * @param string $plugin (optional) the plugin scope, default NULL
944 * @return bool true or exception
946 function set_config($name, $value, $plugin=NULL) {
949 if (empty($plugin)) {
950 if (!array_key_exists($name, $CFG->config_php_settings)) {
951 // So it's defined for this invocation at least
952 if (is_null($value)) {
955 $CFG->$name = (string)$value; // settings from db are always strings
959 if ($DB->get_field('config', 'name', array('name'=>$name))) {
960 if ($value === null) {
961 $DB->delete_records('config', array('name'=>$name));
963 $DB->set_field('config', 'value', $value, array('name'=>$name));
966 if ($value !== null) {
967 $config = new stdClass();
968 $config->name = $name;
969 $config->value = $value;
970 $DB->insert_record('config', $config, false);
974 } else { // plugin scope
975 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
977 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
979 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
982 if ($value !== null) {
983 $config = new stdClass();
984 $config->plugin = $plugin;
985 $config->name = $name;
986 $config->value = $value;
987 $DB->insert_record('config_plugins', $config, false);
996 * Get configuration values from the global config table
997 * or the config_plugins table.
999 * If called with one parameter, it will load all the config
1000 * variables for one plugin, and return them as an object.
1002 * If called with 2 parameters it will return a string single
1003 * value or false if the value is not found.
1005 * @param string $plugin full component name
1006 * @param string $name default NULL
1007 * @return mixed hash-like object or single value, return false no config found
1009 function get_config($plugin, $name = NULL) {
1012 // normalise component name
1013 if ($plugin === 'moodle' or $plugin === 'core') {
1017 if (!empty($name)) { // the user is asking for a specific value
1018 if (!empty($plugin)) {
1019 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1020 // setting forced in config file
1021 return $CFG->forced_plugin_settings[$plugin][$name];
1023 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1026 if (array_key_exists($name, $CFG->config_php_settings)) {
1027 // setting force in config file
1028 return $CFG->config_php_settings[$name];
1030 return $DB->get_field('config', 'value', array('name'=>$name));
1035 // the user is after a recordset
1037 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1038 if (isset($CFG->forced_plugin_settings[$plugin])) {
1039 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1040 if (is_null($v) or is_array($v) or is_object($v)) {
1041 // we do not want any extra mess here, just real settings that could be saved in db
1042 unset($localcfg[$n]);
1044 //convert to string as if it went through the DB
1045 $localcfg[$n] = (string)$v;
1049 return (object)$localcfg;
1052 // this part is not really used any more, but anyway...
1053 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1054 foreach($CFG->config_php_settings as $n=>$v) {
1055 if (is_null($v) or is_array($v) or is_object($v)) {
1056 // we do not want any extra mess here, just real settings that could be saved in db
1057 unset($localcfg[$n]);
1059 //convert to string as if it went through the DB
1060 $localcfg[$n] = (string)$v;
1063 return (object)$localcfg;
1068 * Removes a key from global configuration
1070 * @param string $name the key to set
1071 * @param string $plugin (optional) the plugin scope
1073 * @return boolean whether the operation succeeded.
1075 function unset_config($name, $plugin=NULL) {
1078 if (empty($plugin)) {
1080 $DB->delete_records('config', array('name'=>$name));
1082 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1089 * Remove all the config variables for a given plugin.
1091 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1092 * @return boolean whether the operation succeeded.
1094 function unset_all_config_for_plugin($plugin) {
1096 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1097 $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
1102 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1104 * All users are verified if they still have the necessary capability.
1106 * @param string $value the value of the config setting.
1107 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1108 * @param bool $include admins, include administrators
1109 * @return array of user objects.
1111 function get_users_from_config($value, $capability, $includeadmins = true) {
1114 if (empty($value) or $value === '$@NONE@$') {
1118 // we have to make sure that users still have the necessary capability,
1119 // it should be faster to fetch them all first and then test if they are present
1120 // instead of validating them one-by-one
1121 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1122 if ($includeadmins) {
1123 $admins = get_admins();
1124 foreach ($admins as $admin) {
1125 $users[$admin->id] = $admin;
1129 if ($value === '$@ALL@$') {
1133 $result = array(); // result in correct order
1134 $allowed = explode(',', $value);
1135 foreach ($allowed as $uid) {
1136 if (isset($users[$uid])) {
1137 $user = $users[$uid];
1138 $result[$user->id] = $user;
1147 * Invalidates browser caches and cached data in temp
1150 function purge_all_caches() {
1153 reset_text_filters_cache();
1154 js_reset_all_caches();
1155 theme_reset_all_caches();
1156 get_string_manager()->reset_caches();
1158 // purge all other caches: rss, simplepie, etc.
1159 remove_dir($CFG->dataroot.'/cache', true);
1161 // make sure cache dir is writable, throws exception if not
1162 make_upload_directory('cache');
1168 * Get volatile flags
1170 * @param string $type
1171 * @param int $changedsince default null
1172 * @return records array
1174 function get_cache_flags($type, $changedsince=NULL) {
1177 $params = array('type'=>$type, 'expiry'=>time());
1178 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1179 if ($changedsince !== NULL) {
1180 $params['changedsince'] = $changedsince;
1181 $sqlwhere .= " AND timemodified > :changedsince";
1185 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1186 foreach ($flags as $flag) {
1187 $cf[$flag->name] = $flag->value;
1194 * Get volatile flags
1196 * @param string $type
1197 * @param string $name
1198 * @param int $changedsince default null
1199 * @return records array
1201 function get_cache_flag($type, $name, $changedsince=NULL) {
1204 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1206 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1207 if ($changedsince !== NULL) {
1208 $params['changedsince'] = $changedsince;
1209 $sqlwhere .= " AND timemodified > :changedsince";
1212 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1216 * Set a volatile flag
1218 * @param string $type the "type" namespace for the key
1219 * @param string $name the key to set
1220 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1221 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1222 * @return bool Always returns true
1224 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1227 $timemodified = time();
1228 if ($expiry===NULL || $expiry < $timemodified) {
1229 $expiry = $timemodified + 24 * 60 * 60;
1231 $expiry = (int)$expiry;
1234 if ($value === NULL) {
1235 unset_cache_flag($type,$name);
1239 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1240 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1241 return true; //no need to update; helps rcache too
1244 $f->expiry = $expiry;
1245 $f->timemodified = $timemodified;
1246 $DB->update_record('cache_flags', $f);
1248 $f = new stdClass();
1249 $f->flagtype = $type;
1252 $f->expiry = $expiry;
1253 $f->timemodified = $timemodified;
1254 $DB->insert_record('cache_flags', $f);
1260 * Removes a single volatile flag
1263 * @param string $type the "type" namespace for the key
1264 * @param string $name the key to set
1267 function unset_cache_flag($type, $name) {
1269 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1274 * Garbage-collect volatile flags
1276 * @return bool Always returns true
1278 function gc_cache_flags() {
1280 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1284 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1287 * Refresh user preference cache. This is used most often for $USER
1288 * object that is stored in session, but it also helps with performance in cron script.
1290 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1292 * @param stdClass $user user object, preferences are preloaded into ->preference property
1293 * @param int $cachelifetime cache life time on the current page (ins seconds)
1296 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1298 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1300 if (!isset($user->id)) {
1301 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1304 if (empty($user->id) or isguestuser($user->id)) {
1305 // No permanent storage for not-logged-in users and guest
1306 if (!isset($user->preference)) {
1307 $user->preference = array();
1314 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1315 // Already loaded at least once on this page. Are we up to date?
1316 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1317 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1320 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1321 // no change since the lastcheck on this page
1322 $user->preference['_lastloaded'] = $timenow;
1327 // OK, so we have to reload all preferences
1328 $loadedusers[$user->id] = true;
1329 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1330 $user->preference['_lastloaded'] = $timenow;
1334 * Called from set/delete_user_preferences, so that the prefs can
1335 * be correctly reloaded in different sessions.
1337 * NOTE: internal function, do not call from other code.
1339 * @param integer $userid the user whose prefs were changed.
1342 function mark_user_preferences_changed($userid) {
1345 if (empty($userid) or isguestuser($userid)) {
1346 // no cache flags for guest and not-logged-in users
1350 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1354 * Sets a preference for the specified user.
1356 * If user object submitted, 'preference' property contains the preferences cache.
1358 * @param string $name The key to set as preference for the specified user
1359 * @param string $value The value to set for the $name key in the specified user's record,
1360 * null means delete current value
1361 * @param stdClass|int $user A moodle user object or id, null means current user
1362 * @return bool always true or exception
1364 function set_user_preference($name, $value, $user = null) {
1367 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1368 throw new coding_exception('Invalid preference name in set_user_preference() call');
1371 if (is_null($value)) {
1372 // null means delete current
1373 return unset_user_preference($name, $user);
1374 } else if (is_object($value)) {
1375 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1376 } else if (is_array($value)) {
1377 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1379 $value = (string)$value;
1381 if (is_null($user)) {
1383 } else if (isset($user->id)) {
1384 // $user is valid object
1385 } else if (is_numeric($user)) {
1386 $user = (object)array('id'=>(int)$user);
1388 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1391 check_user_preferences_loaded($user);
1393 if (empty($user->id) or isguestuser($user->id)) {
1394 // no permanent storage for not-logged-in users and guest
1395 $user->preference[$name] = $value;
1399 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1400 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1401 // preference already set to this value
1404 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1407 $preference = new stdClass();
1408 $preference->userid = $user->id;
1409 $preference->name = $name;
1410 $preference->value = $value;
1411 $DB->insert_record('user_preferences', $preference);
1414 // update value in cache
1415 $user->preference[$name] = $value;
1417 // set reload flag for other sessions
1418 mark_user_preferences_changed($user->id);
1424 * Sets a whole array of preferences for the current user
1426 * If user object submitted, 'preference' property contains the preferences cache.
1428 * @param array $prefarray An array of key/value pairs to be set
1429 * @param stdClass|int $user A moodle user object or id, null means current user
1430 * @return bool always true or exception
1432 function set_user_preferences(array $prefarray, $user = null) {
1433 foreach ($prefarray as $name => $value) {
1434 set_user_preference($name, $value, $user);
1440 * Unsets a preference completely by deleting it from the database
1442 * If user object submitted, 'preference' property contains the preferences cache.
1444 * @param string $name The key to unset as preference for the specified user
1445 * @param stdClass|int $user A moodle user object or id, null means current user
1446 * @return bool always true or exception
1448 function unset_user_preference($name, $user = null) {
1451 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1452 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1455 if (is_null($user)) {
1457 } else if (isset($user->id)) {
1458 // $user is valid object
1459 } else if (is_numeric($user)) {
1460 $user = (object)array('id'=>(int)$user);
1462 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1465 check_user_preferences_loaded($user);
1467 if (empty($user->id) or isguestuser($user->id)) {
1468 // no permanent storage for not-logged-in user and guest
1469 unset($user->preference[$name]);
1474 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1476 // delete the preference from cache
1477 unset($user->preference[$name]);
1479 // set reload flag for other sessions
1480 mark_user_preferences_changed($user->id);
1486 * Used to fetch user preference(s)
1488 * If no arguments are supplied this function will return
1489 * all of the current user preferences as an array.
1491 * If a name is specified then this function
1492 * attempts to return that particular preference value. If
1493 * none is found, then the optional value $default is returned,
1496 * If user object submitted, 'preference' property contains the preferences cache.
1498 * @param string $name Name of the key to use in finding a preference value
1499 * @param mixed $default Value to be returned if the $name key is not set in the user preferences
1500 * @param stdClass|int $user A moodle user object or id, null means current user
1501 * @return mixed string value or default
1503 function get_user_preferences($name = null, $default = null, $user = null) {
1506 if (is_null($name)) {
1508 } else if (is_numeric($name) or $name === '_lastloaded') {
1509 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1512 if (is_null($user)) {
1514 } else if (isset($user->id)) {
1515 // $user is valid object
1516 } else if (is_numeric($user)) {
1517 $user = (object)array('id'=>(int)$user);
1519 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1522 check_user_preferences_loaded($user);
1525 return $user->preference; // All values
1526 } else if (isset($user->preference[$name])) {
1527 return $user->preference[$name]; // The single string value
1529 return $default; // Default value (null if not specified)
1533 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1536 * Given date parts in user time produce a GMT timestamp.
1538 * @todo Finish documenting this function
1539 * @param int $year The year part to create timestamp of
1540 * @param int $month The month part to create timestamp of
1541 * @param int $day The day part to create timestamp of
1542 * @param int $hour The hour part to create timestamp of
1543 * @param int $minute The minute part to create timestamp of
1544 * @param int $second The second part to create timestamp of
1545 * @param float $timezone Timezone modifier
1546 * @param bool $applydst Toggle Daylight Saving Time, default true
1547 * @return int timestamp
1549 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1551 $strtimezone = NULL;
1552 if (!is_numeric($timezone)) {
1553 $strtimezone = $timezone;
1556 $timezone = get_user_timezone_offset($timezone);
1558 if (abs($timezone) > 13) {
1559 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1561 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1562 $time = usertime($time, $timezone);
1564 $time -= dst_offset_on($time, $strtimezone);
1573 * Format a date/time (seconds) as weeks, days, hours etc as needed
1575 * Given an amount of time in seconds, returns string
1576 * formatted nicely as weeks, days, hours etc as needed
1582 * @param int $totalsecs Time in seconds
1583 * @param object $str Should be a time object
1584 * @return string A nicely formatted date/time string
1586 function format_time($totalsecs, $str=NULL) {
1588 $totalsecs = abs($totalsecs);
1590 if (!$str) { // Create the str structure the slow way
1591 $str->day = get_string('day');
1592 $str->days = get_string('days');
1593 $str->hour = get_string('hour');
1594 $str->hours = get_string('hours');
1595 $str->min = get_string('min');
1596 $str->mins = get_string('mins');
1597 $str->sec = get_string('sec');
1598 $str->secs = get_string('secs');
1599 $str->year = get_string('year');
1600 $str->years = get_string('years');
1604 $years = floor($totalsecs/YEARSECS);
1605 $remainder = $totalsecs - ($years*YEARSECS);
1606 $days = floor($remainder/DAYSECS);
1607 $remainder = $totalsecs - ($days*DAYSECS);
1608 $hours = floor($remainder/HOURSECS);
1609 $remainder = $remainder - ($hours*HOURSECS);
1610 $mins = floor($remainder/MINSECS);
1611 $secs = $remainder - ($mins*MINSECS);
1613 $ss = ($secs == 1) ? $str->sec : $str->secs;
1614 $sm = ($mins == 1) ? $str->min : $str->mins;
1615 $sh = ($hours == 1) ? $str->hour : $str->hours;
1616 $sd = ($days == 1) ? $str->day : $str->days;
1617 $sy = ($years == 1) ? $str->year : $str->years;
1625 if ($years) $oyears = $years .' '. $sy;
1626 if ($days) $odays = $days .' '. $sd;
1627 if ($hours) $ohours = $hours .' '. $sh;
1628 if ($mins) $omins = $mins .' '. $sm;
1629 if ($secs) $osecs = $secs .' '. $ss;
1631 if ($years) return trim($oyears .' '. $odays);
1632 if ($days) return trim($odays .' '. $ohours);
1633 if ($hours) return trim($ohours .' '. $omins);
1634 if ($mins) return trim($omins .' '. $osecs);
1635 if ($secs) return $osecs;
1636 return get_string('now');
1640 * Returns a formatted string that represents a date in user time
1642 * Returns a formatted string that represents a date in user time
1643 * <b>WARNING: note that the format is for strftime(), not date().</b>
1644 * Because of a bug in most Windows time libraries, we can't use
1645 * the nicer %e, so we have to use %d which has leading zeroes.
1646 * A lot of the fuss in the function is just getting rid of these leading
1647 * zeroes as efficiently as possible.
1649 * If parameter fixday = true (default), then take off leading
1650 * zero from %d, else maintain it.
1652 * @param int $date the timestamp in UTC, as obtained from the database.
1653 * @param string $format strftime format. You should probably get this using
1654 * get_string('strftime...', 'langconfig');
1655 * @param float $timezone by default, uses the user's time zone.
1656 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1657 * If false then the leading zero is maintained.
1658 * @return string the formatted date/time.
1660 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1664 $strtimezone = NULL;
1665 if (!is_numeric($timezone)) {
1666 $strtimezone = $timezone;
1669 if (empty($format)) {
1670 $format = get_string('strftimedaydatetime', 'langconfig');
1673 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1675 } else if ($fixday) {
1676 $formatnoday = str_replace('%d', 'DD', $format);
1677 $fixday = ($formatnoday != $format);
1680 $date += dst_offset_on($date, $strtimezone);
1682 $timezone = get_user_timezone_offset($timezone);
1684 if (abs($timezone) > 13) { /// Server time
1686 $datestring = strftime($formatnoday, $date);
1687 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
1688 $datestring = str_replace('DD', $daystring, $datestring);
1690 $datestring = strftime($format, $date);
1693 $date += (int)($timezone * 3600);
1695 $datestring = gmstrftime($formatnoday, $date);
1696 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
1697 $datestring = str_replace('DD', $daystring, $datestring);
1699 $datestring = gmstrftime($format, $date);
1703 /// If we are running under Windows convert from windows encoding to UTF-8
1704 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1706 if ($CFG->ostype == 'WINDOWS') {
1707 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1708 $textlib = textlib_get_instance();
1709 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1717 * Given a $time timestamp in GMT (seconds since epoch),
1718 * returns an array that represents the date in user time
1720 * @todo Finish documenting this function
1722 * @param int $time Timestamp in GMT
1723 * @param float $timezone ?
1724 * @return array An array that represents the date in user time
1726 function usergetdate($time, $timezone=99) {
1728 $strtimezone = NULL;
1729 if (!is_numeric($timezone)) {
1730 $strtimezone = $timezone;
1733 $timezone = get_user_timezone_offset($timezone);
1735 if (abs($timezone) > 13) { // Server time
1736 return getdate($time);
1739 // There is no gmgetdate so we use gmdate instead
1740 $time += dst_offset_on($time, $strtimezone);
1741 $time += intval((float)$timezone * HOURSECS);
1743 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
1745 //be careful to ensure the returned array matches that produced by getdate() above
1748 $getdate['weekday'],
1755 $getdate['minutes'],
1757 ) = explode('_', $datestring);
1763 * Given a GMT timestamp (seconds since epoch), offsets it by
1764 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1767 * @param int $date Timestamp in GMT
1768 * @param float $timezone
1771 function usertime($date, $timezone=99) {
1773 $timezone = get_user_timezone_offset($timezone);
1775 if (abs($timezone) > 13) {
1778 return $date - (int)($timezone * HOURSECS);
1782 * Given a time, return the GMT timestamp of the most recent midnight
1783 * for the current user.
1785 * @param int $date Timestamp in GMT
1786 * @param float $timezone Defaults to user's timezone
1787 * @return int Returns a GMT timestamp
1789 function usergetmidnight($date, $timezone=99) {
1791 $userdate = usergetdate($date, $timezone);
1793 // Time of midnight of this user's day, in GMT
1794 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1799 * Returns a string that prints the user's timezone
1801 * @param float $timezone The user's timezone
1804 function usertimezone($timezone=99) {
1806 $tz = get_user_timezone($timezone);
1808 if (!is_float($tz)) {
1812 if(abs($tz) > 13) { // Server time
1813 return get_string('serverlocaltime');
1816 if($tz == intval($tz)) {
1817 // Don't show .0 for whole hours
1834 * Returns a float which represents the user's timezone difference from GMT in hours
1835 * Checks various settings and picks the most dominant of those which have a value
1839 * @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
1842 function get_user_timezone_offset($tz = 99) {
1846 $tz = get_user_timezone($tz);
1848 if (is_float($tz)) {
1851 $tzrecord = get_timezone_record($tz);
1852 if (empty($tzrecord)) {
1855 return (float)$tzrecord->gmtoff / HOURMINS;
1860 * Returns an int which represents the systems's timezone difference from GMT in seconds
1863 * @param mixed $tz timezone
1864 * @return int if found, false is timezone 99 or error
1866 function get_timezone_offset($tz) {
1873 if (is_numeric($tz)) {
1874 return intval($tz * 60*60);
1877 if (!$tzrecord = get_timezone_record($tz)) {
1880 return intval($tzrecord->gmtoff * 60);
1884 * Returns a float or a string which denotes the user's timezone
1885 * 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)
1886 * means that for this timezone there are also DST rules to be taken into account
1887 * Checks various settings and picks the most dominant of those which have a value
1891 * @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
1894 function get_user_timezone($tz = 99) {
1899 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1900 isset($USER->timezone) ? $USER->timezone : 99,
1901 isset($CFG->timezone) ? $CFG->timezone : 99,
1906 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
1907 $tz = $next['value'];
1910 return is_numeric($tz) ? (float) $tz : $tz;
1914 * Returns cached timezone record for given $timezonename
1918 * @param string $timezonename
1919 * @return mixed timezonerecord object or false
1921 function get_timezone_record($timezonename) {
1923 static $cache = NULL;
1925 if ($cache === NULL) {
1929 if (isset($cache[$timezonename])) {
1930 return $cache[$timezonename];
1933 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
1934 WHERE name = ? ORDER BY year DESC', array($timezonename), true);
1938 * Build and store the users Daylight Saving Time (DST) table
1943 * @param mixed $from_year Start year for the table, defaults to 1971
1944 * @param mixed $to_year End year for the table, defaults to 2035
1945 * @param mixed $strtimezone
1948 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
1949 global $CFG, $SESSION, $DB;
1951 $usertz = get_user_timezone($strtimezone);
1953 if (is_float($usertz)) {
1954 // Trivial timezone, no DST
1958 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1959 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1960 unset($SESSION->dst_offsets);
1961 unset($SESSION->dst_range);
1964 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1965 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1966 // This will be the return path most of the time, pretty light computationally
1970 // Reaching here means we either need to extend our table or create it from scratch
1972 // Remember which TZ we calculated these changes for
1973 $SESSION->dst_offsettz = $usertz;
1975 if(empty($SESSION->dst_offsets)) {
1976 // If we 're creating from scratch, put the two guard elements in there
1977 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1979 if(empty($SESSION->dst_range)) {
1980 // If creating from scratch
1981 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1982 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1984 // Fill in the array with the extra years we need to process
1985 $yearstoprocess = array();
1986 for($i = $from; $i <= $to; ++$i) {
1987 $yearstoprocess[] = $i;
1990 // Take note of which years we have processed for future calls
1991 $SESSION->dst_range = array($from, $to);
1994 // If needing to extend the table, do the same
1995 $yearstoprocess = array();
1997 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1998 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2000 if($from < $SESSION->dst_range[0]) {
2001 // Take note of which years we need to process and then note that we have processed them for future calls
2002 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2003 $yearstoprocess[] = $i;
2005 $SESSION->dst_range[0] = $from;
2007 if($to > $SESSION->dst_range[1]) {
2008 // Take note of which years we need to process and then note that we have processed them for future calls
2009 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2010 $yearstoprocess[] = $i;
2012 $SESSION->dst_range[1] = $to;
2016 if(empty($yearstoprocess)) {
2017 // This means that there was a call requesting a SMALLER range than we have already calculated
2021 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2022 // Also, the array is sorted in descending timestamp order!
2026 static $presets_cache = array();
2027 if (!isset($presets_cache[$usertz])) {
2028 $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');
2030 if(empty($presets_cache[$usertz])) {
2034 // Remove ending guard (first element of the array)
2035 reset($SESSION->dst_offsets);
2036 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2038 // Add all required change timestamps
2039 foreach($yearstoprocess as $y) {
2040 // Find the record which is in effect for the year $y
2041 foreach($presets_cache[$usertz] as $year => $preset) {
2047 $changes = dst_changes_for_year($y, $preset);
2049 if($changes === NULL) {
2052 if($changes['dst'] != 0) {
2053 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2055 if($changes['std'] != 0) {
2056 $SESSION->dst_offsets[$changes['std']] = 0;
2060 // Put in a guard element at the top
2061 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2062 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2065 krsort($SESSION->dst_offsets);
2071 * Calculates the required DST change and returns a Timestamp Array
2075 * @param mixed $year Int or String Year to focus on
2076 * @param object $timezone Instatiated Timezone object
2077 * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
2079 function dst_changes_for_year($year, $timezone) {
2081 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2085 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2086 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2088 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2089 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2091 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2092 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2094 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2095 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2096 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2098 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2099 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2101 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2105 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2108 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2111 function dst_offset_on($time, $strtimezone = NULL) {
2114 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2118 reset($SESSION->dst_offsets);
2119 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2120 if($from <= $time) {
2125 // This is the normal return path
2126 if($offset !== NULL) {
2130 // Reaching this point means we haven't calculated far enough, do it now:
2131 // Calculate extra DST changes if needed and recurse. The recursion always
2132 // moves toward the stopping condition, so will always end.
2135 // We need a year smaller than $SESSION->dst_range[0]
2136 if($SESSION->dst_range[0] == 1971) {
2139 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2140 return dst_offset_on($time, $strtimezone);
2143 // We need a year larger than $SESSION->dst_range[1]
2144 if($SESSION->dst_range[1] == 2035) {
2147 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2148 return dst_offset_on($time, $strtimezone);
2155 * @todo Document what this function does
2156 * @param int $startday
2157 * @param int $weekday
2162 function find_day_in_month($startday, $weekday, $month, $year) {
2164 $daysinmonth = days_in_month($month, $year);
2166 if($weekday == -1) {
2167 // Don't care about weekday, so return:
2168 // abs($startday) if $startday != -1
2169 // $daysinmonth otherwise
2170 return ($startday == -1) ? $daysinmonth : abs($startday);
2173 // From now on we 're looking for a specific weekday
2175 // Give "end of month" its actual value, since we know it
2176 if($startday == -1) {
2177 $startday = -1 * $daysinmonth;
2180 // Starting from day $startday, the sign is the direction
2184 $startday = abs($startday);
2185 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2187 // This is the last such weekday of the month
2188 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2189 if($lastinmonth > $daysinmonth) {
2193 // Find the first such weekday <= $startday
2194 while($lastinmonth > $startday) {
2198 return $lastinmonth;
2203 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2205 $diff = $weekday - $indexweekday;
2210 // This is the first such weekday of the month equal to or after $startday
2211 $firstfromindex = $startday + $diff;
2213 return $firstfromindex;
2219 * Calculate the number of days in a given month
2221 * @param int $month The month whose day count is sought
2222 * @param int $year The year of the month whose day count is sought
2225 function days_in_month($month, $year) {
2226 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2230 * Calculate the position in the week of a specific calendar day
2232 * @param int $day The day of the date whose position in the week is sought
2233 * @param int $month The month of the date whose position in the week is sought
2234 * @param int $year The year of the date whose position in the week is sought
2237 function dayofweek($day, $month, $year) {
2238 // I wonder if this is any different from
2239 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2240 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2243 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2246 * Returns full login url.
2248 * @return string login url
2250 function get_login_url() {
2253 $url = "$CFG->wwwroot/login/index.php";
2255 if (!empty($CFG->loginhttps)) {
2256 $url = str_replace('http:', 'https:', $url);
2263 * This function checks that the current user is logged in and has the
2264 * required privileges
2266 * This function checks that the current user is logged in, and optionally
2267 * whether they are allowed to be in a particular course and view a particular
2269 * If they are not logged in, then it redirects them to the site login unless
2270 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2271 * case they are automatically logged in as guests.
2272 * If $courseid is given and the user is not enrolled in that course then the
2273 * user is redirected to the course enrolment page.
2274 * If $cm is given and the course module is hidden and the user is not a teacher
2275 * in the course then the user is redirected to the course home page.
2277 * When $cm parameter specified, this function sets page layout to 'module'.
2278 * You need to change it manually later if some other layout needed.
2280 * @param mixed $courseorid id of the course or course object
2281 * @param bool $autologinguest default true
2282 * @param object $cm course module object
2283 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2284 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2285 * in order to keep redirects working properly. MDL-14495
2286 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2287 * @return mixed Void, exit, and die depending on path
2289 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2290 global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2292 // setup global $COURSE, themes, language and locale
2293 if (!empty($courseorid)) {
2294 if (is_object($courseorid)) {
2295 $course = $courseorid;
2296 } else if ($courseorid == SITEID) {
2297 $course = clone($SITE);
2299 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2302 if ($cm->course != $course->id) {
2303 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2305 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2306 $PAGE->set_pagelayout('incourse');
2308 $PAGE->set_course($course); // set's up global $COURSE
2311 // do not touch global $COURSE via $PAGE->set_course(),
2312 // the reasons is we need to be able to call require_login() at any time!!
2315 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2319 // If the user is not even logged in yet then make sure they are
2320 if (!isloggedin()) {
2321 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2322 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2323 // misconfigured site guest, just redirect to login page
2324 redirect(get_login_url());
2325 exit; // never reached
2327 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2328 complete_user_login($guest, false);
2329 $SESSION->lang = $lang;
2331 //NOTE: $USER->site check was obsoleted by session test cookie,
2332 // $USER->confirmed test is in login/index.php
2333 if ($preventredirect) {
2334 throw new require_login_exception('You are not logged in');
2337 if ($setwantsurltome) {
2338 // TODO: switch to PAGE->url
2339 $SESSION->wantsurl = $FULLME;
2341 if (!empty($_SERVER['HTTP_REFERER'])) {
2342 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2344 redirect(get_login_url());
2345 exit; // never reached
2349 // loginas as redirection if needed
2350 if ($course->id != SITEID and session_is_loggedinas()) {
2351 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2352 if ($USER->loginascontext->instanceid != $course->id) {
2353 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2358 // check whether the user should be changing password (but only if it is REALLY them)
2359 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2360 $userauth = get_auth_plugin($USER->auth);
2361 if ($userauth->can_change_password() and !$preventredirect) {
2362 $SESSION->wantsurl = $FULLME;
2363 if ($changeurl = $userauth->change_password_url()) {
2364 //use plugin custom url
2365 redirect($changeurl);
2367 //use moodle internal method
2368 if (empty($CFG->loginhttps)) {
2369 redirect($CFG->wwwroot .'/login/change_password.php');
2371 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2372 redirect($wwwroot .'/login/change_password.php');
2376 print_error('nopasswordchangeforced', 'auth');
2380 // Check that the user account is properly set up
2381 if (user_not_fully_set_up($USER)) {
2382 if ($preventredirect) {
2383 throw new require_login_exception('User not fully set-up');
2385 $SESSION->wantsurl = $FULLME;
2386 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2389 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2392 // Do not bother admins with any formalities
2393 if (is_siteadmin()) {
2394 //set accesstime or the user will appear offline which messes up messaging
2395 user_accesstime_log($course->id);
2399 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2400 if (!$USER->policyagreed and !is_siteadmin()) {
2401 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2402 if ($preventredirect) {
2403 throw new require_login_exception('Policy not agreed');
2405 $SESSION->wantsurl = $FULLME;
2406 redirect($CFG->wwwroot .'/user/policy.php');
2407 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2408 if ($preventredirect) {
2409 throw new require_login_exception('Policy not agreed');
2411 $SESSION->wantsurl = $FULLME;
2412 redirect($CFG->wwwroot .'/user/policy.php');
2416 // Fetch the system context, the course context, and prefetch its child contexts
2417 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2418 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2420 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2425 // If the site is currently under maintenance, then print a message
2426 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2427 if ($preventredirect) {
2428 throw new require_login_exception('Maintenance in progress');
2431 print_maintenance_message();
2434 // make sure the course itself is not hidden
2435 if ($course->id == SITEID) {
2436 // frontpage can not be hidden
2438 if (is_role_switched($course->id)) {
2439 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2441 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2442 // originally there was also test of parent category visibility,
2443 // BUT is was very slow in complex queries involving "my courses"
2444 // now it is also possible to simply hide all courses user is not enrolled in :-)
2445 if ($preventredirect) {
2446 throw new require_login_exception('Course is hidden');
2448 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2453 // is the user enrolled?
2454 if ($course->id == SITEID) {
2455 // everybody is enrolled on the frontpage
2458 if (session_is_loggedinas()) {
2459 // Make sure the REAL person can access this course first
2460 $realuser = session_get_realuser();
2461 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2462 if ($preventredirect) {
2463 throw new require_login_exception('Invalid course login-as access');
2465 echo $OUTPUT->header();
2466 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2470 // very simple enrolment caching - changes in course setting are not reflected immediately
2471 if (!isset($USER->enrol)) {
2472 $USER->enrol = array();
2473 $USER->enrol['enrolled'] = array();
2474 $USER->enrol['tempguest'] = array();
2479 if (is_viewing($coursecontext, $USER)) {
2480 // ok, no need to mess with enrol
2484 if (isset($USER->enrol['enrolled'][$course->id])) {
2485 if ($USER->enrol['enrolled'][$course->id] == 0) {
2487 } else if ($USER->enrol['enrolled'][$course->id] > time()) {
2491 unset($USER->enrol['enrolled'][$course->id]);
2494 if (isset($USER->enrol['tempguest'][$course->id])) {
2495 if ($USER->enrol['tempguest'][$course->id] == 0) {
2497 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2501 unset($USER->enrol['tempguest'][$course->id]);
2502 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2508 } else if (is_enrolled($coursecontext, $USER, '', true)) {
2509 // active participants may always access
2510 // TODO: refactor this into some new function
2512 $sql = "SELECT MAX(ue.timeend)
2513 FROM {user_enrolments} ue
2514 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2515 JOIN {user} u ON u.id = ue.userid
2516 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0
2517 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
2518 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE,
2519 'userid'=>$USER->id, 'courseid'=>$coursecontext->instanceid, 'now1'=>$now, 'now2'=>$now);
2520 $until = $DB->get_field_sql($sql, $params);
2521 if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) {
2522 $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD;
2525 $USER->enrol['enrolled'][$course->id] = $until;
2528 // remove traces of previous temp guest access
2529 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2532 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2533 $enrols = enrol_get_plugins(true);
2534 // first ask all enabled enrol instances in course if they want to auto enrol user
2535 foreach($instances as $instance) {
2536 if (!isset($enrols[$instance->enrol])) {
2539 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2540 if ($until !== false) {
2541 $USER->enrol['enrolled'][$course->id] = $until;
2542 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2547 // if not enrolled yet try to gain temporary guest access
2549 foreach($instances as $instance) {
2550 if (!isset($enrols[$instance->enrol])) {
2553 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2554 if ($until !== false) {
2555 $USER->enrol['tempguest'][$course->id] = $until;
2565 if ($preventredirect) {
2566 throw new require_login_exception('Not enrolled');
2568 $SESSION->wantsurl = $FULLME;
2569 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2574 if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2575 if ($preventredirect) {
2576 throw new require_login_exception('Activity is hidden');
2578 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2581 // groupmembersonly access control
2582 if (!empty($CFG->enablegroupmembersonly) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2583 if (isguestuser() or !groups_has_membership($cm)) {
2584 if ($preventredirect) {
2585 throw new require_login_exception('Not member of a group');
2587 print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
2591 // Conditional activity access control
2592 if (!empty($CFG->enableavailability) and $cm) {
2593 // TODO: this is going to work with login-as-user, sorry!
2594 // We cache conditional access in session
2595 if (!isset($SESSION->conditionaccessok)) {
2596 $SESSION->conditionaccessok = array();
2598 // If you have been allowed into the module once then you are allowed
2599 // in for rest of session, no need to do conditional checks
2600 if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
2601 // Get condition info (does a query for the availability table)
2602 require_once($CFG->libdir.'/conditionlib.php');
2603 $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
2604 // Check condition for user (this will do a query if the availability
2605 // information depends on grade or completion information)
2606 if ($ci->is_available($junk) || has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2607 $SESSION->conditionaccessok[$cm->id] = true;
2609 print_error('activityiscurrentlyhidden');
2614 // Finally access granted, update lastaccess times
2615 user_accesstime_log($course->id);
2620 * This function just makes sure a user is logged out.
2624 function require_logout() {
2628 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2630 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2631 foreach($authsequence as $authname) {
2632 $authplugin = get_auth_plugin($authname);
2633 $authplugin->prelogout_hook();
2637 session_get_instance()->terminate_current();
2641 * Weaker version of require_login()
2643 * This is a weaker version of {@link require_login()} which only requires login
2644 * when called from within a course rather than the site page, unless
2645 * the forcelogin option is turned on.
2646 * @see require_login()
2649 * @param mixed $courseorid The course object or id in question
2650 * @param bool $autologinguest Allow autologin guests if that is wanted
2651 * @param object $cm Course activity module if known
2652 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2653 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2654 * in order to keep redirects working properly. MDL-14495
2655 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2658 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2659 global $CFG, $PAGE, $SITE;
2660 if (!empty($CFG->forcelogin)) {
2661 // login required for both SITE and courses
2662 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2664 } else if (!empty($cm) and !$cm->visible) {
2665 // always login for hidden activities
2666 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2668 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2669 or (!is_object($courseorid) and $courseorid == SITEID)) {
2670 //login for SITE not required
2671 if ($cm and empty($cm->visible)) {
2672 // hidden activities are not accessible without login
2673 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2674 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2675 // not-logged-in users do not have any group membership
2676 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2678 // We still need to instatiate PAGE vars properly so that things
2679 // that rely on it like navigation function correctly.
2680 if (!empty($courseorid)) {
2681 if (is_object($courseorid)) {
2682 $course = $courseorid;
2684 $course = clone($SITE);
2687 if ($cm->course != $course->id) {
2688 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2690 $PAGE->set_cm($cm, $course);
2691 $PAGE->set_pagelayout('incourse');
2693 $PAGE->set_course($course);
2696 // If $PAGE->course, and hence $PAGE->context, have not already been set
2697 // up properly, set them up now.
2698 $PAGE->set_course($PAGE->course);
2700 //TODO: verify conditional activities here
2701 user_accesstime_log(SITEID);
2706 // course login always required
2707 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2712 * Require key login. Function terminates with error if key not found or incorrect.
2718 * @uses NO_MOODLE_COOKIES
2719 * @uses PARAM_ALPHANUM
2720 * @param string $script unique script identifier
2721 * @param int $instance optional instance id
2722 * @return int Instance ID
2724 function require_user_key_login($script, $instance=null) {
2725 global $USER, $SESSION, $CFG, $DB;
2727 if (!NO_MOODLE_COOKIES) {
2728 print_error('sessioncookiesdisable');
2732 @session_write_close();
2734 $keyvalue = required_param('key', PARAM_ALPHANUM);
2736 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2737 print_error('invalidkey');
2740 if (!empty($key->validuntil) and $key->validuntil < time()) {
2741 print_error('expiredkey');
2744 if ($key->iprestriction) {
2745 $remoteaddr = getremoteaddr(null);
2746 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2747 print_error('ipmismatch');
2751 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2752 print_error('invaliduserid');
2755 /// emulate normal session
2756 session_set_user($user);
2758 /// note we are not using normal login
2759 if (!defined('USER_KEY_LOGIN')) {
2760 define('USER_KEY_LOGIN', true);
2763 /// return instance id - it might be empty
2764 return $key->instance;
2768 * Creates a new private user access key.
2771 * @param string $script unique target identifier
2772 * @param int $userid
2773 * @param int $instance optional instance id
2774 * @param string $iprestriction optional ip restricted access
2775 * @param timestamp $validuntil key valid only until given data
2776 * @return string access key value
2778 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2781 $key = new stdClass();
2782 $key->script = $script;
2783 $key->userid = $userid;
2784 $key->instance = $instance;
2785 $key->iprestriction = $iprestriction;
2786 $key->validuntil = $validuntil;
2787 $key->timecreated = time();
2789 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
2790 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
2792 $key->value = md5($userid.'_'.time().random_string(40));
2794 $DB->insert_record('user_private_key', $key);
2799 * Delete the user's new private user access keys for a particular script.
2802 * @param string $script unique target identifier
2803 * @param int $userid
2806 function delete_user_key($script,$userid) {
2808 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
2812 * Gets a private user access key (and creates one if one doesn't exist).
2815 * @param string $script unique target identifier
2816 * @param int $userid
2817 * @param int $instance optional instance id
2818 * @param string $iprestriction optional ip restricted access
2819 * @param timestamp $validuntil key valid only until given data
2820 * @return string access key value
2822 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2825 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
2826 'instance'=>$instance, 'iprestriction'=>$iprestriction,
2827 'validuntil'=>$validuntil))) {
2830 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
2836 * Modify the user table by setting the currently logged in user's
2837 * last login to now.
2841 * @return bool Always returns true
2843 function update_user_login_times() {
2846 $user = new stdClass();
2847 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2848 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2850 $user->id = $USER->id;
2852 $DB->update_record('user', $user);
2857 * Determines if a user has completed setting up their account.
2859 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
2862 function user_not_fully_set_up($user) {
2863 if (isguestuser($user)) {
2866 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
2870 * Check whether the user has exceeded the bounce threshold
2874 * @param user $user A {@link $USER} object
2875 * @return bool true=>User has exceeded bounce threshold
2877 function over_bounce_threshold($user) {
2880 if (empty($CFG->handlebounces)) {
2884 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2888 // set sensible defaults
2889 if (empty($CFG->minbounces)) {
2890 $CFG->minbounces = 10;
2892 if (empty($CFG->bounceratio)) {
2893 $CFG->bounceratio = .20;
2897 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2898 $bouncecount = $bounce->value;
2900 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2901 $sendcount = $send->value;
2903 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2907 * Used to increment or reset email sent count
2910 * @param user $user object containing an id
2911 * @param bool $reset will reset the count to 0
2914 function set_send_count($user,$reset=false) {
2917 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2921 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
2922 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2923 $DB->update_record('user_preferences', $pref);
2925 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2927 $pref = new stdClass();
2928 $pref->name = 'email_send_count';
2930 $pref->userid = $user->id;
2931 $DB->insert_record('user_preferences', $pref, false);
2936 * Increment or reset user's email bounce count
2939 * @param user $user object containing an id
2940 * @param bool $reset will reset the count to 0
2942 function set_bounce_count($user,$reset=false) {
2945 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
2946 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2947 $DB->update_record('user_preferences', $pref);
2949 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2951 $pref = new stdClass();
2952 $pref->name = 'email_bounce_count';
2954 $pref->userid = $user->id;
2955 $DB->insert_record('user_preferences', $pref, false);
2960 * Keeps track of login attempts
2964 function update_login_count() {
2969 if (empty($SESSION->logincount)) {
2970 $SESSION->logincount = 1;
2972 $SESSION->logincount++;
2975 if ($SESSION->logincount > $max_logins) {
2976 unset($SESSION->wantsurl);
2977 print_error('errortoomanylogins');
2982 * Resets login attempts
2986 function reset_login_count() {
2989 $SESSION->logincount = 0;
2993 * Returns reference to full info about modules in course (including visibility).
2994 * Cached and as fast as possible (0 or 1 db query).
2999 * @uses CONTEXT_MODULE
3000 * @uses MAX_MODINFO_CACHE_SIZE
3001 * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
3002 * @param int $userid Defaults to current user id
3003 * @return mixed courseinfo object or nothing if resetting
3005 function &get_fast_modinfo(&$course, $userid=0) {
3006 global $CFG, $USER, $DB;
3007 require_once($CFG->dirroot.'/course/lib.php');
3009 if (!empty($CFG->enableavailability)) {
3010 require_once($CFG->libdir.'/conditionlib.php');
3013 static $cache = array();
3015 if ($course === 'reset') {
3018 return $nothing; // we must return some reference
3021 if (empty($userid)) {
3022 $userid = $USER->id;
3025 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
3026 return $cache[$course->id];
3029 if (empty($course->modinfo)) {
3030 // no modinfo yet - load it
3031 rebuild_course_cache($course->id);
3032 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
3035 $modinfo = new stdClass();
3036 $modinfo->courseid = $course->id;
3037 $modinfo->userid = $userid;
3038 $modinfo->sections = array();
3039 $modinfo->cms = array();
3040 $modinfo->instances = array();
3041 $modinfo->groups = null; // loaded only when really needed - the only one db query
3043 $info = unserialize($course->modinfo);
3044 if (!is_array($info)) {
3045 // hmm, something is wrong - lets try to fix it
3046 rebuild_course_cache($course->id);
3047 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
3048 $info = unserialize($course->modinfo);
3049 if (!is_array($info)) {
3055 // detect if upgrade required
3056 $first = reset($info);
3057 if (!isset($first->id)) {
3058 rebuild_course_cache($course->id);
3059 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
3060 $info = unserialize($course->modinfo);
3061 if (!is_array($info)) {
3067 $modlurals = array();
3069 // If we haven't already preloaded contexts for the course, do it now
3070 preload_course_contexts($course->id);
3072 foreach ($info as $mod) {
3073 if (empty($mod->name)) {
3074 // something is wrong here
3077 // reconstruct minimalistic $cm
3078 $cm = new stdClass();
3080 $cm->instance = $mod->id;
3081 $cm->course = $course->id;
3082 $cm->modname = $mod->mod;
3083 $cm->idnumber = $mod->idnumber;
3084 $cm->name = $mod->name;
3085 $cm->visible = $mod->visible;
3086 $cm->sectionnum = $mod->section;
3087 $cm->groupmode = $mod->groupmode;
3088 $cm->groupingid = $mod->groupingid;
3089 $cm->groupmembersonly = $mod->groupmembersonly;
3090 $cm->indent = $mod->indent;
3091 $cm->completion = $mod->completion;
3092 $cm->extra = isset($mod->extra) ? $mod->extra : '';
3093 $cm->icon = isset($mod->icon) ? $mod->icon : '';
3094 $cm->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
3095 $cm->uservisible = true;
3096 if (!empty($CFG->enableavailability)) {
3097 // We must have completion information from modinfo. If it's not
3098 // there, cache needs rebuilding
3099 if(!isset($mod->availablefrom)) {
3100 debugging('enableavailability option was changed; rebuilding '.
3101 'cache for course '.$course->id);
3102 rebuild_course_cache($course->id,true);
3103 // Re-enter this routine to do it all properly
3104 return get_fast_modinfo($course, $userid);
3106 $cm->availablefrom = $mod->availablefrom;
3107 $cm->availableuntil = $mod->availableuntil;
3108 $cm->showavailability = $mod->showavailability;
3109 $cm->conditionscompletion = $mod->conditionscompletion;
3110 $cm->conditionsgrade = $mod->conditionsgrade;
3113 // preload long names plurals and also check module is installed properly
3114 if (!isset($modlurals[$cm->modname])) {
3115 if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
3118 $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
3120 $cm->modplural = $modlurals[$cm->modname];
3121 $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id);
3123 if (!empty($CFG->enableavailability)) {
3124 // Unfortunately the next call really wants to call
3125 // get_fast_modinfo, but that would be recursive, so we fake up a
3126 // modinfo for it already
3127 if (empty($minimalmodinfo)) { //TODO: this is suspicious (skodak)
3128 $minimalmodinfo = new stdClass();
3129 $minimalmodinfo->cms = array();
3130 foreach($info as $mod) {
3131 if (empty($mod->name)) {
3132 // something is wrong here
3135 $minimalcm = new stdClass();
3136 $minimalcm->id = $mod->cm;
3137 $minimalcm->name = $mod->name;
3138 $minimalmodinfo->cms[$minimalcm->id]=$minimalcm;
3142 // Get availability information
3143 $ci = new condition_info($cm);
3144 $cm->available = $ci->is_available($cm->availableinfo, true, $userid, $minimalmodinfo);
3146 $cm->available = true;
3148 if ((!$cm->visible or !$cm->available) and !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
3149 $cm->uservisible = false;
3151 } else if (!empty($CFG->enablegroupmembersonly) and !empty($cm->groupmembersonly)
3152 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
3153 if (is_null($modinfo->groups)) {
3154 $modinfo->groups = groups_get_user_groups($course->id, $userid);
3156 if (empty($modinfo->groups[$cm->groupingid])) {
3157 $cm->uservisible = false;
3161 if (!isset($modinfo->instances[$cm->modname])) {
3162 $modinfo->instances[$cm->modname] = array();
3164 $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
3165 $modinfo->cms[$cm->id] =& $cm;
3167 // reconstruct sections
3168 if (!isset($modinfo->sections[$cm->sectionnum])) {
3169 $modinfo->sections[$cm->sectionnum] = array();
3171 $modinfo->sections[$cm->sectionnum][] = $cm->id;
3176 unset($cache[$course->id]); // prevent potential reference problems when switching users
3177 $cache[$course->id] = $modinfo;
3179 // Ensure cache does not use too much RAM
3180 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
3183 unset($cache[$key]);
3186 return $cache[$course->id];
3190 * Determines if the currently logged in user is in editing mode.
3191 * Note: originally this function had $userid parameter - it was not usable anyway
3193 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3194 * @todo Deprecated function remove when ready
3197 * @uses DEBUG_DEVELOPER
3200 function isediting() {
3202 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3203 return $PAGE->user_is_editing();
3207 * Determines if the logged in user is currently moving an activity
3210 * @param int $courseid The id of the course being tested
3213 function ismoving($courseid) {
3216 if (!empty($USER->activitycopy)) {
3217 return ($USER->activitycopycourse == $courseid);
3223 * Returns a persons full name
3225 * Given an object containing firstname and lastname
3226 * values, this function returns a string with the
3227 * full name of the person.
3228 * The result may depend on system settings
3229 * or language. 'override' will force both names
3230 * to be used even if system settings specify one.
3234 * @param object $user A {@link $USER} object to get full name of
3235 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3238 function fullname($user, $override=false) {
3239 global $CFG, $SESSION;
3241 if (!isset($user->firstname) and !isset($user->lastname)) {
3246 if (!empty($CFG->forcefirstname)) {
3247 $user->firstname = $CFG->forcefirstname;
3249 if (!empty($CFG->forcelastname)) {
3250 $user->lastname = $CFG->forcelastname;
3254 if (!empty($SESSION->fullnamedisplay)) {
3255 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3258 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3259 return $user->firstname .' '. $user->lastname;
3261 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3262 return $user->lastname .' '. $user->firstname;
3264 } else if ($CFG->fullnamedisplay == 'firstname') {
3266 return get_string('fullnamedisplay', '', $user);
3268 return $user->firstname;
3272 return get_string('fullnamedisplay', '', $user);
3276 * Returns whether a given authentication plugin exists.
3279 * @param string $auth Form of authentication to check for. Defaults to the
3280 * global setting in {@link $CFG}.
3281 * @return boolean Whether the plugin is available.
3283 function exists_auth_plugin($auth) {
3286 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3287 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3293 * Checks if a given plugin is in the list of enabled authentication plugins.
3295 * @param string $auth Authentication plugin.
3296 * @return boolean Whether the plugin is enabled.
3298 function is_enabled_auth($auth) {
3303 $enabled = get_enabled_auth_plugins();
3305 return in_array($auth, $enabled);
3309 * Returns an authentication plugin instance.
3312 * @param string $auth name of authentication plugin
3313 * @return auth_plugin_base An instance of the required authentication plugin.
3315 function get_auth_plugin($auth) {
3318 // check the plugin exists first
3319 if (! exists_auth_plugin($auth)) {
3320 print_error('authpluginnotfound', 'debug', '', $auth);
3323 // return auth plugin instance
3324 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3325 $class = "auth_plugin_$auth";
3330 * Returns array of active auth plugins.
3332 * @param bool $fix fix $CFG->auth if needed
3335 function get_enabled_auth_plugins($fix=false) {
3338 $default = array('manual', 'nologin');
3340 if (empty($CFG->auth)) {
3343 $auths = explode(',', $CFG->auth);
3347 $auths = array_unique($auths);
3348 foreach($auths as $k=>$authname) {
3349 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3353 $newconfig = implode(',', $auths);
3354 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3355 set_config('auth', $newconfig);
3359 return (array_merge($default, $auths));
3363 * Returns true if an internal authentication method is being used.
3364 * if method not specified then, global default is assumed
3366 * @param string $auth Form of authentication required
3369 function is_internal_auth($auth) {
3370 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3371 return $authplugin->is_internal();
3375 * Returns true if the user is a 'restored' one
3377 * Used in the login process to inform the user
3378 * and allow him/her to reset the password
3382 * @param string $username username to be checked
3385 function is_restored_user($username) {
3388 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3392 * Returns an array of user fields
3394 * @return array User field/column names
3396 function get_user_fieldnames() {
3399 $fieldarray = $DB->get_columns('user');
3400 unset($fieldarray['id']);
3401 $fieldarray = array_keys($fieldarray);
3407 * Creates a bare-bones user record
3409 * @todo Outline auth types and provide code example
3413 * @param string $username New user's username to add to record
3414 * @param string $password New user's password to add to record
3415 * @param string $auth Form of authentication required
3416 * @return object A {@link $USER} object
3418 function create_user_record($username, $password, $auth='manual') {
3421 //just in case check text case
3422 $username = trim(moodle_strtolower($username));
3424 $authplugin = get_auth_plugin($auth);
3426 $newuser = new stdClass();
3428 if ($newinfo = $authplugin->get_userinfo($username)) {
3429 $newinfo = truncate_userinfo($newinfo);
3430 foreach ($newinfo as $key => $value){
3431 $newuser->$key = $value;
3435 if (!empty($newuser->email)) {
3436 if (email_is_not_allowed($newuser->email)) {
3437 unset($newuser->email);
3441 if (!isset($newuser->city)) {
3442 $newuser->city = '';
3445 $newuser->auth = $auth;
3446 $newuser->username = $username;
3449 // user CFG lang for user if $newuser->lang is empty
3450 // or $user->lang is not an installed language
3451 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3452 $newuser->lang = $CFG->lang;
3454 $newuser->confirmed = 1;
3455 $newuser->lastip = getremoteaddr();
3456 $newuser->timemodified = time();
3457 $newuser->mnethostid = $CFG->mnet_localhost_id;
3459 $DB->insert_record('user', $newuser);
3460 $user = get_complete_user_data('username', $newuser->username);
3461 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3462 set_user_preference('auth_forcepasswordchange', 1, $user->id);
3464 update_internal_user_password($user, $password);
3469 * Will update a local user record from an external source
3472 * @param string $username New user's username to add to record
3473 * @param string $authplugin Unused
3474 * @return user A {@link $USER} object
3476 function update_user_record($username, $authplugin) {
3479 $username = trim(moodle_strtolower($username)); /// just in case check text case
3481 $oldinfo = $DB->get_record('user', array('username'=>$username), 'username, auth');
3482 $userauth = get_auth_plugin($oldinfo->auth);
3484 if ($newinfo = $userauth->get_userinfo($username)) {
3485 $newinfo = truncate_userinfo($newinfo);
3486 foreach ($newinfo as $key => $value){
3487 if ($key === 'username') {
3488 // 'username' is not a mapped updateable/lockable field, so skip it.
3491 $confval = $userauth->config->{'field_updatelocal_' . $key};
3492 $lockval = $userauth->config->{'field_lock_' . $key};
3493 if (empty($confval) || empty($lockval)) {
3496 if ($confval === 'onlogin') {
3497 // MDL-4207 Don't overwrite modified user profile values with
3498 // empty LDAP values when 'unlocked if empty' is set. The purpose
3499 // of the setting 'unlocked if empty' is to allow the user to fill
3500 // in a value for the selected field _if LDAP is giving
3501 // nothing_ for this field. Thus it makes sense to let this value
3502 // stand in until LDAP is giving a value for this field.
3503 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3504 $DB->set_field('user', $key, $value, array('username'=>$username));
3510 return get_complete_user_data('username', $username);
3514 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3515 * which may have large fields
3517 * @todo Add vartype handling to ensure $info is an array
3519 * @param array $info Array of user properties to truncate if needed
3520 * @return array The now truncated information that was passed in
3522 function truncate_userinfo($info) {
3523 // define the limits
3533 'institution' => 40,
3541 $textlib = textlib_get_instance();
3542 // apply where needed
3543 foreach (array_keys($info) as $key) {
3544 if (!empty($limit[$key])) {
3545 $info[$key] = trim($textlib->substr($info[$key],0, $limit[$key]));
3553 * Marks user deleted in internal user database and notifies the auth plugin.
3554 * Also unenrols user from all roles and does other cleanup.
3556 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3558 * @param object $user User object before delete
3559 * @return boolean always true
3561 function delete_user($user) {
3563 require_once($CFG->libdir.'/grouplib.php');
3564 require_once($CFG->libdir.'/gradelib.php');
3565 require_once($CFG->dirroot.'/message/lib.php');
3566 require_once($CFG->dirroot.'/tag/lib.php');
3568 // delete all grades - backup is kept in grade_grades_history table
3569 grade_user_delete($user->id);
3571 //move unread messages from this user to read
3572 message_move_userfrom_unread2read($user->id);
3574 // TODO: remove from cohorts using standard API here
3577 tag_set('user', $user->id, array());
3579 // unconditionally unenrol from all courses
3580 enrol_user_delete($user);
3582 // unenrol from all roles in all contexts
3583 role_unassign_all(array('userid'=>$user->id)); // this might be slow but it is really needed - modules might do some extra cleanup!
3585 //now do a brute force cleanup
3587 // remove from all cohorts
3588 $DB->delete_records('cohort_members', array('userid'=>$user->id));
3590 // remove from all groups
3591 $DB->delete_records('groups_members', array('userid'=>$user->id));
3593 // brute force unenrol from all courses
3594 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
3596 // purge user preferences
3597 $DB->delete_records('user_preferences', array('userid'=>$user->id));
3599 // purge user extra profile info
3600 $DB->delete_records('user_info_data', array('userid'=>$user->id));
3602 // last course access not necessary either
3603 $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
3605 // now do a final accesslib cleanup - removes all role assignments in user context and context itself
3606 delete_context(CONTEXT_USER, $user->id);
3608 // workaround for bulk deletes of users with the same email address
3609 $delname = "$user->email.".time();
3610 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3614 // mark internal user record as "deleted"
3615 $updateuser = new stdClass();
3616 $updateuser->id = $user->id;
3617 $updateuser->deleted = 1;
3618 $updateuser->username = $delname; // Remember it just in case
3619 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
3620 $updateuser->idnumber = ''; // Clear this field to free it up
3621 $updateuser->timemodified = time();
3623 $DB->update_record('user', $updateuser);
3625 // notify auth plugin - do not block the delete even when plugin fails
3626 $authplugin = get_auth_plugin($user->auth);
3627 $authplugin->user_delete($user);
3629 // any plugin that needs to cleanup should register this event
3630 events_trigger('user_deleted', $user);
3636 * Retrieve the guest user object
3640 * @return user A {@link $USER} object
3642 function guest_user() {
3645 if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
3646 $newuser->confirmed = 1;
3647 $newuser->lang = $CFG->lang;
3648 $newuser->lastip = getremoteaddr();
3655 * Authenticates a user against the chosen authentication mechanism
3657 * Given a username and password, this function looks them
3658 * up using the currently selected authentication mechanism,
3659 * and if the authentication is successful, it returns a
3660 * valid $user object from the 'user' table.
3662 * Uses auth_ functions from the currently active auth module
3664 * After authenticate_user_login() returns success, you will need to
3665 * log that the user has logged in, and call complete_user_login() to set
3668 * Note: this function works only with non-mnet accounts!
3670 * @param string $username User's username
3671 * @param string $password User's password
3672 * @return user|flase A {@link $USER} object or false if error
3674 function authenticate_user_login($username, $password) {
3677 $authsenabled = get_enabled_auth_plugins();
3679 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
3680 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
3681 if (!empty($user->suspended)) {
3682 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3683 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3686 if ($auth=='nologin' or !is_enabled_auth($auth)) {
3687 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3688 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3691 $auths = array($auth);
3694 // check if there's a deleted record (cheaply)
3695 if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
3696 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3700 // User does not exist
3701 $auths = $authsenabled;
3702 $user = new stdClass();
3706 foreach ($auths as $auth) {
3707 $authplugin = get_auth_plugin($auth);
3709 // on auth fail fall through to the next plugin
3710 if (!$authplugin->user_login($username, $password)) {
3714 // successful authentication
3715 if ($user->id) { // User already exists in database
3716 if (empty($user->auth)) { // For some reason auth isn't set yet
3717 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
3718 $user->auth = $auth;
3720 if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3721 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
3722 $user->firstaccess = $user->timemodified;
3725 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3727 if (!$authplugin->is_internal()) { // update user record from external DB
3728 $user = update_user_record($username, get_auth_plugin($user->auth));
3731 // if user not found, create him
3732 $user = create_user_record($username, $password, $auth);
3735 $authplugin->sync_roles($user);
3737 foreach ($authsenabled as $hau) {
3738 $hauth = get_auth_plugin($hau);
3739 $hauth->user_authenticated_hook($user, $username, $password);
3742 if (empty($user->id)) {
3746 if (!empty($user->suspended)) {
3747 // just in case some auth plugin suspended account
3748 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3749 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3756 // failed if all the plugins have failed
3757 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
3758 if (debugging('', DEBUG_ALL)) {
3759 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3765 * Call to complete the user login process after authenticate_user_login()
3766 * has succeeded. It will setup the $USER variable and other required bits
3770 * - It will NOT log anything -- up to the caller to decide what to log.
3772 * @param object $user
3773 * @param bool $setcookie
3774 * @return object A {@link $USER} object - BC only, do not use
3776 function complete_user_login($user, $setcookie=true) {
3779 // regenerate session id and delete old session,
3780 // this helps prevent session fixation attacks from the same domain
3781 session_regenerate_id(true);
3783 // check enrolments, load caps and setup $USER object
3784 session_set_user($user);
3786 // reload preferences from DB
3787 unset($user->preference);
3788 check_user_preferences_loaded($user);
3790 // update login times
3791 update_user_login_times();
3793 // extra session prefs init
3794 set_login_session_preferences();
3796 if (isguestuser()) {
3797 // no need to continue when user is THE guest
3802 if (empty($CFG->nolastloggedin)) {
3803 set_moodle_cookie($USER->username);
3805 // do not store last logged in user in cookie
3806 // auth plugins can temporarily override this from loginpage_hook()
3807 // do not save $CFG->nolastloggedin in database!
3808 set_moodle_cookie('');
3812 /// Select password change url
3813 $userauth = get_auth_plugin($USER->auth);
3815 /// check whether the user should be changing password
3816 if (get_user_preferences('auth_forcepasswordchange', false)){
3817 if ($userauth->can_change_password()) {
3818 if ($changeurl = $userauth->change_password_url()) {
3819 redirect($changeurl);
3821 redirect($CFG->httpswwwroot.'/login/change_password.php');
3824 print_error('nopasswordchangeforced', 'auth');
3831 * Compare password against hash stored in internal user table.
3832 * If necessary it also updates the stored hash to new format.
3835 * @param object $user
3836 * @param string $password plain text password
3837 * @return bool is password valid?
3839 function validate_internal_user_password(&$user, $password) {
3842 if (!isset($CFG->passwordsaltmain)) {
3843 $CFG->passwordsaltmain = '';
3848 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)) {
3851 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
3852 $alt = 'passwordsaltalt'.$i;
3853 if (!empty($CFG->$alt)) {
3854 if ($user->password == md5($password.$CFG->$alt)) {
3863 // force update of password hash using latest main password salt and encoding if needed
3864 update_internal_user_password($user, $password);
3871 * Calculate hashed value from password using current hash mechanism.
3874 * @param string $password
3875 * @return string password hash
3877 function hash_internal_user_password($password) {
3880 if (isset($CFG->passwordsaltmain)) {
3881 return md5($password.$CFG->passwordsaltmain);
3883 return md5($password);
3888 * Update password hash in user object.
3890 * @param object $user
3891 * @param string $password plain text password
3892 * @return bool always returns true
3894 function update_internal_user_password(&$user, $password) {
3897 $authplugin = get_auth_plugin($user->auth);
3898 if ($authplugin->prevent_local_passwords()) {
3899 $hashedpassword = 'not cached';
3901 $hashedpassword = hash_internal_user_password($password);
3904 if ($user->password !== $hashedpassword) {
3905 $DB->set_field('user', 'password', $hashedpassword, array('id'=>$user->id));
3906 $user->password = $hashedpassword;
3913 * Get a complete user record, which includes all the info
3914 * in the user record.
3916 * Intended for setting as $USER session variable
3918 * @param string $field The user field to be checked for a given value.
3919 * @param string $value The value to match for $field.
3920 * @param int $mnethostid
3921 * @return mixed False, or A {@link $USER} object.
3923 function get_complete_user_data($field, $value, $mnethostid = null) {
3926 if (!$field || !$value) {
3930 /// Build the WHERE clause for an SQL query
3931 $params = array('fieldval'=>$value);
3932 $constraints = "$field = :fieldval AND deleted <> 1";
3934 // If we are loading user data based on anything other than id,
3935 // we must also restrict our search based on mnet host.
3936 if ($field != 'id') {
3937 if (empty($mnethostid)) {
3938 // if empty, we restrict to local users
3939 $mnethostid = $CFG->mnet_localhost_id;
3942 if (!empty($mnethostid)) {
3943 $params['mnethostid'] = $mnethostid;
3944 $constraints .= " AND mnethostid = :mnethostid";
3947 /// Get all the basic user data
3949 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
3953 /// Get various settings and preferences
3955 if ($displays = $DB->get_records('course_display', array('userid'=>$user->id))) {
3956 foreach ($displays as $display) {
3957 $user->display[$display->course] = $display->display;
3961 // preload preference cache
3962 check_user_preferences_loaded($user);
3964 // load course enrolment related stuff
3965 $user->lastcourseaccess = array(); // during last session
3966 $user->currentcourseaccess = array(); // during current session
3967 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid'=>$user->id))) {
3968 foreach ($lastaccesses as $lastaccess) {
3969 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
3973 $sql = "SELECT g.id, g.courseid
3974 FROM {groups} g, {groups_members} gm
3975 WHERE gm.groupid=g.id AND gm.userid=?";
3977 // this is a special hack to speedup calendar display
3978 $user->groupmember = array();
3979 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
3980 foreach ($groups as $group) {
3981 if (!array_key_exists($group->courseid, $user->groupmember)) {
3982 $user->groupmember[$group->courseid] = array();
3984 $user->groupmember[$group->courseid][$group->id] = $group->id;
3988 /// Add the custom profile fields to the user record
3989 require_once($CFG->dirroot.'/user/profile/lib.php');
3990 profile_load_custom_fields($user);
3992 /// Rewrite some variables if necessary
3993 if (!empty($user->description)) {
3994 $user->description = true; // No need to cart all of it around
3996 if (isguestuser($user)) {
3997 $user->lang = $CFG->lang; // Guest language always same as site
3998 $user->firstname = get_string('guestuser'); // Name always in current language
3999 $user->lastname = ' ';
4006 * Validate a password against the configured password policy
4009 * @param string $password the password to be checked against the password policy
4010 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4011 * @return bool true if the password is valid according to the policy. false otherwise.
4013 function check_password_policy($password, &$errmsg) {
4016 if (empty($CFG->passwordpolicy)) {
4020 $textlib = textlib_get_instance();
4022 if ($textlib->strlen($password) < $CFG->minpasswordlength) {
4023 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4026 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4027 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4030 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4031 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4034 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4035 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4038 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4039 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4041 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4042 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4045 if ($errmsg == '') {
4054 * When logging in, this function is run to set certain preferences
4055 * for the current SESSION
4060 function set_login_session_preferences() {
4061 global $SESSION, $CFG;
4063 $SESSION->justloggedin = true;
4065 unset($SESSION->lang);
4067 // Restore the calendar filters, if saved
4068 if (intval(get_user_preferences('calendar_persistflt', 0))) {
4069 include_once($CFG->dirroot.'/calendar/lib.php');
4070 calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
4076 * Delete a course, including all related data from the database,
4077 * and any associated files.
4081 * @param mixed $courseorid The id of the course or course object to delete.
4082 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4083 * @return bool true if all the removals succeeded. false if there were any failures. If this
4084 * method returns false, some of the removals will probably have succeeded, and others
4085 * failed, but you have no way of knowing which.
4087 function delete_course($courseorid, $showfeedback = true) {
4090 if (is_object($courseorid)) {
4091 $courseid = $courseorid->id;
4092 $course = $courseorid;
4094 $courseid = $courseorid;
4095 if (!$course = $DB->get_record('course', array('id'=>$courseid))) {
4099 $context = get_context_instance(CONTEXT_COURSE, $courseid);
4101 // frontpage course can not be deleted!!
4102 if ($courseid == SITEID) {
4106 // make the course completely empty
4107 remove_course_contents($courseid, $showfeedback);
4109 // delete the course and related context instance
4110 delete_context(CONTEXT_COURSE, $courseid);
4111 $DB->delete_records("course", array("id"=>$courseid));
4114 $course->context = $context; // you can not fetch context in the event because it was already deleted
4115 events_trigger('course_deleted', $course);
4121 * Clear a course out completely, deleting all content
4122 * but don't delete the course itself.
4123 * This function does not verify any permissions.
4125 * Please note this function also deletes all user enrolments,
4126 * enrolment instances and role assignments.
4128 * @param int $courseid The id of the course that is being deleted
4129 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4130 * @return bool true if all the removals succeeded. false if there were any failures. If this
4131 * method returns false, some of the removals will probably have succeeded, and others
4132 * failed, but you have no way of knowing which.
4134 function remove_course_contents($courseid, $showfeedback = true) {
4135 global $CFG, $DB, $OUTPUT;
4136 require_once($CFG->libdir.'/questionlib.php');
4137 require_once($CFG->libdir.'/gradelib.php');
4138 require_once($CFG->dirroot.'/group/lib.php');
4139 require_once($CFG->dirroot.'/tag/coursetagslib.php');
4141 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
4142 $context = get_context_instance(CONTEXT_COURSE, $courseid, MUST_EXIST);
4144 $strdeleted = get_string('deleted');
4146 // Delete course completion information,
4147 // this has to be done before grades and enrols
4148 $cc = new completion_info($course);
4149 $cc->clear_criteria();
4151 // remove roles and enrolments
4152 role_unassign_all(array('contextid'=>$context->id), true);
4153 enrol_course_delete($course);
4155 // Clean up course formats (iterate through all formats in the even the course format was ever changed)
4156 $formats = get_plugin_list('format');
4157 foreach ($formats as $format=>$formatdir) {
4158 $formatdelete = 'format_'.$format.'_delete_course';
4159 $formatlib = "$formatdir/lib.php";
4160 if (file_exists($formatlib)) {
4161 include_once($formatlib);
4162 if (function_exists($formatdelete)) {
4163 if ($showfeedback) {
4164 echo $OUTPUT->notification($strdeleted.' '.$format);
4166 $formatdelete($course->id);
4171 // Remove all data from gradebook - this needs to be done before course modules
4172 // because while deleting this information, the system may need to reference
4173 // the course modules that own the grades.
4174 remove_course_grades($courseid, $showfeedback);
4175 remove_grade_letters($context, $showfeedback);
4177 // Remove all data from availability and completion tables that is associated
4178 // with course-modules belonging to this course. Note this is done even if the
4179 // features are not enabled now, in case they were enabled previously
4180 $DB->delete_records_select('course_modules_completion',
4181 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4183 $DB->delete_records_select('course_modules_availability',
4184 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4187 // Delete course blocks - they may depend on modules so delete them first
4188 blocks_delete_all_for_context($context->id);
4190 // Delete every instance of every module
4191 if ($allmods = $DB->get_records('modules') ) {
4192 foreach ($allmods as $mod) {
4193 $modname = $mod->name;
4194 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
4195 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
4196 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
4198 if (file_exists($modfile)) {
4199 include_once($modfile);
4200 if (function_exists($moddelete)) {
4201 if ($instances = $DB->get_records($modname, array('course'=>$course->id))) {
4202 foreach ($instances as $instance) {
4203 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
4204 /// Delete activity context questions and question categories
4205 question_delete_activity($cm, $showfeedback);
4207 if ($moddelete($instance->id)) {
4211 echo $OUTPUT->notification('Could not delete '. $modname .' instance '. $instance->id .' ('. format_string($instance->name) .')');
4214 // delete cm and its context in correct order
4215 delete_context(CONTEXT_MODULE, $cm->id); // some callbacks may try to fetch context, better delete first
4216 $DB->delete_records('course_modules', array('id'=>$cm->id));
4221 //note: we should probably delete these anyway
4222 echo $OUTPUT->notification('Function '.$moddelete.'() doesn\'t exist!');
4225 if (function_exists($moddeletecourse)) {
4226 $moddeletecourse($course, $showfeedback);
4229 if ($showfeedback) {
4230 echo $OUTPUT->notification($strdeleted .' '. $count .' x '. $modname);
4235 // Delete any groups, removing members and grouping/course links first.
4236 groups_delete_groupings($course->id, $showfeedback);
4237 groups_delete_groups($course->id, $showfeedback);
4239 // Delete questions and question categories
4240 question_delete_course($course, $showfeedback);
4242 // Delete course tags
4243 coursetag_delete_course_tags($course->id, $showfeedback);
4245 // Delete legacy files (just in case some files are still left there after conversion to new file api)
4246 fulldelete($CFG->dataroot.'/'.$course->id);
4248 // cleanup course record - remove links to delted stuff
4249 $oldcourse = new stdClass();
4250 $oldcourse->id = $course->id;
4251 $oldcourse->summary = '';
4252 $oldcourse->modinfo = NULL;
4253 $oldcourse->legacyfiles = 0;
4254 $oldcourse->defaultgroupingid = 0;
4255 $oldcourse->enablecompletion = 0;
4256 $DB->update_record('course', $oldcourse);
4258 // Delete all related records in other tables that may have a courseid
4259 // This array stores the tables that need to be cleared, as
4260 // table_name => column_name that contains the course id.
4261 $tablestoclear = array(
4262 'event' => 'courseid', // Delete events
4263 'log' => 'course', // Delete logs
4264 'course_sections' => 'course', // Delete any course stuff
4265 'course_modules' => 'course',
4266 'course_display' => 'course',
4267 'backup_courses' => 'courseid', // Delete scheduled backup stuff
4268 'user_lastaccess' => 'courseid',
4269 'backup_log' => 'courseid'
4271 foreach ($tablestoclear as $table => $col) {
4272 $DB->delete_records($table, array($col=>$course->id));
4275 // Delete all remaining stuff linked to context,
4276 // such as remaining roles, files, comments, etc.
4277 // Keep the context record for now.
4278 delete_context(CONTEXT_COURSE, $course->id, false);
4281 $course->context = $context; // you can not access context in cron event later after course is deleted
4282 events_trigger('course_content_removed', $course);
4288 * Change dates in module - used from course reset.
4292 * @param string $modname forum, assignment, etc
4293 * @param array $fields array of date fields from mod table
4294 * @param int $timeshift time difference
4295 * @param int $courseid
4296 * @return bool success
4298 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid) {
4300 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
4303 foreach ($fields as $field) {
4304 $updatesql = "UPDATE {".$modname."}
4305 SET $field = $field + ?
4306 WHERE course=? AND $field<>0 AND $field<>0";
4307 $return = $DB->execute($updatesql, array($timeshift, $courseid)) && $return;
4310 $refreshfunction = $modname.'_refresh_events';
4311 if (function_exists($refreshfunction)) {
4312 $refreshfunction($courseid);
4319 * This function will empty a course of user data.
4320 * It will retain the activities and the structure of the course.
4322 * @param object $data an object containing all the settings including courseid (without magic quotes)
4323 * @return array status array of array component, item, error
4325 function reset_course_userdata($data) {
4326 global $CFG, $USER, $DB;
4327 require_once($CFG->libdir.'/gradelib.php');
4328 require_once($CFG->dirroot.'/group/lib.php');
4330 $data->courseid = $data->id;
4331 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
4333 // calculate the time shift of dates
4334 if (!empty($data->reset_start_date)) {
4335 // time part of course startdate should be zero
4336 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
4338 $data->timeshift = 0;
4341 // result array: component, item, error
4344 // start the resetting
4345 $componentstr = get_string('general');
4347 // move the course start time
4348 if (!empty($data->reset_start_date) and $data->timeshift) {
4349 // change course start data
4350 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id'=>$data->courseid));
4351 // update all course and group events - do not move activity events
4352 $updatesql = "UPDATE {event}
4353 SET timestart = timestart + ?
4354 WHERE courseid=? AND instance=0";
4355 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
4357 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
4360 if (!empty($data->reset_logs)) {
4361 $DB->delete_records('log', array('course'=>$data->courseid));
4362 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletelogs'), 'error'=>false);