2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
35 /// Date and time constants ///
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 /// Parameter constants - every call to optional_param(), required_param() ///
72 /// or clean_param() should have a specified type of parameter. //////////////
77 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
79 define('PARAM_ALPHA', 'alpha');
82 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
83 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
85 define('PARAM_ALPHAEXT', 'alphaext');
88 * PARAM_ALPHANUM - expected numbers and letters only.
90 define('PARAM_ALPHANUM', 'alphanum');
93 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
95 define('PARAM_ALPHANUMEXT', 'alphanumext');
98 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
100 define('PARAM_AUTH', 'auth');
103 * PARAM_BASE64 - Base 64 encoded format
105 define('PARAM_BASE64', 'base64');
108 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
110 define('PARAM_BOOL', 'bool');
113 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
114 * checked against the list of capabilities in the database.
116 define('PARAM_CAPABILITY', 'capability');
119 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
120 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
121 * the input (required/optional_param or formslib) and then sanitse the HTML
122 * using format_text on output. This is for the rare cases when you want to
123 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
125 define('PARAM_CLEANHTML', 'cleanhtml');
128 * PARAM_EMAIL - an email address following the RFC
130 define('PARAM_EMAIL', 'email');
133 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
135 define('PARAM_FILE', 'file');
138 * PARAM_FLOAT - a real/floating point number.
140 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
141 * It does not work for languages that use , as a decimal separator.
142 * Instead, do something like
143 * $rawvalue = required_param('name', PARAM_RAW);
144 * // ... other code including require_login, which sets current lang ...
145 * $realvalue = unformat_float($rawvalue);
146 * // ... then use $realvalue
148 define('PARAM_FLOAT', 'float');
151 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
153 define('PARAM_HOST', 'host');
156 * PARAM_INT - integers only, use when expecting only numbers.
158 define('PARAM_INT', 'int');
161 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
163 define('PARAM_LANG', 'lang');
166 * 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!)
168 define('PARAM_LOCALURL', 'localurl');
171 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
173 define('PARAM_NOTAGS', 'notags');
176 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
177 * note: the leading slash is not removed, window drive letter is not allowed
179 define('PARAM_PATH', 'path');
182 * PARAM_PEM - Privacy Enhanced Mail format
184 define('PARAM_PEM', 'pem');
187 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
189 define('PARAM_PERMISSION', 'permission');
192 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
194 define('PARAM_RAW', 'raw');
197 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
199 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
202 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
204 define('PARAM_SAFEDIR', 'safedir');
207 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
209 define('PARAM_SAFEPATH', 'safepath');
212 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
214 define('PARAM_SEQUENCE', 'sequence');
217 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
219 define('PARAM_TAG', 'tag');
222 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
224 define('PARAM_TAGLIST', 'taglist');
227 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
229 define('PARAM_TEXT', 'text');
232 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
234 define('PARAM_THEME', 'theme');
237 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * 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!!
244 define('PARAM_USERNAME', 'username');
247 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
249 define('PARAM_STRINGID', 'stringid');
251 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
253 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
254 * It was one of the first types, that is why it is abused so much ;-)
255 * @deprecated since 2.0
257 define('PARAM_CLEAN', 'clean');
260 * PARAM_INTEGER - deprecated alias for PARAM_INT
261 * @deprecated since 2.0
263 define('PARAM_INTEGER', 'int');
266 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
267 * @deprecated since 2.0
269 define('PARAM_NUMBER', 'float');
272 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
273 * NOTE: originally alias for PARAM_APLHA
274 * @deprecated since 2.0
276 define('PARAM_ACTION', 'alphanumext');
279 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
280 * NOTE: originally alias for PARAM_APLHA
281 * @deprecated since 2.0
283 define('PARAM_FORMAT', 'alphanumext');
286 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
287 * @deprecated since 2.0
289 define('PARAM_MULTILANG', 'text');
292 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
293 * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
294 * America/Port-au-Prince)
296 define('PARAM_TIMEZONE', 'timezone');
299 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
301 define('PARAM_CLEANFILE', 'file');
304 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
305 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
306 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
307 * NOTE: numbers and underscores are strongly discouraged in plugin names!
309 define('PARAM_COMPONENT', 'component');
312 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
313 * It is usually used together with context id and component.
314 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
316 define('PARAM_AREA', 'area');
319 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
320 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
321 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
323 define('PARAM_PLUGIN', 'plugin');
329 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
331 define('VALUE_REQUIRED', 1);
334 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
336 define('VALUE_OPTIONAL', 2);
339 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
341 define('VALUE_DEFAULT', 0);
344 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
346 define('NULL_NOT_ALLOWED', false);
349 * NULL_ALLOWED - the parameter can be set to null in the database
351 define('NULL_ALLOWED', true);
355 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
357 define('PAGE_COURSE_VIEW', 'course-view');
359 /** Get remote addr constant */
360 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
364 /// Blog access level constant declaration ///
365 define ('BLOG_USER_LEVEL', 1);
366 define ('BLOG_GROUP_LEVEL', 2);
367 define ('BLOG_COURSE_LEVEL', 3);
368 define ('BLOG_SITE_LEVEL', 4);
369 define ('BLOG_GLOBAL_LEVEL', 5);
374 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
375 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
376 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
378 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
380 define('TAG_MAX_LENGTH', 50);
382 /// Password policy constants ///
383 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
384 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
385 define ('PASSWORD_DIGITS', '0123456789');
386 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
388 /// Feature constants ///
389 // Used for plugin_supports() to report features that are, or are not, supported by a module.
391 /** True if module can provide a grade */
392 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
393 /** True if module supports outcomes */
394 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
395 /** True if module supports advanced grading methods */
396 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
397 /** True if module controls the grade visibility over the gradebook */
398 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
399 /** True if module supports plagiarism plugins */
400 define('FEATURE_PLAGIARISM', 'plagiarism');
402 /** True if module has code to track whether somebody viewed it */
403 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
404 /** True if module has custom completion rules */
405 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
407 /** True if module has no 'view' page (like label) */
408 define('FEATURE_NO_VIEW_LINK', 'viewlink');
409 /** True if module supports outcomes */
410 define('FEATURE_IDNUMBER', 'idnumber');
411 /** True if module supports groups */
412 define('FEATURE_GROUPS', 'groups');
413 /** True if module supports groupings */
414 define('FEATURE_GROUPINGS', 'groupings');
415 /** True if module supports groupmembersonly */
416 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
418 /** Type of module */
419 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
420 /** True if module supports intro editor */
421 define('FEATURE_MOD_INTRO', 'mod_intro');
422 /** True if module has default completion */
423 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
425 define('FEATURE_COMMENT', 'comment');
427 define('FEATURE_RATE', 'rate');
428 /** True if module supports backup/restore of moodle2 format */
429 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
431 /** True if module can show description on course main page */
432 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
434 /** Unspecified module archetype */
435 define('MOD_ARCHETYPE_OTHER', 0);
436 /** Resource-like type module */
437 define('MOD_ARCHETYPE_RESOURCE', 1);
438 /** Assignment module archetype */
439 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
440 /** System (not user-addable) module archetype */
441 define('MOD_ARCHETYPE_SYSTEM', 3);
444 * Security token used for allowing access
445 * from external application such as web services.
446 * Scripts do not use any session, performance is relatively
447 * low because we need to load access info in each request.
448 * Scripts are executed in parallel.
450 define('EXTERNAL_TOKEN_PERMANENT', 0);
453 * Security token used for allowing access
454 * of embedded applications, the code is executed in the
455 * active user session. Token is invalidated after user logs out.
456 * Scripts are executed serially - normal session locking is used.
458 define('EXTERNAL_TOKEN_EMBEDDED', 1);
461 * The home page should be the site home
463 define('HOMEPAGE_SITE', 0);
465 * The home page should be the users my page
467 define('HOMEPAGE_MY', 1);
469 * The home page can be chosen by the user
471 define('HOMEPAGE_USER', 2);
474 * Hub directory url (should be moodle.org)
476 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
480 * Moodle.org url (should be moodle.org)
482 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
485 * Moodle mobile app service name
487 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
490 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
492 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
495 * Course display settings
497 define('COURSE_DISPLAY_SINGLEPAGE', 0); // display all sections on one page
498 define('COURSE_DISPLAY_MULTIPAGE', 1); // split pages into a page per section
501 * Authentication constants.
503 define('AUTH_PASSWORD_NOT_CACHED', 'not cached'); // String used in password field when password is not stored.
505 /// PARAMETER HANDLING ////////////////////////////////////////////////////
508 * Returns a particular value for the named variable, taken from
509 * POST or GET. If the parameter doesn't exist then an error is
510 * thrown because we require this variable.
512 * This function should be used to initialise all required values
513 * in a script that are based on parameters. Usually it will be
515 * $id = required_param('id', PARAM_INT);
517 * Please note the $type parameter is now required and the value can not be array.
519 * @param string $parname the name of the page parameter we want
520 * @param string $type expected type of parameter
523 function required_param($parname, $type) {
524 if (func_num_args() != 2 or empty($parname) or empty($type)) {
525 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
527 if (isset($_POST[$parname])) { // POST has precedence
528 $param = $_POST[$parname];
529 } else if (isset($_GET[$parname])) {
530 $param = $_GET[$parname];
532 print_error('missingparam', '', '', $parname);
535 if (is_array($param)) {
536 debugging('Invalid array parameter detected in required_param(): '.$parname);
537 // TODO: switch to fatal error in Moodle 2.3
538 //print_error('missingparam', '', '', $parname);
539 return required_param_array($parname, $type);
542 return clean_param($param, $type);
546 * Returns a particular array value for the named variable, taken from
547 * POST or GET. If the parameter doesn't exist then an error is
548 * thrown because we require this variable.
550 * This function should be used to initialise all required values
551 * in a script that are based on parameters. Usually it will be
553 * $ids = required_param_array('ids', PARAM_INT);
555 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
557 * @param string $parname the name of the page parameter we want
558 * @param string $type expected type of parameter
561 function required_param_array($parname, $type) {
562 if (func_num_args() != 2 or empty($parname) or empty($type)) {
563 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
565 if (isset($_POST[$parname])) { // POST has precedence
566 $param = $_POST[$parname];
567 } else if (isset($_GET[$parname])) {
568 $param = $_GET[$parname];
570 print_error('missingparam', '', '', $parname);
572 if (!is_array($param)) {
573 print_error('missingparam', '', '', $parname);
577 foreach($param as $key=>$value) {
578 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
579 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
582 $result[$key] = clean_param($value, $type);
589 * Returns a particular value for the named variable, taken from
590 * POST or GET, otherwise returning a given default.
592 * This function should be used to initialise all optional values
593 * in a script that are based on parameters. Usually it will be
595 * $name = optional_param('name', 'Fred', PARAM_TEXT);
597 * Please note the $type parameter is now required and the value can not be array.
599 * @param string $parname the name of the page parameter we want
600 * @param mixed $default the default value to return if nothing is found
601 * @param string $type expected type of parameter
604 function optional_param($parname, $default, $type) {
605 if (func_num_args() != 3 or empty($parname) or empty($type)) {
606 throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
608 if (!isset($default)) {
612 if (isset($_POST[$parname])) { // POST has precedence
613 $param = $_POST[$parname];
614 } else if (isset($_GET[$parname])) {
615 $param = $_GET[$parname];
620 if (is_array($param)) {
621 debugging('Invalid array parameter detected in required_param(): '.$parname);
622 // TODO: switch to $default in Moodle 2.3
624 return optional_param_array($parname, $default, $type);
627 return clean_param($param, $type);
631 * Returns a particular array value for the named variable, taken from
632 * POST or GET, otherwise returning a given default.
634 * This function should be used to initialise all optional values
635 * in a script that are based on parameters. Usually it will be
637 * $ids = optional_param('id', array(), PARAM_INT);
639 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
641 * @param string $parname the name of the page parameter we want
642 * @param mixed $default the default value to return if nothing is found
643 * @param string $type expected type of parameter
646 function optional_param_array($parname, $default, $type) {
647 if (func_num_args() != 3 or empty($parname) or empty($type)) {
648 throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
651 if (isset($_POST[$parname])) { // POST has precedence
652 $param = $_POST[$parname];
653 } else if (isset($_GET[$parname])) {
654 $param = $_GET[$parname];
658 if (!is_array($param)) {
659 debugging('optional_param_array() expects array parameters only: '.$parname);
664 foreach($param as $key=>$value) {
665 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
666 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
669 $result[$key] = clean_param($value, $type);
676 * Strict validation of parameter values, the values are only converted
677 * to requested PHP type. Internally it is using clean_param, the values
678 * before and after cleaning must be equal - otherwise
679 * an invalid_parameter_exception is thrown.
680 * Objects and classes are not accepted.
682 * @param mixed $param
683 * @param string $type PARAM_ constant
684 * @param bool $allownull are nulls valid value?
685 * @param string $debuginfo optional debug information
686 * @return mixed the $param value converted to PHP type
687 * @throws invalid_parameter_exception if $param is not of given type
689 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
690 if (is_null($param)) {
691 if ($allownull == NULL_ALLOWED) {
694 throw new invalid_parameter_exception($debuginfo);
697 if (is_array($param) or is_object($param)) {
698 throw new invalid_parameter_exception($debuginfo);
701 $cleaned = clean_param($param, $type);
703 if ($type == PARAM_FLOAT) {
704 // Do not detect precision loss here.
705 if (is_float($param) or is_int($param)) {
707 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
708 throw new invalid_parameter_exception($debuginfo);
710 } else if ((string)$param !== (string)$cleaned) {
711 // conversion to string is usually lossless
712 throw new invalid_parameter_exception($debuginfo);
719 * Makes sure array contains only the allowed types,
720 * this function does not validate array key names!
722 * $options = clean_param($options, PARAM_INT);
725 * @param array $param the variable array we are cleaning
726 * @param string $type expected format of param after cleaning.
727 * @param bool $recursive clean recursive arrays
730 function clean_param_array(array $param = null, $type, $recursive = false) {
731 $param = (array)$param; // convert null to empty array
732 foreach ($param as $key => $value) {
733 if (is_array($value)) {
735 $param[$key] = clean_param_array($value, $type, true);
737 throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
740 $param[$key] = clean_param($value, $type);
747 * Used by {@link optional_param()} and {@link required_param()} to
748 * clean the variables and/or cast to specific types, based on
751 * $course->format = clean_param($course->format, PARAM_ALPHA);
752 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
755 * @param mixed $param the variable we are cleaning
756 * @param string $type expected format of param after cleaning.
759 function clean_param($param, $type) {
763 if (is_array($param)) {
764 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
765 } else if (is_object($param)) {
766 if (method_exists($param, '__toString')) {
767 $param = $param->__toString();
769 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
774 case PARAM_RAW: // no cleaning at all
775 $param = fix_utf8($param);
778 case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
779 $param = fix_utf8($param);
782 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
783 // this is deprecated!, please use more specific type instead
784 if (is_numeric($param)) {
787 $param = fix_utf8($param);
788 return clean_text($param); // Sweep for scripts, etc
790 case PARAM_CLEANHTML: // clean html fragment
791 $param = fix_utf8($param);
792 $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
796 return (int)$param; // Convert to integer
799 return (float)$param; // Convert to float
801 case PARAM_ALPHA: // Remove everything not a-z
802 return preg_replace('/[^a-zA-Z]/i', '', $param);
804 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
805 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
807 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
808 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
810 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
811 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
813 case PARAM_SEQUENCE: // Remove everything not 0-9,
814 return preg_replace('/[^0-9,]/i', '', $param);
816 case PARAM_BOOL: // Convert to 1 or 0
817 $tempstr = strtolower($param);
818 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
820 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
823 $param = empty($param) ? 0 : 1;
827 case PARAM_NOTAGS: // Strip all tags
828 $param = fix_utf8($param);
829 return strip_tags($param);
831 case PARAM_TEXT: // leave only tags needed for multilang
832 $param = fix_utf8($param);
833 // if the multilang syntax is not correct we strip all tags
834 // because it would break xhtml strict which is required for accessibility standards
835 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
837 if (strpos($param, '</lang>') !== false) {
838 // old and future mutilang syntax
839 $param = strip_tags($param, '<lang>');
840 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
844 foreach ($matches[0] as $match) {
845 if ($match === '</lang>') {
853 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
864 } else if (strpos($param, '</span>') !== false) {
865 // current problematic multilang syntax
866 $param = strip_tags($param, '<span>');
867 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
871 foreach ($matches[0] as $match) {
872 if ($match === '</span>') {
880 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
892 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
893 return strip_tags($param);
895 case PARAM_COMPONENT:
896 // we do not want any guessing here, either the name is correct or not
897 // please note only normalised component names are accepted
898 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
901 if (strpos($param, '__') !== false) {
904 if (strpos($param, 'mod_') === 0) {
905 // module names must not contain underscores because we need to differentiate them from invalid plugin types
906 if (substr_count($param, '_') != 1) {
914 // we do not want any guessing here, either the name is correct or not
915 if (!is_valid_plugin_name($param)) {
920 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
921 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
923 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
924 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
926 case PARAM_FILE: // Strip all suspicious characters from filename
927 $param = fix_utf8($param);
928 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
929 if ($param === '.' || $param === '..') {
934 case PARAM_PATH: // Strip all suspicious characters from file path
935 $param = fix_utf8($param);
936 $param = str_replace('\\', '/', $param);
938 // Explode the path and clean each element using the PARAM_FILE rules.
939 $breadcrumb = explode('/', $param);
940 foreach ($breadcrumb as $key => $crumb) {
941 if ($crumb === '.' && $key === 0) {
942 // Special condition to allow for relative current path such as ./currentdirfile.txt.
944 $crumb = clean_param($crumb, PARAM_FILE);
946 $breadcrumb[$key] = $crumb;
948 $param = implode('/', $breadcrumb);
950 // Remove multiple current path (./././) and multiple slashes (///).
951 $param = preg_replace('~//+~', '/', $param);
952 $param = preg_replace('~/(\./)+~', '/', $param);
955 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
956 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
957 // match ipv4 dotted quad
958 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
959 // confirm values are ok
963 || $match[4] > 255 ) {
964 // hmmm, what kind of dotted quad is this?
967 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
968 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
969 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
971 // all is ok - $param is respected
978 case PARAM_URL: // allow safe ftp, http, mailto urls
979 $param = fix_utf8($param);
980 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
981 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
982 // all is ok, param is respected
984 $param =''; // not really ok
988 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
989 $param = clean_param($param, PARAM_URL);
990 if (!empty($param)) {
991 if (preg_match(':^/:', $param)) {
992 // root-relative, ok!
993 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
994 // absolute, and matches our wwwroot
996 // relative - let's make sure there are no tricks
997 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1007 $param = trim($param);
1008 // PEM formatted strings may contain letters/numbers and the symbols
1012 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
1013 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1014 list($wholething, $body) = $matches;
1015 unset($wholething, $matches);
1016 $b64 = clean_param($body, PARAM_BASE64);
1018 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1026 if (!empty($param)) {
1027 // PEM formatted strings may contain letters/numbers and the symbols
1031 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1034 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1035 // Each line of base64 encoded data must be 64 characters in
1036 // length, except for the last line which may be less than (or
1037 // equal to) 64 characters long.
1038 for ($i=0, $j=count($lines); $i < $j; $i++) {
1040 if (64 < strlen($lines[$i])) {
1046 if (64 != strlen($lines[$i])) {
1050 return implode("\n",$lines);
1056 $param = fix_utf8($param);
1057 // Please note it is not safe to use the tag name directly anywhere,
1058 // it must be processed with s(), urlencode() before embedding anywhere.
1059 // remove some nasties
1060 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1061 //convert many whitespace chars into one
1062 $param = preg_replace('/\s+/', ' ', $param);
1063 $param = textlib::substr(trim($param), 0, TAG_MAX_LENGTH);
1067 $param = fix_utf8($param);
1068 $tags = explode(',', $param);
1070 foreach ($tags as $tag) {
1071 $res = clean_param($tag, PARAM_TAG);
1077 return implode(',', $result);
1082 case PARAM_CAPABILITY:
1083 if (get_capability_info($param)) {
1089 case PARAM_PERMISSION:
1090 $param = (int)$param;
1091 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1098 $param = clean_param($param, PARAM_PLUGIN);
1099 if (empty($param)) {
1101 } else if (exists_auth_plugin($param)) {
1108 $param = clean_param($param, PARAM_SAFEDIR);
1109 if (get_string_manager()->translation_exists($param)) {
1112 return ''; // Specified language is not installed or param malformed
1116 $param = clean_param($param, PARAM_PLUGIN);
1117 if (empty($param)) {
1119 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1121 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1124 return ''; // Specified theme is not installed
1127 case PARAM_USERNAME:
1128 $param = fix_utf8($param);
1129 $param = str_replace(" " , "", $param);
1130 $param = textlib::strtolower($param); // Convert uppercase to lowercase MDL-16919
1131 if (empty($CFG->extendedusernamechars)) {
1132 // regular expression, eliminate all chars EXCEPT:
1133 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1134 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1139 $param = fix_utf8($param);
1140 if (validate_email($param)) {
1146 case PARAM_STRINGID:
1147 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1153 case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1154 $param = fix_utf8($param);
1155 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1156 if (preg_match($timezonepattern, $param)) {
1162 default: // throw error, switched parameters in optional_param or another serious problem
1163 print_error("unknownparamtype", '', '', $type);
1168 * Makes sure the data is using valid utf8, invalid characters are discarded.
1170 * Note: this function is not intended for full objects with methods and private properties.
1172 * @param mixed $value
1173 * @return mixed with proper utf-8 encoding
1175 function fix_utf8($value) {
1176 if (is_null($value) or $value === '') {
1179 } else if (is_string($value)) {
1180 if ((string)(int)$value === $value) {
1185 // Lower error reporting because glibc throws bogus notices.
1186 $olderror = error_reporting();
1187 if ($olderror & E_NOTICE) {
1188 error_reporting($olderror ^ E_NOTICE);
1191 // Note: this duplicates min_fix_utf8() intentionally.
1192 static $buggyiconv = null;
1193 if ($buggyiconv === null) {
1194 $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1198 if (function_exists('mb_convert_encoding')) {
1199 $subst = mb_substitute_character();
1200 mb_substitute_character('');
1201 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1202 mb_substitute_character($subst);
1205 // Warn admins on admin/index.php page.
1210 $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1213 if ($olderror & E_NOTICE) {
1214 error_reporting($olderror);
1219 } else if (is_array($value)) {
1220 foreach ($value as $k=>$v) {
1221 $value[$k] = fix_utf8($v);
1225 } else if (is_object($value)) {
1226 $value = clone($value); // do not modify original
1227 foreach ($value as $k=>$v) {
1228 $value->$k = fix_utf8($v);
1233 // this is some other type, no utf-8 here
1239 * Return true if given value is integer or string with integer value
1241 * @param mixed $value String or Int
1242 * @return bool true if number, false if not
1244 function is_number($value) {
1245 if (is_int($value)) {
1247 } else if (is_string($value)) {
1248 return ((string)(int)$value) === $value;
1255 * Returns host part from url
1256 * @param string $url full url
1257 * @return string host, null if not found
1259 function get_host_from_url($url) {
1260 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1268 * Tests whether anything was returned by text editor
1270 * This function is useful for testing whether something you got back from
1271 * the HTML editor actually contains anything. Sometimes the HTML editor
1272 * appear to be empty, but actually you get back a <br> tag or something.
1274 * @param string $string a string containing HTML.
1275 * @return boolean does the string contain any actual content - that is text,
1276 * images, objects, etc.
1278 function html_is_blank($string) {
1279 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1283 * Set a key in global configuration
1285 * Set a key/value pair in both this session's {@link $CFG} global variable
1286 * and in the 'config' database table for future sessions.
1288 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1289 * In that case it doesn't affect $CFG.
1291 * A NULL value will delete the entry.
1295 * @param string $name the key to set
1296 * @param string $value the value to set (without magic quotes)
1297 * @param string $plugin (optional) the plugin scope, default NULL
1298 * @return bool true or exception
1300 function set_config($name, $value, $plugin=NULL) {
1303 if (empty($plugin)) {
1304 if (!array_key_exists($name, $CFG->config_php_settings)) {
1305 // So it's defined for this invocation at least
1306 if (is_null($value)) {
1309 $CFG->$name = (string)$value; // settings from db are always strings
1313 if ($DB->get_field('config', 'name', array('name'=>$name))) {
1314 if ($value === null) {
1315 $DB->delete_records('config', array('name'=>$name));
1317 $DB->set_field('config', 'value', $value, array('name'=>$name));
1320 if ($value !== null) {
1321 $config = new stdClass();
1322 $config->name = $name;
1323 $config->value = $value;
1324 $DB->insert_record('config', $config, false);
1327 if ($name === 'siteidentifier') {
1328 cache_helper::update_site_identifier($value);
1330 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1331 } else { // plugin scope
1332 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1333 if ($value===null) {
1334 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1336 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1339 if ($value !== null) {
1340 $config = new stdClass();
1341 $config->plugin = $plugin;
1342 $config->name = $name;
1343 $config->value = $value;
1344 $DB->insert_record('config_plugins', $config, false);
1347 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1354 * Get configuration values from the global config table
1355 * or the config_plugins table.
1357 * If called with one parameter, it will load all the config
1358 * variables for one plugin, and return them as an object.
1360 * If called with 2 parameters it will return a string single
1361 * value or false if the value is not found.
1363 * @static $siteidentifier The site identifier is not cached. We use this static cache so
1364 * that we need only fetch it once per request.
1365 * @param string $plugin full component name
1366 * @param string $name default NULL
1367 * @return mixed hash-like object or single value, return false no config found
1369 function get_config($plugin, $name = NULL) {
1372 static $siteidentifier = null;
1374 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1375 $forced =& $CFG->config_php_settings;
1379 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1380 $forced =& $CFG->forced_plugin_settings[$plugin];
1387 if ($siteidentifier === null) {
1389 // This may fail during installation.
1390 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1391 // install the database.
1392 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1393 } catch (dml_exception $ex) {
1394 // Set siteidentifier to false. We don't want to trip this continually.
1395 $siteidentifier = false;
1400 if (!empty($name)) {
1401 if (array_key_exists($name, $forced)) {
1402 return (string)$forced[$name];
1403 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1404 return $siteidentifier;
1408 $cache = cache::make('core', 'config');
1409 $result = $cache->get($plugin);
1410 if ($result === false) {
1411 // the user is after a recordset
1412 $result = new stdClass;
1414 $result = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1416 // this part is not really used any more, but anyway...
1417 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1419 $cache->set($plugin, $result);
1422 if (!empty($name)) {
1423 if (array_key_exists($name, $result)) {
1424 return $result[$name];
1429 if ($plugin === 'core') {
1430 $result['siteidentifier'] = $siteidentifier;
1433 foreach ($forced as $key => $value) {
1434 if (is_null($value) or is_array($value) or is_object($value)) {
1435 // we do not want any extra mess here, just real settings that could be saved in db
1436 unset($result[$key]);
1438 //convert to string as if it went through the DB
1439 $result[$key] = (string)$value;
1443 return (object)$result;
1447 * Removes a key from global configuration
1449 * @param string $name the key to set
1450 * @param string $plugin (optional) the plugin scope
1452 * @return boolean whether the operation succeeded.
1454 function unset_config($name, $plugin=NULL) {
1457 if (empty($plugin)) {
1459 $DB->delete_records('config', array('name'=>$name));
1460 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1462 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1463 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1470 * Remove all the config variables for a given plugin.
1471 * NOTE: this function is called from lib/db/upgrade.php
1473 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1474 * @return boolean whether the operation succeeded.
1476 function unset_all_config_for_plugin($plugin) {
1478 // Delete from the obvious config_plugins first
1479 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1480 // Next delete any suspect settings from config
1481 $like = $DB->sql_like('name', '?', true, true, false, '|');
1482 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1483 $DB->delete_records_select('config', $like, $params);
1484 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1485 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1491 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1493 * All users are verified if they still have the necessary capability.
1495 * @param string $value the value of the config setting.
1496 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1497 * @param bool $include admins, include administrators
1498 * @return array of user objects.
1500 function get_users_from_config($value, $capability, $includeadmins = true) {
1503 if (empty($value) or $value === '$@NONE@$') {
1507 // we have to make sure that users still have the necessary capability,
1508 // it should be faster to fetch them all first and then test if they are present
1509 // instead of validating them one-by-one
1510 $users = get_users_by_capability(context_system::instance(), $capability);
1511 if ($includeadmins) {
1512 $admins = get_admins();
1513 foreach ($admins as $admin) {
1514 $users[$admin->id] = $admin;
1518 if ($value === '$@ALL@$') {
1522 $result = array(); // result in correct order
1523 $allowed = explode(',', $value);
1524 foreach ($allowed as $uid) {
1525 if (isset($users[$uid])) {
1526 $user = $users[$uid];
1527 $result[$user->id] = $user;
1536 * Invalidates browser caches and cached data in temp
1538 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1539 * {@see phpunit_util::reset_dataroot()}
1543 function purge_all_caches() {
1546 reset_text_filters_cache();
1547 js_reset_all_caches();
1548 theme_reset_all_caches();
1549 get_string_manager()->reset_caches();
1550 textlib::reset_caches();
1552 cache_helper::purge_all();
1554 // Clear course cache for all courses.
1555 rebuild_course_cache(0, true);
1557 // purge all other caches: rss, simplepie, etc.
1558 remove_dir($CFG->cachedir.'', true);
1560 // make sure cache dir is writable, throws exception if not
1561 make_cache_directory('');
1563 // hack: this script may get called after the purifier was initialised,
1564 // but we do not want to verify repeatedly this exists in each call
1565 make_cache_directory('htmlpurifier');
1569 * Get volatile flags
1571 * @param string $type
1572 * @param int $changedsince default null
1573 * @return records array
1575 function get_cache_flags($type, $changedsince=NULL) {
1578 $params = array('type'=>$type, 'expiry'=>time());
1579 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1580 if ($changedsince !== NULL) {
1581 $params['changedsince'] = $changedsince;
1582 $sqlwhere .= " AND timemodified > :changedsince";
1586 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1587 foreach ($flags as $flag) {
1588 $cf[$flag->name] = $flag->value;
1595 * Get volatile flags
1597 * @param string $type
1598 * @param string $name
1599 * @param int $changedsince default null
1600 * @return records array
1602 function get_cache_flag($type, $name, $changedsince=NULL) {
1605 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1607 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1608 if ($changedsince !== NULL) {
1609 $params['changedsince'] = $changedsince;
1610 $sqlwhere .= " AND timemodified > :changedsince";
1613 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1617 * Set a volatile flag
1619 * @param string $type the "type" namespace for the key
1620 * @param string $name the key to set
1621 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1622 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1623 * @return bool Always returns true
1625 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1628 $timemodified = time();
1629 if ($expiry===NULL || $expiry < $timemodified) {
1630 $expiry = $timemodified + 24 * 60 * 60;
1632 $expiry = (int)$expiry;
1635 if ($value === NULL) {
1636 unset_cache_flag($type,$name);
1640 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1641 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1642 return true; //no need to update
1645 $f->expiry = $expiry;
1646 $f->timemodified = $timemodified;
1647 $DB->update_record('cache_flags', $f);
1649 $f = new stdClass();
1650 $f->flagtype = $type;
1653 $f->expiry = $expiry;
1654 $f->timemodified = $timemodified;
1655 $DB->insert_record('cache_flags', $f);
1661 * Removes a single volatile flag
1664 * @param string $type the "type" namespace for the key
1665 * @param string $name the key to set
1668 function unset_cache_flag($type, $name) {
1670 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1675 * Garbage-collect volatile flags
1677 * @return bool Always returns true
1679 function gc_cache_flags() {
1681 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1685 // USER PREFERENCE API
1688 * Refresh user preference cache. This is used most often for $USER
1689 * object that is stored in session, but it also helps with performance in cron script.
1691 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1694 * @category preference
1696 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1697 * @param int $cachelifetime Cache life time on the current page (in seconds)
1698 * @throws coding_exception
1701 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1703 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1705 if (!isset($user->id)) {
1706 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1709 if (empty($user->id) or isguestuser($user->id)) {
1710 // No permanent storage for not-logged-in users and guest
1711 if (!isset($user->preference)) {
1712 $user->preference = array();
1719 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1720 // Already loaded at least once on this page. Are we up to date?
1721 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1722 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1725 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1726 // no change since the lastcheck on this page
1727 $user->preference['_lastloaded'] = $timenow;
1732 // OK, so we have to reload all preferences
1733 $loadedusers[$user->id] = true;
1734 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1735 $user->preference['_lastloaded'] = $timenow;
1739 * Called from set/unset_user_preferences, so that the prefs can
1740 * be correctly reloaded in different sessions.
1742 * NOTE: internal function, do not call from other code.
1746 * @param integer $userid the user whose prefs were changed.
1748 function mark_user_preferences_changed($userid) {
1751 if (empty($userid) or isguestuser($userid)) {
1752 // no cache flags for guest and not-logged-in users
1756 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1760 * Sets a preference for the specified user.
1762 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1765 * @category preference
1767 * @param string $name The key to set as preference for the specified user
1768 * @param string $value The value to set for the $name key in the specified user's
1769 * record, null means delete current value.
1770 * @param stdClass|int|null $user A moodle user object or id, null means current user
1771 * @throws coding_exception
1772 * @return bool Always true or exception
1774 function set_user_preference($name, $value, $user = null) {
1777 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1778 throw new coding_exception('Invalid preference name in set_user_preference() call');
1781 if (is_null($value)) {
1782 // null means delete current
1783 return unset_user_preference($name, $user);
1784 } else if (is_object($value)) {
1785 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1786 } else if (is_array($value)) {
1787 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1789 $value = (string)$value;
1790 if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1791 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1794 if (is_null($user)) {
1796 } else if (isset($user->id)) {
1797 // $user is valid object
1798 } else if (is_numeric($user)) {
1799 $user = (object)array('id'=>(int)$user);
1801 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1804 check_user_preferences_loaded($user);
1806 if (empty($user->id) or isguestuser($user->id)) {
1807 // no permanent storage for not-logged-in users and guest
1808 $user->preference[$name] = $value;
1812 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1813 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1814 // preference already set to this value
1817 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1820 $preference = new stdClass();
1821 $preference->userid = $user->id;
1822 $preference->name = $name;
1823 $preference->value = $value;
1824 $DB->insert_record('user_preferences', $preference);
1827 // update value in cache
1828 $user->preference[$name] = $value;
1830 // set reload flag for other sessions
1831 mark_user_preferences_changed($user->id);
1837 * Sets a whole array of preferences for the current user
1839 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1842 * @category preference
1844 * @param array $prefarray An array of key/value pairs to be set
1845 * @param stdClass|int|null $user A moodle user object or id, null means current user
1846 * @return bool Always true or exception
1848 function set_user_preferences(array $prefarray, $user = null) {
1849 foreach ($prefarray as $name => $value) {
1850 set_user_preference($name, $value, $user);
1856 * Unsets a preference completely by deleting it from the database
1858 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1861 * @category preference
1863 * @param string $name The key to unset as preference for the specified user
1864 * @param stdClass|int|null $user A moodle user object or id, null means current user
1865 * @throws coding_exception
1866 * @return bool Always true or exception
1868 function unset_user_preference($name, $user = null) {
1871 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1872 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1875 if (is_null($user)) {
1877 } else if (isset($user->id)) {
1878 // $user is valid object
1879 } else if (is_numeric($user)) {
1880 $user = (object)array('id'=>(int)$user);
1882 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1885 check_user_preferences_loaded($user);
1887 if (empty($user->id) or isguestuser($user->id)) {
1888 // no permanent storage for not-logged-in user and guest
1889 unset($user->preference[$name]);
1894 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1896 // delete the preference from cache
1897 unset($user->preference[$name]);
1899 // set reload flag for other sessions
1900 mark_user_preferences_changed($user->id);
1906 * Used to fetch user preference(s)
1908 * If no arguments are supplied this function will return
1909 * all of the current user preferences as an array.
1911 * If a name is specified then this function
1912 * attempts to return that particular preference value. If
1913 * none is found, then the optional value $default is returned,
1916 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1919 * @category preference
1921 * @param string $name Name of the key to use in finding a preference value
1922 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1923 * @param stdClass|int|null $user A moodle user object or id, null means current user
1924 * @throws coding_exception
1925 * @return string|mixed|null A string containing the value of a single preference. An
1926 * array with all of the preferences or null
1928 function get_user_preferences($name = null, $default = null, $user = null) {
1931 if (is_null($name)) {
1933 } else if (is_numeric($name) or $name === '_lastloaded') {
1934 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1937 if (is_null($user)) {
1939 } else if (isset($user->id)) {
1940 // $user is valid object
1941 } else if (is_numeric($user)) {
1942 $user = (object)array('id'=>(int)$user);
1944 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1947 check_user_preferences_loaded($user);
1950 return $user->preference; // All values
1951 } else if (isset($user->preference[$name])) {
1952 return $user->preference[$name]; // The single string value
1954 return $default; // Default value (null if not specified)
1958 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1961 * Given date parts in user time produce a GMT timestamp.
1965 * @param int $year The year part to create timestamp of
1966 * @param int $month The month part to create timestamp of
1967 * @param int $day The day part to create timestamp of
1968 * @param int $hour The hour part to create timestamp of
1969 * @param int $minute The minute part to create timestamp of
1970 * @param int $second The second part to create timestamp of
1971 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1972 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
1973 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1974 * applied only if timezone is 99 or string.
1975 * @return int GMT timestamp
1977 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1979 //save input timezone, required for dst offset check.
1980 $passedtimezone = $timezone;
1982 $timezone = get_user_timezone_offset($timezone);
1984 if (abs($timezone) > 13) { //server time
1985 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1987 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1988 $time = usertime($time, $timezone);
1990 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1991 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1992 $time -= dst_offset_on($time, $passedtimezone);
2001 * Format a date/time (seconds) as weeks, days, hours etc as needed
2003 * Given an amount of time in seconds, returns string
2004 * formatted nicely as weeks, days, hours etc as needed
2012 * @param int $totalsecs Time in seconds
2013 * @param object $str Should be a time object
2014 * @return string A nicely formatted date/time string
2016 function format_time($totalsecs, $str=NULL) {
2018 $totalsecs = abs($totalsecs);
2020 if (!$str) { // Create the str structure the slow way
2021 $str = new stdClass();
2022 $str->day = get_string('day');
2023 $str->days = get_string('days');
2024 $str->hour = get_string('hour');
2025 $str->hours = get_string('hours');
2026 $str->min = get_string('min');
2027 $str->mins = get_string('mins');
2028 $str->sec = get_string('sec');
2029 $str->secs = get_string('secs');
2030 $str->year = get_string('year');
2031 $str->years = get_string('years');
2035 $years = floor($totalsecs/YEARSECS);
2036 $remainder = $totalsecs - ($years*YEARSECS);
2037 $days = floor($remainder/DAYSECS);
2038 $remainder = $totalsecs - ($days*DAYSECS);
2039 $hours = floor($remainder/HOURSECS);
2040 $remainder = $remainder - ($hours*HOURSECS);
2041 $mins = floor($remainder/MINSECS);
2042 $secs = $remainder - ($mins*MINSECS);
2044 $ss = ($secs == 1) ? $str->sec : $str->secs;
2045 $sm = ($mins == 1) ? $str->min : $str->mins;
2046 $sh = ($hours == 1) ? $str->hour : $str->hours;
2047 $sd = ($days == 1) ? $str->day : $str->days;
2048 $sy = ($years == 1) ? $str->year : $str->years;
2056 if ($years) $oyears = $years .' '. $sy;
2057 if ($days) $odays = $days .' '. $sd;
2058 if ($hours) $ohours = $hours .' '. $sh;
2059 if ($mins) $omins = $mins .' '. $sm;
2060 if ($secs) $osecs = $secs .' '. $ss;
2062 if ($years) return trim($oyears .' '. $odays);
2063 if ($days) return trim($odays .' '. $ohours);
2064 if ($hours) return trim($ohours .' '. $omins);
2065 if ($mins) return trim($omins .' '. $osecs);
2066 if ($secs) return $osecs;
2067 return get_string('now');
2071 * Returns a formatted string that represents a date in user time
2073 * Returns a formatted string that represents a date in user time
2074 * <b>WARNING: note that the format is for strftime(), not date().</b>
2075 * Because of a bug in most Windows time libraries, we can't use
2076 * the nicer %e, so we have to use %d which has leading zeroes.
2077 * A lot of the fuss in the function is just getting rid of these leading
2078 * zeroes as efficiently as possible.
2080 * If parameter fixday = true (default), then take off leading
2081 * zero from %d, else maintain it.
2085 * @param int $date the timestamp in UTC, as obtained from the database.
2086 * @param string $format strftime format. You should probably get this using
2087 * get_string('strftime...', 'langconfig');
2088 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2089 * not 99 then daylight saving will not be added.
2090 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2091 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2092 * If false then the leading zero is maintained.
2093 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2094 * @return string the formatted date/time.
2096 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2100 if (empty($format)) {
2101 $format = get_string('strftimedaydatetime', 'langconfig');
2104 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
2106 } else if ($fixday) {
2107 $formatnoday = str_replace('%d', 'DD', $format);
2108 $fixday = ($formatnoday != $format);
2109 $format = $formatnoday;
2112 // Note: This logic about fixing 12-hour time to remove unnecessary leading
2113 // zero is required because on Windows, PHP strftime function does not
2114 // support the correct 'hour without leading zero' parameter (%l).
2115 if (!empty($CFG->nofixhour)) {
2116 // Config.php can force %I not to be fixed.
2118 } else if ($fixhour) {
2119 $formatnohour = str_replace('%I', 'HH', $format);
2120 $fixhour = ($formatnohour != $format);
2121 $format = $formatnohour;
2124 //add daylight saving offset for string timezones only, as we can't get dst for
2125 //float values. if timezone is 99 (user default timezone), then try update dst.
2126 if ((99 == $timezone) || !is_numeric($timezone)) {
2127 $date += dst_offset_on($date, $timezone);
2130 $timezone = get_user_timezone_offset($timezone);
2132 // If we are running under Windows convert to windows encoding and then back to UTF-8
2133 // (because it's impossible to specify UTF-8 to fetch locale info in Win32)
2135 if (abs($timezone) > 13) { /// Server time
2136 $datestring = date_format_string($date, $format, $timezone);
2138 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
2139 $datestring = str_replace('DD', $daystring, $datestring);
2142 $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2143 $datestring = str_replace('HH', $hourstring, $datestring);
2147 $date += (int)($timezone * 3600);
2148 $datestring = date_format_string($date, $format, $timezone);
2150 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
2151 $datestring = str_replace('DD', $daystring, $datestring);
2154 $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2155 $datestring = str_replace('HH', $hourstring, $datestring);
2163 * Returns a formatted date ensuring it is UTF-8.
2165 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2166 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2168 * This function does not do any calculation regarding the user preferences and should
2169 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2170 * to differenciate the use of server time or not (strftime() against gmstrftime()).
2172 * @param int $date the timestamp.
2173 * @param string $format strftime format.
2174 * @param int|float $timezone the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2175 * @return string the formatted date/time.
2178 function date_format_string($date, $format, $tz = 99) {
2180 if (abs($tz) > 13) {
2181 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
2182 $format = textlib::convert($format, 'utf-8', $localewincharset);
2183 $datestring = strftime($format, $date);
2184 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2186 $datestring = strftime($format, $date);
2189 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
2190 $format = textlib::convert($format, 'utf-8', $localewincharset);
2191 $datestring = gmstrftime($format, $date);
2192 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2194 $datestring = gmstrftime($format, $date);
2201 * Given a $time timestamp in GMT (seconds since epoch),
2202 * returns an array that represents the date in user time
2207 * @param int $time Timestamp in GMT
2208 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2209 * dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
2210 * @return array An array that represents the date in user time
2212 function usergetdate($time, $timezone=99) {
2214 //save input timezone, required for dst offset check.
2215 $passedtimezone = $timezone;
2217 $timezone = get_user_timezone_offset($timezone);
2219 if (abs($timezone) > 13) { // Server time
2220 return getdate($time);
2223 //add daylight saving offset for string timezones only, as we can't get dst for
2224 //float values. if timezone is 99 (user default timezone), then try update dst.
2225 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2226 $time += dst_offset_on($time, $passedtimezone);
2229 $time += intval((float)$timezone * HOURSECS);
2231 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2233 //be careful to ensure the returned array matches that produced by getdate() above
2236 $getdate['weekday'],
2243 $getdate['minutes'],
2245 ) = explode('_', $datestring);
2247 // set correct datatype to match with getdate()
2248 $getdate['seconds'] = (int)$getdate['seconds'];
2249 $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
2250 $getdate['year'] = (int)$getdate['year'];
2251 $getdate['mon'] = (int)$getdate['mon'];
2252 $getdate['wday'] = (int)$getdate['wday'];
2253 $getdate['mday'] = (int)$getdate['mday'];
2254 $getdate['hours'] = (int)$getdate['hours'];
2255 $getdate['minutes'] = (int)$getdate['minutes'];
2260 * Given a GMT timestamp (seconds since epoch), offsets it by
2261 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2266 * @param int $date Timestamp in GMT
2267 * @param float|int|string $timezone timezone to calculate GMT time offset before
2268 * calculating user time, 99 is default user timezone
2269 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2272 function usertime($date, $timezone=99) {
2274 $timezone = get_user_timezone_offset($timezone);
2276 if (abs($timezone) > 13) {
2279 return $date - (int)($timezone * HOURSECS);
2283 * Given a time, return the GMT timestamp of the most recent midnight
2284 * for the current user.
2288 * @param int $date Timestamp in GMT
2289 * @param float|int|string $timezone timezone to calculate GMT time offset before
2290 * calculating user midnight time, 99 is default user timezone
2291 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2292 * @return int Returns a GMT timestamp
2294 function usergetmidnight($date, $timezone=99) {
2296 $userdate = usergetdate($date, $timezone);
2298 // Time of midnight of this user's day, in GMT
2299 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2304 * Returns a string that prints the user's timezone
2308 * @param float|int|string $timezone timezone to calculate GMT time offset before
2309 * calculating user timezone, 99 is default user timezone
2310 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2313 function usertimezone($timezone=99) {
2315 $tz = get_user_timezone($timezone);
2317 if (!is_float($tz)) {
2321 if(abs($tz) > 13) { // Server time
2322 return get_string('serverlocaltime');
2325 if($tz == intval($tz)) {
2326 // Don't show .0 for whole hours
2343 * Returns a float which represents the user's timezone difference from GMT in hours
2344 * Checks various settings and picks the most dominant of those which have a value
2348 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2349 * 99 is default user timezone
2350 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2353 function get_user_timezone_offset($tz = 99) {
2357 $tz = get_user_timezone($tz);
2359 if (is_float($tz)) {
2362 $tzrecord = get_timezone_record($tz);
2363 if (empty($tzrecord)) {
2366 return (float)$tzrecord->gmtoff / HOURMINS;
2371 * Returns an int which represents the systems's timezone difference from GMT in seconds
2375 * @param float|int|string $tz timezone for which offset is required.
2376 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2377 * @return int|bool if found, false is timezone 99 or error
2379 function get_timezone_offset($tz) {
2386 if (is_numeric($tz)) {
2387 return intval($tz * 60*60);
2390 if (!$tzrecord = get_timezone_record($tz)) {
2393 return intval($tzrecord->gmtoff * 60);
2397 * Returns a float or a string which denotes the user's timezone
2398 * 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)
2399 * means that for this timezone there are also DST rules to be taken into account
2400 * Checks various settings and picks the most dominant of those which have a value
2404 * @param float|int|string $tz timezone to calculate GMT time offset before
2405 * calculating user timezone, 99 is default user timezone
2406 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2407 * @return float|string
2409 function get_user_timezone($tz = 99) {
2414 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2415 isset($USER->timezone) ? $USER->timezone : 99,
2416 isset($CFG->timezone) ? $CFG->timezone : 99,
2421 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array
2422 while(((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2423 $tz = $next['value'];
2425 return is_numeric($tz) ? (float) $tz : $tz;
2429 * Returns cached timezone record for given $timezonename
2432 * @param string $timezonename name of the timezone
2433 * @return stdClass|bool timezonerecord or false
2435 function get_timezone_record($timezonename) {
2437 static $cache = NULL;
2439 if ($cache === NULL) {
2443 if (isset($cache[$timezonename])) {
2444 return $cache[$timezonename];
2447 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2448 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2452 * Build and store the users Daylight Saving Time (DST) table
2455 * @param int $from_year Start year for the table, defaults to 1971
2456 * @param int $to_year End year for the table, defaults to 2035
2457 * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
2460 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2461 global $CFG, $SESSION, $DB;
2463 $usertz = get_user_timezone($strtimezone);
2465 if (is_float($usertz)) {
2466 // Trivial timezone, no DST
2470 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2471 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2472 unset($SESSION->dst_offsets);
2473 unset($SESSION->dst_range);
2476 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2477 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2478 // This will be the return path most of the time, pretty light computationally
2482 // Reaching here means we either need to extend our table or create it from scratch
2484 // Remember which TZ we calculated these changes for
2485 $SESSION->dst_offsettz = $usertz;
2487 if(empty($SESSION->dst_offsets)) {
2488 // If we 're creating from scratch, put the two guard elements in there
2489 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2491 if(empty($SESSION->dst_range)) {
2492 // If creating from scratch
2493 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2494 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2496 // Fill in the array with the extra years we need to process
2497 $yearstoprocess = array();
2498 for($i = $from; $i <= $to; ++$i) {
2499 $yearstoprocess[] = $i;
2502 // Take note of which years we have processed for future calls
2503 $SESSION->dst_range = array($from, $to);
2506 // If needing to extend the table, do the same
2507 $yearstoprocess = array();
2509 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2510 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2512 if($from < $SESSION->dst_range[0]) {
2513 // Take note of which years we need to process and then note that we have processed them for future calls
2514 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2515 $yearstoprocess[] = $i;
2517 $SESSION->dst_range[0] = $from;
2519 if($to > $SESSION->dst_range[1]) {
2520 // Take note of which years we need to process and then note that we have processed them for future calls
2521 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2522 $yearstoprocess[] = $i;
2524 $SESSION->dst_range[1] = $to;
2528 if(empty($yearstoprocess)) {
2529 // This means that there was a call requesting a SMALLER range than we have already calculated
2533 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2534 // Also, the array is sorted in descending timestamp order!
2538 static $presets_cache = array();
2539 if (!isset($presets_cache[$usertz])) {
2540 $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');
2542 if(empty($presets_cache[$usertz])) {
2546 // Remove ending guard (first element of the array)
2547 reset($SESSION->dst_offsets);
2548 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2550 // Add all required change timestamps
2551 foreach($yearstoprocess as $y) {
2552 // Find the record which is in effect for the year $y
2553 foreach($presets_cache[$usertz] as $year => $preset) {
2559 $changes = dst_changes_for_year($y, $preset);
2561 if($changes === NULL) {
2564 if($changes['dst'] != 0) {
2565 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2567 if($changes['std'] != 0) {
2568 $SESSION->dst_offsets[$changes['std']] = 0;
2572 // Put in a guard element at the top
2573 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2574 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2577 krsort($SESSION->dst_offsets);
2583 * Calculates the required DST change and returns a Timestamp Array
2589 * @param int|string $year Int or String Year to focus on
2590 * @param object $timezone Instatiated Timezone object
2591 * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
2593 function dst_changes_for_year($year, $timezone) {
2595 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2599 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2600 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2602 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2603 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2605 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2606 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2608 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2609 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2610 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2612 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2613 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2615 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2619 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2620 * - Note: Daylight saving only works for string timezones and not for float.
2624 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2625 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2626 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2629 function dst_offset_on($time, $strtimezone = NULL) {
2632 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2636 reset($SESSION->dst_offsets);
2637 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2638 if($from <= $time) {
2643 // This is the normal return path
2644 if($offset !== NULL) {
2648 // Reaching this point means we haven't calculated far enough, do it now:
2649 // Calculate extra DST changes if needed and recurse. The recursion always
2650 // moves toward the stopping condition, so will always end.
2653 // We need a year smaller than $SESSION->dst_range[0]
2654 if($SESSION->dst_range[0] == 1971) {
2657 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2658 return dst_offset_on($time, $strtimezone);
2661 // We need a year larger than $SESSION->dst_range[1]
2662 if($SESSION->dst_range[1] == 2035) {
2665 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2666 return dst_offset_on($time, $strtimezone);
2671 * Calculates when the day appears in specific month
2675 * @param int $startday starting day of the month
2676 * @param int $weekday The day when week starts (normally taken from user preferences)
2677 * @param int $month The month whose day is sought
2678 * @param int $year The year of the month whose day is sought
2681 function find_day_in_month($startday, $weekday, $month, $year) {
2683 $daysinmonth = days_in_month($month, $year);
2685 if($weekday == -1) {
2686 // Don't care about weekday, so return:
2687 // abs($startday) if $startday != -1
2688 // $daysinmonth otherwise
2689 return ($startday == -1) ? $daysinmonth : abs($startday);
2692 // From now on we 're looking for a specific weekday
2694 // Give "end of month" its actual value, since we know it
2695 if($startday == -1) {
2696 $startday = -1 * $daysinmonth;
2699 // Starting from day $startday, the sign is the direction
2703 $startday = abs($startday);
2704 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2706 // This is the last such weekday of the month
2707 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2708 if($lastinmonth > $daysinmonth) {
2712 // Find the first such weekday <= $startday
2713 while($lastinmonth > $startday) {
2717 return $lastinmonth;
2722 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2724 $diff = $weekday - $indexweekday;
2729 // This is the first such weekday of the month equal to or after $startday
2730 $firstfromindex = $startday + $diff;
2732 return $firstfromindex;
2738 * Calculate the number of days in a given month
2742 * @param int $month The month whose day count is sought
2743 * @param int $year The year of the month whose day count is sought
2746 function days_in_month($month, $year) {
2747 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2751 * Calculate the position in the week of a specific calendar day
2755 * @param int $day The day of the date whose position in the week is sought
2756 * @param int $month The month of the date whose position in the week is sought
2757 * @param int $year The year of the date whose position in the week is sought
2760 function dayofweek($day, $month, $year) {
2761 // I wonder if this is any different from
2762 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2763 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2766 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2769 * Returns full login url.
2771 * @return string login url
2773 function get_login_url() {
2776 $url = "$CFG->wwwroot/login/index.php";
2778 if (!empty($CFG->loginhttps)) {
2779 $url = str_replace('http:', 'https:', $url);
2786 * This function checks that the current user is logged in and has the
2787 * required privileges
2789 * This function checks that the current user is logged in, and optionally
2790 * whether they are allowed to be in a particular course and view a particular
2792 * If they are not logged in, then it redirects them to the site login unless
2793 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2794 * case they are automatically logged in as guests.
2795 * If $courseid is given and the user is not enrolled in that course then the
2796 * user is redirected to the course enrolment page.
2797 * If $cm is given and the course module is hidden and the user is not a teacher
2798 * in the course then the user is redirected to the course home page.
2800 * When $cm parameter specified, this function sets page layout to 'module'.
2801 * You need to change it manually later if some other layout needed.
2803 * @package core_access
2806 * @param mixed $courseorid id of the course or course object
2807 * @param bool $autologinguest default true
2808 * @param object $cm course module object
2809 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2810 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2811 * in order to keep redirects working properly. MDL-14495
2812 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2813 * @return mixed Void, exit, and die depending on path
2815 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2816 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2818 // Must not redirect when byteserving already started.
2819 if (!empty($_SERVER['HTTP_RANGE'])) {
2820 $preventredirect = true;
2823 // setup global $COURSE, themes, language and locale
2824 if (!empty($courseorid)) {
2825 if (is_object($courseorid)) {
2826 $course = $courseorid;
2827 } else if ($courseorid == SITEID) {
2828 $course = clone($SITE);
2830 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2833 if ($cm->course != $course->id) {
2834 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2836 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2837 if (!($cm instanceof cm_info)) {
2838 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2839 // db queries so this is not really a performance concern, however it is obviously
2840 // better if you use get_fast_modinfo to get the cm before calling this.
2841 $modinfo = get_fast_modinfo($course);
2842 $cm = $modinfo->get_cm($cm->id);
2844 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2845 $PAGE->set_pagelayout('incourse');
2847 $PAGE->set_course($course); // set's up global $COURSE
2850 // do not touch global $COURSE via $PAGE->set_course(),
2851 // the reasons is we need to be able to call require_login() at any time!!
2854 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2858 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2859 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2860 // risk leading the user back to the AJAX request URL.
2861 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2862 $setwantsurltome = false;
2865 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2866 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2867 if ($setwantsurltome) {
2868 $SESSION->wantsurl = qualified_me();
2870 redirect(get_login_url());
2873 // If the user is not even logged in yet then make sure they are
2874 if (!isloggedin()) {
2875 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2876 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2877 // misconfigured site guest, just redirect to login page
2878 redirect(get_login_url());
2879 exit; // never reached
2881 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2882 complete_user_login($guest);
2883 $USER->autologinguest = true;
2884 $SESSION->lang = $lang;
2886 //NOTE: $USER->site check was obsoleted by session test cookie,
2887 // $USER->confirmed test is in login/index.php
2888 if ($preventredirect) {
2889 throw new require_login_exception('You are not logged in');
2892 if ($setwantsurltome) {
2893 $SESSION->wantsurl = qualified_me();
2895 if (!empty($_SERVER['HTTP_REFERER'])) {
2896 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2898 redirect(get_login_url());
2899 exit; // never reached
2903 // loginas as redirection if needed
2904 if ($course->id != SITEID and session_is_loggedinas()) {
2905 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2906 if ($USER->loginascontext->instanceid != $course->id) {
2907 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2912 // check whether the user should be changing password (but only if it is REALLY them)
2913 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2914 $userauth = get_auth_plugin($USER->auth);
2915 if ($userauth->can_change_password() and !$preventredirect) {
2916 if ($setwantsurltome) {
2917 $SESSION->wantsurl = qualified_me();
2919 if ($changeurl = $userauth->change_password_url()) {
2920 //use plugin custom url
2921 redirect($changeurl);
2923 //use moodle internal method
2924 if (empty($CFG->loginhttps)) {
2925 redirect($CFG->wwwroot .'/login/change_password.php');
2927 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2928 redirect($wwwroot .'/login/change_password.php');
2932 print_error('nopasswordchangeforced', 'auth');
2936 // Check that the user account is properly set up
2937 if (user_not_fully_set_up($USER)) {
2938 if ($preventredirect) {
2939 throw new require_login_exception('User not fully set-up');
2941 if ($setwantsurltome) {
2942 $SESSION->wantsurl = qualified_me();
2944 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2947 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2950 // Do not bother admins with any formalities
2951 if (is_siteadmin()) {
2952 //set accesstime or the user will appear offline which messes up messaging
2953 user_accesstime_log($course->id);
2957 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2958 if (!$USER->policyagreed and !is_siteadmin()) {
2959 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2960 if ($preventredirect) {
2961 throw new require_login_exception('Policy not agreed');
2963 if ($setwantsurltome) {
2964 $SESSION->wantsurl = qualified_me();
2966 redirect($CFG->wwwroot .'/user/policy.php');
2967 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2968 if ($preventredirect) {
2969 throw new require_login_exception('Policy not agreed');
2971 if ($setwantsurltome) {
2972 $SESSION->wantsurl = qualified_me();
2974 redirect($CFG->wwwroot .'/user/policy.php');
2978 // Fetch the system context, the course context, and prefetch its child contexts
2979 $sysctx = context_system::instance();
2980 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2982 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2987 // If the site is currently under maintenance, then print a message
2988 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2989 if ($preventredirect) {
2990 throw new require_login_exception('Maintenance in progress');
2993 print_maintenance_message();
2996 // make sure the course itself is not hidden
2997 if ($course->id == SITEID) {
2998 // frontpage can not be hidden
3000 if (is_role_switched($course->id)) {
3001 // when switching roles ignore the hidden flag - user had to be in course to do the switch
3003 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3004 // originally there was also test of parent category visibility,
3005 // BUT is was very slow in complex queries involving "my courses"
3006 // now it is also possible to simply hide all courses user is not enrolled in :-)
3007 if ($preventredirect) {
3008 throw new require_login_exception('Course is hidden');
3010 // We need to override the navigation URL as the course won't have
3011 // been added to the navigation and thus the navigation will mess up
3012 // when trying to find it.
3013 navigation_node::override_active_url(new moodle_url('/'));
3014 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3019 // is the user enrolled?
3020 if ($course->id == SITEID) {
3021 // everybody is enrolled on the frontpage
3024 if (session_is_loggedinas()) {
3025 // Make sure the REAL person can access this course first
3026 $realuser = session_get_realuser();
3027 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3028 if ($preventredirect) {
3029 throw new require_login_exception('Invalid course login-as access');
3031 echo $OUTPUT->header();
3032 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3038 if (is_role_switched($course->id)) {
3039 // ok, user had to be inside this course before the switch
3042 } else if (is_viewing($coursecontext, $USER)) {
3043 // ok, no need to mess with enrol
3047 if (isset($USER->enrol['enrolled'][$course->id])) {
3048 if ($USER->enrol['enrolled'][$course->id] > time()) {
3050 if (isset($USER->enrol['tempguest'][$course->id])) {
3051 unset($USER->enrol['tempguest'][$course->id]);
3052 remove_temp_course_roles($coursecontext);
3056 unset($USER->enrol['enrolled'][$course->id]);
3059 if (isset($USER->enrol['tempguest'][$course->id])) {
3060 if ($USER->enrol['tempguest'][$course->id] == 0) {
3062 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3066 unset($USER->enrol['tempguest'][$course->id]);
3067 remove_temp_course_roles($coursecontext);
3074 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3075 if ($until !== false) {
3076 // active participants may always access, a timestamp in the future, 0 (always) or false.
3078 $until = ENROL_MAX_TIMESTAMP;
3080 $USER->enrol['enrolled'][$course->id] = $until;
3084 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
3085 $enrols = enrol_get_plugins(true);
3086 // first ask all enabled enrol instances in course if they want to auto enrol user
3087 foreach($instances as $instance) {
3088 if (!isset($enrols[$instance->enrol])) {
3091 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3092 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3093 if ($until !== false) {
3095 $until = ENROL_MAX_TIMESTAMP;
3097 $USER->enrol['enrolled'][$course->id] = $until;
3102 // if not enrolled yet try to gain temporary guest access
3104 foreach($instances as $instance) {
3105 if (!isset($enrols[$instance->enrol])) {
3108 // Get a duration for the guest access, a timestamp in the future or false.
3109 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3110 if ($until !== false and $until > time()) {
3111 $USER->enrol['tempguest'][$course->id] = $until;
3122 if ($preventredirect) {
3123 throw new require_login_exception('Not enrolled');
3125 if ($setwantsurltome) {
3126 $SESSION->wantsurl = qualified_me();
3128 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3132 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
3133 // conditional availability, etc
3134 if ($cm && !$cm->uservisible) {
3135 if ($preventredirect) {
3136 throw new require_login_exception('Activity is hidden');
3138 if ($course->id != SITEID) {
3139 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
3141 $url = new moodle_url('/');
3143 redirect($url, get_string('activityiscurrentlyhidden'));
3146 // Finally access granted, update lastaccess times
3147 user_accesstime_log($course->id);
3152 * This function just makes sure a user is logged out.
3154 * @package core_access
3156 function require_logout() {
3162 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
3164 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
3165 foreach($authsequence as $authname) {
3166 $authplugin = get_auth_plugin($authname);
3167 $authplugin->prelogout_hook();
3171 events_trigger('user_logout', $params);
3172 session_get_instance()->terminate_current();
3177 * Weaker version of require_login()
3179 * This is a weaker version of {@link require_login()} which only requires login
3180 * when called from within a course rather than the site page, unless
3181 * the forcelogin option is turned on.
3182 * @see require_login()
3184 * @package core_access
3187 * @param mixed $courseorid The course object or id in question
3188 * @param bool $autologinguest Allow autologin guests if that is wanted
3189 * @param object $cm Course activity module if known
3190 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3191 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3192 * in order to keep redirects working properly. MDL-14495
3193 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3196 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
3197 global $CFG, $PAGE, $SITE;
3198 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3199 or (!is_object($courseorid) and $courseorid == SITEID);
3200 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3201 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
3202 // db queries so this is not really a performance concern, however it is obviously
3203 // better if you use get_fast_modinfo to get the cm before calling this.
3204 if (is_object($courseorid)) {
3205 $course = $courseorid;
3207 $course = clone($SITE);
3209 $modinfo = get_fast_modinfo($course);
3210 $cm = $modinfo->get_cm($cm->id);
3212 if (!empty($CFG->forcelogin)) {
3213 // login required for both SITE and courses
3214 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3216 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3217 // always login for hidden activities
3218 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3220 } else if ($issite) {
3221 //login for SITE not required
3222 if ($cm and empty($cm->visible)) {
3223 // hidden activities are not accessible without login
3224 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3225 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3226 // not-logged-in users do not have any group membership
3227 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3229 // We still need to instatiate PAGE vars properly so that things
3230 // that rely on it like navigation function correctly.
3231 if (!empty($courseorid)) {
3232 if (is_object($courseorid)) {
3233 $course = $courseorid;
3235 $course = clone($SITE);
3238 if ($cm->course != $course->id) {
3239 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3241 $PAGE->set_cm($cm, $course);
3242 $PAGE->set_pagelayout('incourse');
3244 $PAGE->set_course($course);
3247 // If $PAGE->course, and hence $PAGE->context, have not already been set
3248 // up properly, set them up now.
3249 $PAGE->set_course($PAGE->course);
3251 //TODO: verify conditional activities here
3252 user_accesstime_log(SITEID);
3257 // course login always required
3258 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3263 * Require key login. Function terminates with error if key not found or incorrect.
3269 * @uses NO_MOODLE_COOKIES
3270 * @uses PARAM_ALPHANUM
3271 * @param string $script unique script identifier
3272 * @param int $instance optional instance id
3273 * @return int Instance ID
3275 function require_user_key_login($script, $instance=null) {
3276 global $USER, $SESSION, $CFG, $DB;
3278 if (!NO_MOODLE_COOKIES) {
3279 print_error('sessioncookiesdisable');
3283 @session_write_close();
3285 $keyvalue = required_param('key', PARAM_ALPHANUM);
3287 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3288 print_error('invalidkey');
3291 if (!empty($key->validuntil) and $key->validuntil < time()) {
3292 print_error('expiredkey');
3295 if ($key->iprestriction) {
3296 $remoteaddr = getremoteaddr(null);
3297 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3298 print_error('ipmismatch');
3302 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
3303 print_error('invaliduserid');
3306 /// emulate normal session
3307 enrol_check_plugins($user);
3308 session_set_user($user);
3310 /// note we are not using normal login
3311 if (!defined('USER_KEY_LOGIN')) {
3312 define('USER_KEY_LOGIN', true);
3315 /// return instance id - it might be empty
3316 return $key->instance;
3320 * Creates a new private user access key.
3323 * @param string $script unique target identifier
3324 * @param int $userid
3325 * @param int $instance optional instance id
3326 * @param string $iprestriction optional ip restricted access
3327 * @param timestamp $validuntil key valid only until given data
3328 * @return string access key value
3330 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3333 $key = new stdClass();
3334 $key->script = $script;
3335 $key->userid = $userid;
3336 $key->instance = $instance;
3337 $key->iprestriction = $iprestriction;
3338 $key->validuntil = $validuntil;
3339 $key->timecreated = time();
3341 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
3342 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3344 $key->value = md5($userid.'_'.time().random_string(40));
3346 $DB->insert_record('user_private_key', $key);
3351 * Delete the user's new private user access keys for a particular script.
3354 * @param string $script unique target identifier
3355 * @param int $userid
3358 function delete_user_key($script,$userid) {
3360 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3364 * Gets a private user access key (and creates one if one doesn't exist).
3367 * @param string $script unique target identifier
3368 * @param int $userid
3369 * @param int $instance optional instance id
3370 * @param string $iprestriction optional ip restricted access
3371 * @param timestamp $validuntil key valid only until given data
3372 * @return string access key value
3374 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3377 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3378 'instance'=>$instance, 'iprestriction'=>$iprestriction,
3379 'validuntil'=>$validuntil))) {
3382 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3388 * Modify the user table by setting the currently logged in user's
3389 * last login to now.
3393 * @return bool Always returns true
3395 function update_user_login_times() {
3398 if (isguestuser()) {
3399 // Do not update guest access times/ips for performance.
3405 $user = new stdClass();
3406 $user->id = $USER->id;
3408 // Make sure all users that logged in have some firstaccess.
3409 if ($USER->firstaccess == 0) {
3410 $USER->firstaccess = $user->firstaccess = $now;
3413 // Store the previous current as lastlogin.
3414 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3416 $USER->currentlogin = $user->currentlogin = $now;
3418 // Function user_accesstime_log() may not update immediately, better do it here.
3419 $USER->lastaccess = $user->lastaccess = $now;
3420 $USER->lastip = $user->lastip = getremoteaddr();
3422 $DB->update_record('user', $user);
3427 * Determines if a user has completed setting up their account.
3429 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3432 function user_not_fully_set_up($user) {
3433 if (isguestuser($user)) {
3436 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3440 * Check whether the user has exceeded the bounce threshold
3444 * @param user $user A {@link $USER} object
3445 * @return bool true=>User has exceeded bounce threshold
3447 function over_bounce_threshold($user) {
3450 if (empty($CFG->handlebounces)) {
3454 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3458 // set sensible defaults
3459 if (empty($CFG->minbounces)) {
3460 $CFG->minbounces = 10;
3462 if (empty($CFG->bounceratio)) {
3463 $CFG->bounceratio = .20;
3467 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3468 $bouncecount = $bounce->value;
3470 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3471 $sendcount = $send->value;
3473 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3477 * Used to increment or reset email sent count
3480 * @param user $user object containing an id
3481 * @param bool $reset will reset the count to 0
3484 function set_send_count($user,$reset=false) {
3487 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3491 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3492 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3493 $DB->update_record('user_preferences', $pref);
3495 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3497 $pref = new stdClass();
3498 $pref->name = 'email_send_count';
3500 $pref->userid = $user->id;
3501 $DB->insert_record('user_preferences', $pref, false);
3506 * Increment or reset user's email bounce count
3509 * @param user $user object containing an id
3510 * @param bool $reset will reset the count to 0
3512 function set_bounce_count($user,$reset=false) {
3515 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3516 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3517 $DB->update_record('user_preferences', $pref);
3519 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3521 $pref = new stdClass();
3522 $pref->name = 'email_bounce_count';
3524 $pref->userid = $user->id;
3525 $DB->insert_record('user_preferences', $pref, false);
3530 * Determines if the currently logged in user is in editing mode.
3531 * Note: originally this function had $userid parameter - it was not usable anyway
3533 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3534 * @todo Deprecated function remove when ready
3537 * @uses DEBUG_DEVELOPER
3540 function isediting() {
3542 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3543 return $PAGE->user_is_editing();
3547 * Determines if the logged in user is currently moving an activity
3550 * @param int $courseid The id of the course being tested
3553 function ismoving($courseid) {
3556 if (!empty($USER->activitycopy)) {
3557 return ($USER->activitycopycourse == $courseid);
3563 * Returns a persons full name
3565 * Given an object containing all of the users name
3566 * values, this function returns a string with the
3567 * full name of the person.
3568 * The result may depend on system settings
3569 * or language. 'override' will force both names
3570 * to be used even if system settings specify one.
3574 * @param object $user A {@link $USER} object to get full name of.
3575 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3578 function fullname($user, $override=false) {
3579 global $CFG, $SESSION;
3581 if (!isset($user->firstname) and !isset($user->lastname)) {
3586 if (!empty($CFG->forcefirstname)) {
3587 $user->firstname = $CFG->forcefirstname;
3589 if (!empty($CFG->forcelastname)) {
3590 $user->lastname = $CFG->forcelastname;
3594 if (!empty($SESSION->fullnamedisplay)) {
3595 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3599 // If the fullnamedisplay setting is available, set the template to that.
3600 if (isset($CFG->fullnamedisplay)) {
3601 $template = $CFG->fullnamedisplay;
3603 // If the template is empty, or set to language, or $override is set, return the language string.
3604 if (empty($template) || $template == 'language' || $override) {
3605 return get_string('fullnamedisplay', null, $user);
3608 // Get all of the name fields.
3609 $allnames = get_all_user_name_fields();
3610 $requirednames = array();
3611 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3612 foreach ($allnames as $allname) {
3613 if (strpos($template, $allname) !== false) {
3614 $requirednames[] = $allname;
3615 // If the field is in the template, but not set in the user object, then notify the programmer that it needs to be fixed.
3616 if (!array_key_exists($allname, $user)) {
3617 debugging('You need to update your sql query to include additional name fields in the user object.', DEBUG_DEVELOPER);
3622 $displayname = $template;
3623 // Switch in the actual data into the template.
3624 foreach ($requirednames as $altname) {
3625 if (isset($user->$altname)) {
3626 // Using empty() on the below if statement causes breakages.
3627 if ((string)$user->$altname == '') {
3628 $displayname = str_replace($altname, 'EMPTY', $displayname);
3630 $displayname = str_replace($altname, $user->$altname, $displayname);
3633 $displayname = str_replace($altname, 'EMPTY', $displayname);
3636 // Tidy up any misc. characters (Not perfect, but gets most characters).
3637 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or katakana and parenthesis.
3638 $patterns = array();
3639 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been filled in by a user.
3640 // The special characters are Japanese brackets that are common enough to make special allowance for them (not covered by :punct:).
3641 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3642 // This regular expression is to remove any double spaces in the display name.
3643 $patterns[] = '/\s{2,}/';
3644 foreach ($patterns as $pattern) {
3645 $displayname = preg_replace($pattern, ' ', $displayname);
3648 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3649 $displayname = trim($displayname);
3650 if (empty($displayname)) {