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.
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
83 define('PARAM_ALPHAEXT', 'alphaext');
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
98 define('PARAM_AUTH', 'auth');
101 * PARAM_BASE64 - Base 64 encoded format
103 define('PARAM_BASE64', 'base64');
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
108 define('PARAM_BOOL', 'bool');
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
114 define('PARAM_CAPABILITY', 'capability');
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119 * the input (required/optional_param or formslib) and then sanitse the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
123 define('PARAM_CLEANHTML', 'cleanhtml');
126 * PARAM_EMAIL - an email address following the RFC
128 define('PARAM_EMAIL', 'email');
131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
133 define('PARAM_FILE', 'file');
136 * PARAM_FLOAT - a real/floating point number.
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
146 define('PARAM_FLOAT', 'float');
149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
151 define('PARAM_HOST', 'host');
154 * PARAM_INT - integers only, use when expecting only numbers.
156 define('PARAM_INT', 'int');
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
161 define('PARAM_LANG', 'lang');
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
167 define('PARAM_LOCALURL', 'localurl');
170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
172 define('PARAM_NOTAGS', 'notags');
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
178 define('PARAM_PATH', 'path');
181 * PARAM_PEM - Privacy Enhanced Mail format
183 define('PARAM_PEM', 'pem');
186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
188 define('PARAM_PERMISSION', 'permission');
191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
193 define('PARAM_RAW', 'raw');
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
203 define('PARAM_SAFEDIR', 'safedir');
206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
208 define('PARAM_SAFEPATH', 'safepath');
211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
213 define('PARAM_SEQUENCE', 'sequence');
216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
218 define('PARAM_TAG', 'tag');
221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
223 define('PARAM_TAGLIST', 'taglist');
226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
228 define('PARAM_TEXT', 'text');
231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
233 define('PARAM_THEME', 'theme');
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * 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
243 * accounts, do NOT use when syncing with external systems!!
245 define('PARAM_USERNAME', 'username');
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
250 define('PARAM_STRINGID', 'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
256 * @deprecated since 2.0
258 define('PARAM_CLEAN', 'clean');
261 * PARAM_INTEGER - deprecated alias for PARAM_INT
262 * @deprecated since 2.0
264 define('PARAM_INTEGER', 'int');
267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268 * @deprecated since 2.0
270 define('PARAM_NUMBER', 'float');
273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274 * NOTE: originally alias for PARAM_APLHA
275 * @deprecated since 2.0
277 define('PARAM_ACTION', 'alphanumext');
280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
282 * @deprecated since 2.0
284 define('PARAM_FORMAT', 'alphanumext');
287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288 * @deprecated since 2.0
290 define('PARAM_MULTILANG', 'text');
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295 * America/Port-au-Prince)
297 define('PARAM_TIMEZONE', 'timezone');
300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
302 define('PARAM_CLEANFILE', 'file');
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
310 define('PARAM_COMPONENT', 'component');
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
317 define('PARAM_AREA', 'area');
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
324 define('PARAM_PLUGIN', 'plugin');
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
332 define('VALUE_REQUIRED', 1);
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
337 define('VALUE_OPTIONAL', 2);
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
342 define('VALUE_DEFAULT', 0);
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
347 define('NULL_NOT_ALLOWED', false);
350 * NULL_ALLOWED - the parameter can be set to null in the database
352 define('NULL_ALLOWED', true);
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True if module supports outcomes */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
417 /** True if module supports groupmembersonly */
418 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
420 /** Type of module */
421 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
422 /** True if module supports intro editor */
423 define('FEATURE_MOD_INTRO', 'mod_intro');
424 /** True if module has default completion */
425 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
427 define('FEATURE_COMMENT', 'comment');
429 define('FEATURE_RATE', 'rate');
430 /** True if module supports backup/restore of moodle2 format */
431 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
433 /** True if module can show description on course main page */
434 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
436 /** Unspecified module archetype */
437 define('MOD_ARCHETYPE_OTHER', 0);
438 /** Resource-like type module */
439 define('MOD_ARCHETYPE_RESOURCE', 1);
440 /** Assignment module archetype */
441 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
442 /** System (not user-addable) module archetype */
443 define('MOD_ARCHETYPE_SYSTEM', 3);
446 * Security token used for allowing access
447 * from external application such as web services.
448 * Scripts do not use any session, performance is relatively
449 * low because we need to load access info in each request.
450 * Scripts are executed in parallel.
452 define('EXTERNAL_TOKEN_PERMANENT', 0);
455 * Security token used for allowing access
456 * of embedded applications, the code is executed in the
457 * active user session. Token is invalidated after user logs out.
458 * Scripts are executed serially - normal session locking is used.
460 define('EXTERNAL_TOKEN_EMBEDDED', 1);
463 * The home page should be the site home
465 define('HOMEPAGE_SITE', 0);
467 * The home page should be the users my page
469 define('HOMEPAGE_MY', 1);
471 * The home page can be chosen by the user
473 define('HOMEPAGE_USER', 2);
476 * Hub directory url (should be moodle.org)
478 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
482 * Moodle.org url (should be moodle.org)
484 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
487 * Moodle mobile app service name
489 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
492 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
494 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
497 * Course display settings: display all sections on one page.
499 define('COURSE_DISPLAY_SINGLEPAGE', 0);
501 * Course display settings: split pages into a page per section.
503 define('COURSE_DISPLAY_MULTIPAGE', 1);
506 * Authentication constant: String used in password field when password is not stored.
508 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
510 // PARAMETER HANDLING.
513 * Returns a particular value for the named variable, taken from
514 * POST or GET. If the parameter doesn't exist then an error is
515 * thrown because we require this variable.
517 * This function should be used to initialise all required values
518 * in a script that are based on parameters. Usually it will be
520 * $id = required_param('id', PARAM_INT);
522 * Please note the $type parameter is now required and the value can not be array.
524 * @param string $parname the name of the page parameter we want
525 * @param string $type expected type of parameter
527 * @throws coding_exception
529 function required_param($parname, $type) {
530 if (func_num_args() != 2 or empty($parname) or empty($type)) {
531 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
533 // POST has precedence.
534 if (isset($_POST[$parname])) {
535 $param = $_POST[$parname];
536 } else if (isset($_GET[$parname])) {
537 $param = $_GET[$parname];
539 print_error('missingparam', '', '', $parname);
542 if (is_array($param)) {
543 debugging('Invalid array parameter detected in required_param(): '.$parname);
544 // TODO: switch to fatal error in Moodle 2.3.
545 return required_param_array($parname, $type);
548 return clean_param($param, $type);
552 * Returns a particular array value for the named variable, taken from
553 * POST or GET. If the parameter doesn't exist then an error is
554 * thrown because we require this variable.
556 * This function should be used to initialise all required values
557 * in a script that are based on parameters. Usually it will be
559 * $ids = required_param_array('ids', PARAM_INT);
561 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
563 * @param string $parname the name of the page parameter we want
564 * @param string $type expected type of parameter
566 * @throws coding_exception
568 function required_param_array($parname, $type) {
569 if (func_num_args() != 2 or empty($parname) or empty($type)) {
570 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
572 // POST has precedence.
573 if (isset($_POST[$parname])) {
574 $param = $_POST[$parname];
575 } else if (isset($_GET[$parname])) {
576 $param = $_GET[$parname];
578 print_error('missingparam', '', '', $parname);
580 if (!is_array($param)) {
581 print_error('missingparam', '', '', $parname);
585 foreach ($param as $key => $value) {
586 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
587 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
590 $result[$key] = clean_param($value, $type);
597 * Returns a particular value for the named variable, taken from
598 * POST or GET, otherwise returning a given default.
600 * This function should be used to initialise all optional values
601 * in a script that are based on parameters. Usually it will be
603 * $name = optional_param('name', 'Fred', PARAM_TEXT);
605 * Please note the $type parameter is now required and the value can not be array.
607 * @param string $parname the name of the page parameter we want
608 * @param mixed $default the default value to return if nothing is found
609 * @param string $type expected type of parameter
611 * @throws coding_exception
613 function optional_param($parname, $default, $type) {
614 if (func_num_args() != 3 or empty($parname) or empty($type)) {
615 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
617 if (!isset($default)) {
621 // POST has precedence.
622 if (isset($_POST[$parname])) {
623 $param = $_POST[$parname];
624 } else if (isset($_GET[$parname])) {
625 $param = $_GET[$parname];
630 if (is_array($param)) {
631 debugging('Invalid array parameter detected in required_param(): '.$parname);
632 // TODO: switch to $default in Moodle 2.3.
633 return optional_param_array($parname, $default, $type);
636 return clean_param($param, $type);
640 * Returns a particular array value for the named variable, taken from
641 * POST or GET, otherwise returning a given default.
643 * This function should be used to initialise all optional values
644 * in a script that are based on parameters. Usually it will be
646 * $ids = optional_param('id', array(), PARAM_INT);
648 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
650 * @param string $parname the name of the page parameter we want
651 * @param mixed $default the default value to return if nothing is found
652 * @param string $type expected type of parameter
654 * @throws coding_exception
656 function optional_param_array($parname, $default, $type) {
657 if (func_num_args() != 3 or empty($parname) or empty($type)) {
658 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
661 // POST has precedence.
662 if (isset($_POST[$parname])) {
663 $param = $_POST[$parname];
664 } else if (isset($_GET[$parname])) {
665 $param = $_GET[$parname];
669 if (!is_array($param)) {
670 debugging('optional_param_array() expects array parameters only: '.$parname);
675 foreach ($param as $key => $value) {
676 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
677 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
680 $result[$key] = clean_param($value, $type);
687 * Strict validation of parameter values, the values are only converted
688 * to requested PHP type. Internally it is using clean_param, the values
689 * before and after cleaning must be equal - otherwise
690 * an invalid_parameter_exception is thrown.
691 * Objects and classes are not accepted.
693 * @param mixed $param
694 * @param string $type PARAM_ constant
695 * @param bool $allownull are nulls valid value?
696 * @param string $debuginfo optional debug information
697 * @return mixed the $param value converted to PHP type
698 * @throws invalid_parameter_exception if $param is not of given type
700 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
701 if (is_null($param)) {
702 if ($allownull == NULL_ALLOWED) {
705 throw new invalid_parameter_exception($debuginfo);
708 if (is_array($param) or is_object($param)) {
709 throw new invalid_parameter_exception($debuginfo);
712 $cleaned = clean_param($param, $type);
714 if ($type == PARAM_FLOAT) {
715 // Do not detect precision loss here.
716 if (is_float($param) or is_int($param)) {
718 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
719 throw new invalid_parameter_exception($debuginfo);
721 } else if ((string)$param !== (string)$cleaned) {
722 // Conversion to string is usually lossless.
723 throw new invalid_parameter_exception($debuginfo);
730 * Makes sure array contains only the allowed types, this function does not validate array key names!
733 * $options = clean_param($options, PARAM_INT);
736 * @param array $param the variable array we are cleaning
737 * @param string $type expected format of param after cleaning.
738 * @param bool $recursive clean recursive arrays
740 * @throws coding_exception
742 function clean_param_array(array $param = null, $type, $recursive = false) {
743 // Convert null to empty array.
744 $param = (array)$param;
745 foreach ($param as $key => $value) {
746 if (is_array($value)) {
748 $param[$key] = clean_param_array($value, $type, true);
750 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
753 $param[$key] = clean_param($value, $type);
760 * Used by {@link optional_param()} and {@link required_param()} to
761 * clean the variables and/or cast to specific types, based on
764 * $course->format = clean_param($course->format, PARAM_ALPHA);
765 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
768 * @param mixed $param the variable we are cleaning
769 * @param string $type expected format of param after cleaning.
771 * @throws coding_exception
773 function clean_param($param, $type) {
776 if (is_array($param)) {
777 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
778 } else if (is_object($param)) {
779 if (method_exists($param, '__toString')) {
780 $param = $param->__toString();
782 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
788 // No cleaning at all.
789 $param = fix_utf8($param);
792 case PARAM_RAW_TRIMMED:
793 // No cleaning, but strip leading and trailing whitespace.
794 $param = fix_utf8($param);
798 // General HTML cleaning, try to use more specific type if possible this is deprecated!
799 // Please use more specific type instead.
800 if (is_numeric($param)) {
803 $param = fix_utf8($param);
804 // Sweep for scripts, etc.
805 return clean_text($param);
807 case PARAM_CLEANHTML:
808 // Clean html fragment.
809 $param = fix_utf8($param);
810 // Sweep for scripts, etc.
811 $param = clean_text($param, FORMAT_HTML);
815 // Convert to integer.
820 return (float)$param;
823 // Remove everything not `a-z`.
824 return preg_replace('/[^a-zA-Z]/i', '', $param);
827 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
828 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
831 // Remove everything not `a-zA-Z0-9`.
832 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
834 case PARAM_ALPHANUMEXT:
835 // Remove everything not `a-zA-Z0-9_-`.
836 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
839 // Remove everything not `0-9,`.
840 return preg_replace('/[^0-9,]/i', '', $param);
843 // Convert to 1 or 0.
844 $tempstr = strtolower($param);
845 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
847 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
850 $param = empty($param) ? 0 : 1;
856 $param = fix_utf8($param);
857 return strip_tags($param);
860 // Leave only tags needed for multilang.
861 $param = fix_utf8($param);
862 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
863 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
865 if (strpos($param, '</lang>') !== false) {
866 // Old and future mutilang syntax.
867 $param = strip_tags($param, '<lang>');
868 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
872 foreach ($matches[0] as $match) {
873 if ($match === '</lang>') {
881 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
892 } else if (strpos($param, '</span>') !== false) {
893 // Current problematic multilang syntax.
894 $param = strip_tags($param, '<span>');
895 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
899 foreach ($matches[0] as $match) {
900 if ($match === '</span>') {
908 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
920 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
921 return strip_tags($param);
923 case PARAM_COMPONENT:
924 // We do not want any guessing here, either the name is correct or not
925 // please note only normalised component names are accepted.
926 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
929 if (strpos($param, '__') !== false) {
932 if (strpos($param, 'mod_') === 0) {
933 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
934 if (substr_count($param, '_') != 1) {
942 // We do not want any guessing here, either the name is correct or not.
943 if (!is_valid_plugin_name($param)) {
949 // Remove everything not a-zA-Z0-9_- .
950 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
953 // Remove everything not a-zA-Z0-9/_- .
954 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
957 // Strip all suspicious characters from filename.
958 $param = fix_utf8($param);
959 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
960 if ($param === '.' || $param === '..') {
966 // Strip all suspicious characters from file path.
967 $param = fix_utf8($param);
968 $param = str_replace('\\', '/', $param);
970 // Explode the path and clean each element using the PARAM_FILE rules.
971 $breadcrumb = explode('/', $param);
972 foreach ($breadcrumb as $key => $crumb) {
973 if ($crumb === '.' && $key === 0) {
974 // Special condition to allow for relative current path such as ./currentdirfile.txt.
976 $crumb = clean_param($crumb, PARAM_FILE);
978 $breadcrumb[$key] = $crumb;
980 $param = implode('/', $breadcrumb);
982 // Remove multiple current path (./././) and multiple slashes (///).
983 $param = preg_replace('~//+~', '/', $param);
984 $param = preg_replace('~/(\./)+~', '/', $param);
988 // Allow FQDN or IPv4 dotted quad.
989 $param = preg_replace('/[^\.\d\w-]/', '', $param );
990 // Match ipv4 dotted quad.
991 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
992 // Confirm values are ok.
996 || $match[4] > 255 ) {
997 // Hmmm, what kind of dotted quad is this?
1000 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1001 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1002 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1004 // All is ok - $param is respected.
1011 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1012 $param = fix_utf8($param);
1013 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1014 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1015 // All is ok, param is respected.
1022 case PARAM_LOCALURL:
1023 // Allow http absolute, root relative and relative URLs within wwwroot.
1024 $param = clean_param($param, PARAM_URL);
1025 if (!empty($param)) {
1026 if (preg_match(':^/:', $param)) {
1027 // Root-relative, ok!
1028 } else if (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i', $param)) {
1029 // Absolute, and matches our wwwroot.
1031 // Relative - let's make sure there are no tricks.
1032 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1042 $param = trim($param);
1043 // PEM formatted strings may contain letters/numbers and the symbols:
1047 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1048 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1049 list($wholething, $body) = $matches;
1050 unset($wholething, $matches);
1051 $b64 = clean_param($body, PARAM_BASE64);
1053 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1061 if (!empty($param)) {
1062 // PEM formatted strings may contain letters/numbers and the symbols
1066 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1069 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1070 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1071 // than (or equal to) 64 characters long.
1072 for ($i=0, $j=count($lines); $i < $j; $i++) {
1074 if (64 < strlen($lines[$i])) {
1080 if (64 != strlen($lines[$i])) {
1084 return implode("\n", $lines);
1090 $param = fix_utf8($param);
1091 // Please note it is not safe to use the tag name directly anywhere,
1092 // it must be processed with s(), urlencode() before embedding anywhere.
1093 // Remove some nasties.
1094 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1095 // Convert many whitespace chars into one.
1096 $param = preg_replace('/\s+/', ' ', $param);
1097 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1101 $param = fix_utf8($param);
1102 $tags = explode(',', $param);
1104 foreach ($tags as $tag) {
1105 $res = clean_param($tag, PARAM_TAG);
1111 return implode(',', $result);
1116 case PARAM_CAPABILITY:
1117 if (get_capability_info($param)) {
1123 case PARAM_PERMISSION:
1124 $param = (int)$param;
1125 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1132 $param = clean_param($param, PARAM_PLUGIN);
1133 if (empty($param)) {
1135 } else if (exists_auth_plugin($param)) {
1142 $param = clean_param($param, PARAM_SAFEDIR);
1143 if (get_string_manager()->translation_exists($param)) {
1146 // Specified language is not installed or param malformed.
1151 $param = clean_param($param, PARAM_PLUGIN);
1152 if (empty($param)) {
1154 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1156 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1159 // Specified theme is not installed.
1163 case PARAM_USERNAME:
1164 $param = fix_utf8($param);
1165 $param = str_replace(" " , "", $param);
1166 // Convert uppercase to lowercase MDL-16919.
1167 $param = core_text::strtolower($param);
1168 if (empty($CFG->extendedusernamechars)) {
1169 // Regular expression, eliminate all chars EXCEPT:
1170 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1171 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1176 $param = fix_utf8($param);
1177 if (validate_email($param)) {
1183 case PARAM_STRINGID:
1184 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1190 case PARAM_TIMEZONE:
1191 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1192 $param = fix_utf8($param);
1193 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1194 if (preg_match($timezonepattern, $param)) {
1201 // Doh! throw error, switched parameters in optional_param or another serious problem.
1202 print_error("unknownparamtype", '', '', $type);
1207 * Makes sure the data is using valid utf8, invalid characters are discarded.
1209 * Note: this function is not intended for full objects with methods and private properties.
1211 * @param mixed $value
1212 * @return mixed with proper utf-8 encoding
1214 function fix_utf8($value) {
1215 if (is_null($value) or $value === '') {
1218 } else if (is_string($value)) {
1219 if ((string)(int)$value === $value) {
1224 // Lower error reporting because glibc throws bogus notices.
1225 $olderror = error_reporting();
1226 if ($olderror & E_NOTICE) {
1227 error_reporting($olderror ^ E_NOTICE);
1230 // Note: this duplicates min_fix_utf8() intentionally.
1231 static $buggyiconv = null;
1232 if ($buggyiconv === null) {
1233 $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1237 if (function_exists('mb_convert_encoding')) {
1238 $subst = mb_substitute_character();
1239 mb_substitute_character('');
1240 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1241 mb_substitute_character($subst);
1244 // Warn admins on admin/index.php page.
1249 $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1252 if ($olderror & E_NOTICE) {
1253 error_reporting($olderror);
1258 } else if (is_array($value)) {
1259 foreach ($value as $k => $v) {
1260 $value[$k] = fix_utf8($v);
1264 } else if (is_object($value)) {
1265 // Do not modify original.
1266 $value = clone($value);
1267 foreach ($value as $k => $v) {
1268 $value->$k = fix_utf8($v);
1273 // This is some other type, no utf-8 here.
1279 * Return true if given value is integer or string with integer value
1281 * @param mixed $value String or Int
1282 * @return bool true if number, false if not
1284 function is_number($value) {
1285 if (is_int($value)) {
1287 } else if (is_string($value)) {
1288 return ((string)(int)$value) === $value;
1295 * Returns host part from url.
1297 * @param string $url full url
1298 * @return string host, null if not found
1300 function get_host_from_url($url) {
1301 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1309 * Tests whether anything was returned by text editor
1311 * This function is useful for testing whether something you got back from
1312 * the HTML editor actually contains anything. Sometimes the HTML editor
1313 * appear to be empty, but actually you get back a <br> tag or something.
1315 * @param string $string a string containing HTML.
1316 * @return boolean does the string contain any actual content - that is text,
1317 * images, objects, etc.
1319 function html_is_blank($string) {
1320 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1324 * Set a key in global configuration
1326 * Set a key/value pair in both this session's {@link $CFG} global variable
1327 * and in the 'config' database table for future sessions.
1329 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1330 * In that case it doesn't affect $CFG.
1332 * A NULL value will delete the entry.
1334 * @param string $name the key to set
1335 * @param string $value the value to set (without magic quotes)
1336 * @param string $plugin (optional) the plugin scope, default null
1337 * @return bool true or exception
1339 function set_config($name, $value, $plugin=null) {
1342 if (empty($plugin)) {
1343 if (!array_key_exists($name, $CFG->config_php_settings)) {
1344 // So it's defined for this invocation at least.
1345 if (is_null($value)) {
1348 // Settings from db are always strings.
1349 $CFG->$name = (string)$value;
1353 if ($DB->get_field('config', 'name', array('name' => $name))) {
1354 if ($value === null) {
1355 $DB->delete_records('config', array('name' => $name));
1357 $DB->set_field('config', 'value', $value, array('name' => $name));
1360 if ($value !== null) {
1361 $config = new stdClass();
1362 $config->name = $name;
1363 $config->value = $value;
1364 $DB->insert_record('config', $config, false);
1367 if ($name === 'siteidentifier') {
1368 cache_helper::update_site_identifier($value);
1370 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1373 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1374 if ($value===null) {
1375 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1377 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1380 if ($value !== null) {
1381 $config = new stdClass();
1382 $config->plugin = $plugin;
1383 $config->name = $name;
1384 $config->value = $value;
1385 $DB->insert_record('config_plugins', $config, false);
1388 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1395 * Get configuration values from the global config table
1396 * or the config_plugins table.
1398 * If called with one parameter, it will load all the config
1399 * variables for one plugin, and return them as an object.
1401 * If called with 2 parameters it will return a string single
1402 * value or false if the value is not found.
1404 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1405 * that we need only fetch it once per request.
1406 * @param string $plugin full component name
1407 * @param string $name default null
1408 * @return mixed hash-like object or single value, return false no config found
1409 * @throws dml_exception
1411 function get_config($plugin, $name = null) {
1414 static $siteidentifier = null;
1416 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1417 $forced =& $CFG->config_php_settings;
1421 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1422 $forced =& $CFG->forced_plugin_settings[$plugin];
1429 if ($siteidentifier === null) {
1431 // This may fail during installation.
1432 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1433 // install the database.
1434 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1435 } catch (dml_exception $ex) {
1436 // Set siteidentifier to false. We don't want to trip this continually.
1437 $siteidentifier = false;
1442 if (!empty($name)) {
1443 if (array_key_exists($name, $forced)) {
1444 return (string)$forced[$name];
1445 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1446 return $siteidentifier;
1450 $cache = cache::make('core', 'config');
1451 $result = $cache->get($plugin);
1452 if ($result === false) {
1453 // The user is after a recordset.
1455 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1457 // This part is not really used any more, but anyway...
1458 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1460 $cache->set($plugin, $result);
1463 if (!empty($name)) {
1464 if (array_key_exists($name, $result)) {
1465 return $result[$name];
1470 if ($plugin === 'core') {
1471 $result['siteidentifier'] = $siteidentifier;
1474 foreach ($forced as $key => $value) {
1475 if (is_null($value) or is_array($value) or is_object($value)) {
1476 // We do not want any extra mess here, just real settings that could be saved in db.
1477 unset($result[$key]);
1479 // Convert to string as if it went through the DB.
1480 $result[$key] = (string)$value;
1484 return (object)$result;
1488 * Removes a key from global configuration.
1490 * @param string $name the key to set
1491 * @param string $plugin (optional) the plugin scope
1492 * @return boolean whether the operation succeeded.
1494 function unset_config($name, $plugin=null) {
1497 if (empty($plugin)) {
1499 $DB->delete_records('config', array('name' => $name));
1500 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1502 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1503 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1510 * Remove all the config variables for a given plugin.
1512 * NOTE: this function is called from lib/db/upgrade.php
1514 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1515 * @return boolean whether the operation succeeded.
1517 function unset_all_config_for_plugin($plugin) {
1519 // Delete from the obvious config_plugins first.
1520 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1521 // Next delete any suspect settings from config.
1522 $like = $DB->sql_like('name', '?', true, true, false, '|');
1523 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1524 $DB->delete_records_select('config', $like, $params);
1525 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1526 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1532 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1534 * All users are verified if they still have the necessary capability.
1536 * @param string $value the value of the config setting.
1537 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1538 * @param bool $includeadmins include administrators.
1539 * @return array of user objects.
1541 function get_users_from_config($value, $capability, $includeadmins = true) {
1542 if (empty($value) or $value === '$@NONE@$') {
1546 // We have to make sure that users still have the necessary capability,
1547 // it should be faster to fetch them all first and then test if they are present
1548 // instead of validating them one-by-one.
1549 $users = get_users_by_capability(context_system::instance(), $capability);
1550 if ($includeadmins) {
1551 $admins = get_admins();
1552 foreach ($admins as $admin) {
1553 $users[$admin->id] = $admin;
1557 if ($value === '$@ALL@$') {
1561 $result = array(); // Result in correct order.
1562 $allowed = explode(',', $value);
1563 foreach ($allowed as $uid) {
1564 if (isset($users[$uid])) {
1565 $user = $users[$uid];
1566 $result[$user->id] = $user;
1575 * Invalidates browser caches and cached data in temp.
1577 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1578 * {@link phpunit_util::reset_dataroot()}
1582 function purge_all_caches() {
1585 reset_text_filters_cache();
1586 js_reset_all_caches();
1587 theme_reset_all_caches();
1588 get_string_manager()->reset_caches();
1589 core_text::reset_caches();
1591 cache_helper::purge_all();
1593 // Purge all other caches: rss, simplepie, etc.
1594 remove_dir($CFG->cachedir.'', true);
1596 // Make sure cache dir is writable, throws exception if not.
1597 make_cache_directory('');
1599 // This is the only place where we purge local caches, we are only adding files there.
1600 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1601 remove_dir($CFG->localcachedir, true);
1602 set_config('localcachedirpurged', time());
1603 make_localcache_directory('', true);
1607 * Get volatile flags
1609 * @param string $type
1610 * @param int $changedsince default null
1611 * @return array records array
1613 function get_cache_flags($type, $changedsince = null) {
1616 $params = array('type' => $type, 'expiry' => time());
1617 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1618 if ($changedsince !== null) {
1619 $params['changedsince'] = $changedsince;
1620 $sqlwhere .= " AND timemodified > :changedsince";
1623 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1624 foreach ($flags as $flag) {
1625 $cf[$flag->name] = $flag->value;
1632 * Get volatile flags
1634 * @param string $type
1635 * @param string $name
1636 * @param int $changedsince default null
1637 * @return string|false The cache flag value or false
1639 function get_cache_flag($type, $name, $changedsince=null) {
1642 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1644 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1645 if ($changedsince !== null) {
1646 $params['changedsince'] = $changedsince;
1647 $sqlwhere .= " AND timemodified > :changedsince";
1650 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1654 * Set a volatile flag
1656 * @param string $type the "type" namespace for the key
1657 * @param string $name the key to set
1658 * @param string $value the value to set (without magic quotes) - null will remove the flag
1659 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1660 * @return bool Always returns true
1662 function set_cache_flag($type, $name, $value, $expiry = null) {
1665 $timemodified = time();
1666 if ($expiry === null || $expiry < $timemodified) {
1667 $expiry = $timemodified + 24 * 60 * 60;
1669 $expiry = (int)$expiry;
1672 if ($value === null) {
1673 unset_cache_flag($type, $name);
1677 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1678 // This is a potential problem in DEBUG_DEVELOPER.
1679 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1680 return true; // No need to update.
1683 $f->expiry = $expiry;
1684 $f->timemodified = $timemodified;
1685 $DB->update_record('cache_flags', $f);
1687 $f = new stdClass();
1688 $f->flagtype = $type;
1691 $f->expiry = $expiry;
1692 $f->timemodified = $timemodified;
1693 $DB->insert_record('cache_flags', $f);
1699 * Removes a single volatile flag
1701 * @param string $type the "type" namespace for the key
1702 * @param string $name the key to set
1705 function unset_cache_flag($type, $name) {
1707 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1712 * Garbage-collect volatile flags
1714 * @return bool Always returns true
1716 function gc_cache_flags() {
1718 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1722 // USER PREFERENCE API.
1725 * Refresh user preference cache. This is used most often for $USER
1726 * object that is stored in session, but it also helps with performance in cron script.
1728 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1731 * @category preference
1733 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1734 * @param int $cachelifetime Cache life time on the current page (in seconds)
1735 * @throws coding_exception
1738 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1740 // Static cache, we need to check on each page load, not only every 2 minutes.
1741 static $loadedusers = array();
1743 if (!isset($user->id)) {
1744 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1747 if (empty($user->id) or isguestuser($user->id)) {
1748 // No permanent storage for not-logged-in users and guest.
1749 if (!isset($user->preference)) {
1750 $user->preference = array();
1757 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1758 // Already loaded at least once on this page. Are we up to date?
1759 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1760 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1763 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1764 // No change since the lastcheck on this page.
1765 $user->preference['_lastloaded'] = $timenow;
1770 // OK, so we have to reload all preferences.
1771 $loadedusers[$user->id] = true;
1772 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1773 $user->preference['_lastloaded'] = $timenow;
1777 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1779 * NOTE: internal function, do not call from other code.
1783 * @param integer $userid the user whose prefs were changed.
1785 function mark_user_preferences_changed($userid) {
1788 if (empty($userid) or isguestuser($userid)) {
1789 // No cache flags for guest and not-logged-in users.
1793 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1797 * Sets a preference for the specified user.
1799 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1802 * @category preference
1804 * @param string $name The key to set as preference for the specified user
1805 * @param string $value The value to set for the $name key in the specified user's
1806 * record, null means delete current value.
1807 * @param stdClass|int|null $user A moodle user object or id, null means current user
1808 * @throws coding_exception
1809 * @return bool Always true or exception
1811 function set_user_preference($name, $value, $user = null) {
1814 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1815 throw new coding_exception('Invalid preference name in set_user_preference() call');
1818 if (is_null($value)) {
1819 // Null means delete current.
1820 return unset_user_preference($name, $user);
1821 } else if (is_object($value)) {
1822 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1823 } else if (is_array($value)) {
1824 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1826 // Value column maximum length is 1333 characters.
1827 $value = (string)$value;
1828 if (core_text::strlen($value) > 1333) {
1829 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1832 if (is_null($user)) {
1834 } else if (isset($user->id)) {
1835 // It is a valid object.
1836 } else if (is_numeric($user)) {
1837 $user = (object)array('id' => (int)$user);
1839 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1842 check_user_preferences_loaded($user);
1844 if (empty($user->id) or isguestuser($user->id)) {
1845 // No permanent storage for not-logged-in users and guest.
1846 $user->preference[$name] = $value;
1850 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1851 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1852 // Preference already set to this value.
1855 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1858 $preference = new stdClass();
1859 $preference->userid = $user->id;
1860 $preference->name = $name;
1861 $preference->value = $value;
1862 $DB->insert_record('user_preferences', $preference);
1865 // Update value in cache.
1866 $user->preference[$name] = $value;
1868 // Set reload flag for other sessions.
1869 mark_user_preferences_changed($user->id);
1875 * Sets a whole array of preferences for the current user
1877 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1880 * @category preference
1882 * @param array $prefarray An array of key/value pairs to be set
1883 * @param stdClass|int|null $user A moodle user object or id, null means current user
1884 * @return bool Always true or exception
1886 function set_user_preferences(array $prefarray, $user = null) {
1887 foreach ($prefarray as $name => $value) {
1888 set_user_preference($name, $value, $user);
1894 * Unsets a preference completely by deleting it from the database
1896 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1899 * @category preference
1901 * @param string $name The key to unset as preference for the specified user
1902 * @param stdClass|int|null $user A moodle user object or id, null means current user
1903 * @throws coding_exception
1904 * @return bool Always true or exception
1906 function unset_user_preference($name, $user = null) {
1909 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1910 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1913 if (is_null($user)) {
1915 } else if (isset($user->id)) {
1916 // It is a valid object.
1917 } else if (is_numeric($user)) {
1918 $user = (object)array('id' => (int)$user);
1920 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1923 check_user_preferences_loaded($user);
1925 if (empty($user->id) or isguestuser($user->id)) {
1926 // No permanent storage for not-logged-in user and guest.
1927 unset($user->preference[$name]);
1932 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1934 // Delete the preference from cache.
1935 unset($user->preference[$name]);
1937 // Set reload flag for other sessions.
1938 mark_user_preferences_changed($user->id);
1944 * Used to fetch user preference(s)
1946 * If no arguments are supplied this function will return
1947 * all of the current user preferences as an array.
1949 * If a name is specified then this function
1950 * attempts to return that particular preference value. If
1951 * none is found, then the optional value $default is returned,
1954 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1957 * @category preference
1959 * @param string $name Name of the key to use in finding a preference value
1960 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1961 * @param stdClass|int|null $user A moodle user object or id, null means current user
1962 * @throws coding_exception
1963 * @return string|mixed|null A string containing the value of a single preference. An
1964 * array with all of the preferences or null
1966 function get_user_preferences($name = null, $default = null, $user = null) {
1969 if (is_null($name)) {
1971 } else if (is_numeric($name) or $name === '_lastloaded') {
1972 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1975 if (is_null($user)) {
1977 } else if (isset($user->id)) {
1978 // Is a valid object.
1979 } else if (is_numeric($user)) {
1980 $user = (object)array('id' => (int)$user);
1982 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1985 check_user_preferences_loaded($user);
1989 return $user->preference;
1990 } else if (isset($user->preference[$name])) {
1991 // The single string value.
1992 return $user->preference[$name];
1994 // Default value (null if not specified).
1999 // FUNCTIONS FOR HANDLING TIME.
2002 * Given date parts in user time produce a GMT timestamp.
2006 * @param int $year The year part to create timestamp of
2007 * @param int $month The month part to create timestamp of
2008 * @param int $day The day part to create timestamp of
2009 * @param int $hour The hour part to create timestamp of
2010 * @param int $minute The minute part to create timestamp of
2011 * @param int $second The second part to create timestamp of
2012 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2013 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2014 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2015 * applied only if timezone is 99 or string.
2016 * @return int GMT timestamp
2018 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2020 // Save input timezone, required for dst offset check.
2021 $passedtimezone = $timezone;
2023 $timezone = get_user_timezone_offset($timezone);
2025 if (abs($timezone) > 13) {
2027 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2029 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2030 $time = usertime($time, $timezone);
2032 // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
2033 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
2034 $time -= dst_offset_on($time, $passedtimezone);
2043 * Format a date/time (seconds) as weeks, days, hours etc as needed
2045 * Given an amount of time in seconds, returns string
2046 * formatted nicely as weeks, days, hours etc as needed
2054 * @param int $totalsecs Time in seconds
2055 * @param stdClass $str Should be a time object
2056 * @return string A nicely formatted date/time string
2058 function format_time($totalsecs, $str = null) {
2060 $totalsecs = abs($totalsecs);
2063 // Create the str structure the slow way.
2064 $str = new stdClass();
2065 $str->day = get_string('day');
2066 $str->days = get_string('days');
2067 $str->hour = get_string('hour');
2068 $str->hours = get_string('hours');
2069 $str->min = get_string('min');
2070 $str->mins = get_string('mins');
2071 $str->sec = get_string('sec');
2072 $str->secs = get_string('secs');
2073 $str->year = get_string('year');
2074 $str->years = get_string('years');
2077 $years = floor($totalsecs/YEARSECS);
2078 $remainder = $totalsecs - ($years*YEARSECS);
2079 $days = floor($remainder/DAYSECS);
2080 $remainder = $totalsecs - ($days*DAYSECS);
2081 $hours = floor($remainder/HOURSECS);
2082 $remainder = $remainder - ($hours*HOURSECS);
2083 $mins = floor($remainder/MINSECS);
2084 $secs = $remainder - ($mins*MINSECS);
2086 $ss = ($secs == 1) ? $str->sec : $str->secs;
2087 $sm = ($mins == 1) ? $str->min : $str->mins;
2088 $sh = ($hours == 1) ? $str->hour : $str->hours;
2089 $sd = ($days == 1) ? $str->day : $str->days;
2090 $sy = ($years == 1) ? $str->year : $str->years;
2099 $oyears = $years .' '. $sy;
2102 $odays = $days .' '. $sd;
2105 $ohours = $hours .' '. $sh;
2108 $omins = $mins .' '. $sm;
2111 $osecs = $secs .' '. $ss;
2115 return trim($oyears .' '. $odays);
2118 return trim($odays .' '. $ohours);
2121 return trim($ohours .' '. $omins);
2124 return trim($omins .' '. $osecs);
2129 return get_string('now');
2133 * Returns a formatted string that represents a date in user time
2135 * Returns a formatted string that represents a date in user time
2136 * <b>WARNING: note that the format is for strftime(), not date().</b>
2137 * Because of a bug in most Windows time libraries, we can't use
2138 * the nicer %e, so we have to use %d which has leading zeroes.
2139 * A lot of the fuss in the function is just getting rid of these leading
2140 * zeroes as efficiently as possible.
2142 * If parameter fixday = true (default), then take off leading
2143 * zero from %d, else maintain it.
2147 * @param int $date the timestamp in UTC, as obtained from the database.
2148 * @param string $format strftime format. You should probably get this using
2149 * get_string('strftime...', 'langconfig');
2150 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2151 * not 99 then daylight saving will not be added.
2152 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2153 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2154 * If false then the leading zero is maintained.
2155 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2156 * @return string the formatted date/time.
2158 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2162 if (empty($format)) {
2163 $format = get_string('strftimedaydatetime', 'langconfig');
2166 if (!empty($CFG->nofixday)) {
2167 // Config.php can force %d not to be fixed.
2169 } else if ($fixday) {
2170 $formatnoday = str_replace('%d', 'DD', $format);
2171 $fixday = ($formatnoday != $format);
2172 $format = $formatnoday;
2175 // Note: This logic about fixing 12-hour time to remove unnecessary leading
2176 // zero is required because on Windows, PHP strftime function does not
2177 // support the correct 'hour without leading zero' parameter (%l).
2178 if (!empty($CFG->nofixhour)) {
2179 // Config.php can force %I not to be fixed.
2181 } else if ($fixhour) {
2182 $formatnohour = str_replace('%I', 'HH', $format);
2183 $fixhour = ($formatnohour != $format);
2184 $format = $formatnohour;
2187 // Add daylight saving offset for string timezones only, as we can't get dst for
2188 // float values. if timezone is 99 (user default timezone), then try update dst.
2189 if ((99 == $timezone) || !is_numeric($timezone)) {
2190 $date += dst_offset_on($date, $timezone);
2193 $timezone = get_user_timezone_offset($timezone);
2195 // If we are running under Windows convert to windows encoding and then back to UTF-8
2196 // (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2198 if (abs($timezone) > 13) {
2200 $datestring = date_format_string($date, $format, $timezone);
2202 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
2203 $datestring = str_replace('DD', $daystring, $datestring);
2206 $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2207 $datestring = str_replace('HH', $hourstring, $datestring);
2211 $date += (int)($timezone * 3600);
2212 $datestring = date_format_string($date, $format, $timezone);
2214 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
2215 $datestring = str_replace('DD', $daystring, $datestring);
2218 $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2219 $datestring = str_replace('HH', $hourstring, $datestring);
2227 * Returns a formatted date ensuring it is UTF-8.
2229 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2230 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2232 * This function does not do any calculation regarding the user preferences and should
2233 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2234 * to differentiate the use of server time or not (strftime() against gmstrftime()).
2236 * @param int $date the timestamp.
2237 * @param string $format strftime format.
2238 * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2239 * @return string the formatted date/time.
2242 function date_format_string($date, $format, $tz = 99) {
2244 if (abs($tz) > 13) {
2245 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
2246 $format = core_text::convert($format, 'utf-8', $localewincharset);
2247 $datestring = strftime($format, $date);
2248 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2250 $datestring = strftime($format, $date);
2253 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
2254 $format = core_text::convert($format, 'utf-8', $localewincharset);
2255 $datestring = gmstrftime($format, $date);
2256 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2258 $datestring = gmstrftime($format, $date);
2265 * Given a $time timestamp in GMT (seconds since epoch),
2266 * returns an array that represents the date in user time
2271 * @param int $time Timestamp in GMT
2272 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2273 * dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
2274 * @return array An array that represents the date in user time
2276 function usergetdate($time, $timezone=99) {
2278 // Save input timezone, required for dst offset check.
2279 $passedtimezone = $timezone;
2281 $timezone = get_user_timezone_offset($timezone);
2283 if (abs($timezone) > 13) {
2285 return getdate($time);
2288 // Add daylight saving offset for string timezones only, as we can't get dst for
2289 // float values. if timezone is 99 (user default timezone), then try update dst.
2290 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2291 $time += dst_offset_on($time, $passedtimezone);
2294 $time += intval((float)$timezone * HOURSECS);
2296 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2298 // Be careful to ensure the returned array matches that produced by getdate() above.
2301 $getdate['weekday'],
2308 $getdate['minutes'],
2310 ) = explode('_', $datestring);
2312 // Set correct datatype to match with getdate().
2313 $getdate['seconds'] = (int)$getdate['seconds'];
2314 $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
2315 $getdate['year'] = (int)$getdate['year'];
2316 $getdate['mon'] = (int)$getdate['mon'];
2317 $getdate['wday'] = (int)$getdate['wday'];
2318 $getdate['mday'] = (int)$getdate['mday'];
2319 $getdate['hours'] = (int)$getdate['hours'];
2320 $getdate['minutes'] = (int)$getdate['minutes'];
2325 * Given a GMT timestamp (seconds since epoch), offsets it by
2326 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2331 * @param int $date Timestamp in GMT
2332 * @param float|int|string $timezone timezone to calculate GMT time offset before
2333 * calculating user time, 99 is default user timezone
2334 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2337 function usertime($date, $timezone=99) {
2339 $timezone = get_user_timezone_offset($timezone);
2341 if (abs($timezone) > 13) {
2344 return $date - (int)($timezone * HOURSECS);
2348 * Given a time, return the GMT timestamp of the most recent midnight
2349 * for the current user.
2353 * @param int $date Timestamp in GMT
2354 * @param float|int|string $timezone timezone to calculate GMT time offset before
2355 * calculating user midnight time, 99 is default user timezone
2356 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2357 * @return int Returns a GMT timestamp
2359 function usergetmidnight($date, $timezone=99) {
2361 $userdate = usergetdate($date, $timezone);
2363 // Time of midnight of this user's day, in GMT.
2364 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2369 * Returns a string that prints the user's timezone
2373 * @param float|int|string $timezone timezone to calculate GMT time offset before
2374 * calculating user timezone, 99 is default user timezone
2375 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2378 function usertimezone($timezone=99) {
2380 $tz = get_user_timezone($timezone);
2382 if (!is_float($tz)) {
2386 if (abs($tz) > 13) {
2388 return get_string('serverlocaltime');
2391 if ($tz == intval($tz)) {
2392 // Don't show .0 for whole hours.
2398 } else if ($tz > 0) {
2407 * Returns a float which represents the user's timezone difference from GMT in hours
2408 * Checks various settings and picks the most dominant of those which have a value
2412 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2413 * 99 is default user timezone
2414 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2417 function get_user_timezone_offset($tz = 99) {
2418 $tz = get_user_timezone($tz);
2420 if (is_float($tz)) {
2423 $tzrecord = get_timezone_record($tz);
2424 if (empty($tzrecord)) {
2427 return (float)$tzrecord->gmtoff / HOURMINS;
2432 * Returns an int which represents the systems's timezone difference from GMT in seconds
2436 * @param float|int|string $tz timezone for which offset is required.
2437 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2438 * @return int|bool if found, false is timezone 99 or error
2440 function get_timezone_offset($tz) {
2445 if (is_numeric($tz)) {
2446 return intval($tz * 60*60);
2449 if (!$tzrecord = get_timezone_record($tz)) {
2452 return intval($tzrecord->gmtoff * 60);
2456 * Returns a float or a string which denotes the user's timezone
2457 * 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)
2458 * means that for this timezone there are also DST rules to be taken into account
2459 * Checks various settings and picks the most dominant of those which have a value
2463 * @param float|int|string $tz timezone to calculate GMT time offset before
2464 * calculating user timezone, 99 is default user timezone
2465 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2466 * @return float|string
2468 function get_user_timezone($tz = 99) {
2473 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2474 isset($USER->timezone) ? $USER->timezone : 99,
2475 isset($CFG->timezone) ? $CFG->timezone : 99,
2480 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2481 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2482 $tz = $next['value'];
2484 return is_numeric($tz) ? (float) $tz : $tz;
2488 * Returns cached timezone record for given $timezonename
2491 * @param string $timezonename name of the timezone
2492 * @return stdClass|bool timezonerecord or false
2494 function get_timezone_record($timezonename) {
2496 static $cache = null;
2498 if ($cache === null) {
2502 if (isset($cache[$timezonename])) {
2503 return $cache[$timezonename];
2506 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2507 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2511 * Build and store the users Daylight Saving Time (DST) table
2514 * @param int $fromyear Start year for the table, defaults to 1971
2515 * @param int $toyear End year for the table, defaults to 2035
2516 * @param int|float|string $strtimezone timezone to check if dst should be applied.
2519 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2520 global $SESSION, $DB;
2522 $usertz = get_user_timezone($strtimezone);
2524 if (is_float($usertz)) {
2525 // Trivial timezone, no DST.
2529 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2530 // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
2531 unset($SESSION->dst_offsets);
2532 unset($SESSION->dst_range);
2535 if (!empty($SESSION->dst_offsets) && empty($fromyear) && empty($toyear)) {
2536 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
2537 // This will be the return path most of the time, pretty light computationally.
2541 // Reaching here means we either need to extend our table or create it from scratch.
2543 // Remember which TZ we calculated these changes for.
2544 $SESSION->dst_offsettz = $usertz;
2546 if (empty($SESSION->dst_offsets)) {
2547 // If we 're creating from scratch, put the two guard elements in there.
2548 $SESSION->dst_offsets = array(1 => null, 0 => null);
2550 if (empty($SESSION->dst_range)) {
2551 // If creating from scratch.
2552 $from = max((empty($fromyear) ? intval(date('Y')) - 3 : $fromyear), 1971);
2553 $to = min((empty($toyear) ? intval(date('Y')) + 3 : $toyear), 2035);
2555 // Fill in the array with the extra years we need to process.
2556 $yearstoprocess = array();
2557 for ($i = $from; $i <= $to; ++$i) {
2558 $yearstoprocess[] = $i;
2561 // Take note of which years we have processed for future calls.
2562 $SESSION->dst_range = array($from, $to);
2564 // If needing to extend the table, do the same.
2565 $yearstoprocess = array();
2567 $from = max((empty($fromyear) ? $SESSION->dst_range[0] : $fromyear), 1971);
2568 $to = min((empty($toyear) ? $SESSION->dst_range[1] : $toyear), 2035);
2570 if ($from < $SESSION->dst_range[0]) {
2571 // Take note of which years we need to process and then note that we have processed them for future calls.
2572 for ($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2573 $yearstoprocess[] = $i;
2575 $SESSION->dst_range[0] = $from;
2577 if ($to > $SESSION->dst_range[1]) {
2578 // Take note of which years we need to process and then note that we have processed them for future calls.
2579 for ($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2580 $yearstoprocess[] = $i;
2582 $SESSION->dst_range[1] = $to;
2586 if (empty($yearstoprocess)) {
2587 // This means that there was a call requesting a SMALLER range than we have already calculated.
2591 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2592 // Also, the array is sorted in descending timestamp order!
2596 static $presetscache = array();
2597 if (!isset($presetscache[$usertz])) {
2598 $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
2599 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
2600 'std_startday, std_weekday, std_skipweeks, std_time');
2602 if (empty($presetscache[$usertz])) {
2606 // Remove ending guard (first element of the array).
2607 reset($SESSION->dst_offsets);
2608 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2610 // Add all required change timestamps.
2611 foreach ($yearstoprocess as $y) {
2612 // Find the record which is in effect for the year $y.
2613 foreach ($presetscache[$usertz] as $year => $preset) {
2619 $changes = dst_changes_for_year($y, $preset);
2621 if ($changes === null) {
2624 if ($changes['dst'] != 0) {
2625 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2627 if ($changes['std'] != 0) {
2628 $SESSION->dst_offsets[$changes['std']] = 0;
2632 // Put in a guard element at the top.
2633 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2634 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = null; // DAYSECS is arbitrary, any "small" number will do.
2637 krsort($SESSION->dst_offsets);
2643 * Calculates the required DST change and returns a Timestamp Array
2649 * @param int|string $year Int or String Year to focus on
2650 * @param object $timezone Instatiated Timezone object
2651 * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
2653 function dst_changes_for_year($year, $timezone) {
2655 if ($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 &&
2656 $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2660 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2661 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2663 list($dsthour, $dstmin) = explode(':', $timezone->dst_time);
2664 list($stdhour, $stdmin) = explode(':', $timezone->std_time);
2666 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2667 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2669 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2670 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2671 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2673 $timedst += $dsthour * HOURSECS + $dstmin * MINSECS;
2674 $timestd += $stdhour * HOURSECS + $stdmin * MINSECS;
2676 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2680 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2681 * - Note: Daylight saving only works for string timezones and not for float.
2685 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2686 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2687 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2690 function dst_offset_on($time, $strtimezone = null) {
2693 if (!calculate_user_dst_table(null, null, $strtimezone) || empty($SESSION->dst_offsets)) {
2697 reset($SESSION->dst_offsets);
2698 while (list($from, $offset) = each($SESSION->dst_offsets)) {
2699 if ($from <= $time) {
2704 // This is the normal return path.
2705 if ($offset !== null) {
2709 // Reaching this point means we haven't calculated far enough, do it now:
2710 // Calculate extra DST changes if needed and recurse. The recursion always
2711 // moves toward the stopping condition, so will always end.
2714 // We need a year smaller than $SESSION->dst_range[0].
2715 if ($SESSION->dst_range[0] == 1971) {
2718 calculate_user_dst_table($SESSION->dst_range[0] - 5, null, $strtimezone);
2719 return dst_offset_on($time, $strtimezone);
2721 // We need a year larger than $SESSION->dst_range[1].
2722 if ($SESSION->dst_range[1] == 2035) {
2725 calculate_user_dst_table(null, $SESSION->dst_range[1] + 5, $strtimezone);
2726 return dst_offset_on($time, $strtimezone);
2731 * Calculates when the day appears in specific month
2735 * @param int $startday starting day of the month
2736 * @param int $weekday The day when week starts (normally taken from user preferences)
2737 * @param int $month The month whose day is sought
2738 * @param int $year The year of the month whose day is sought
2741 function find_day_in_month($startday, $weekday, $month, $year) {
2743 $daysinmonth = days_in_month($month, $year);
2745 if ($weekday == -1) {
2746 // Don't care about weekday, so return:
2747 // abs($startday) if $startday != -1
2748 // $daysinmonth otherwise.
2749 return ($startday == -1) ? $daysinmonth : abs($startday);
2752 // From now on we 're looking for a specific weekday.
2754 // Give "end of month" its actual value, since we know it.
2755 if ($startday == -1) {
2756 $startday = -1 * $daysinmonth;
2759 // Starting from day $startday, the sign is the direction.
2761 if ($startday < 1) {
2763 $startday = abs($startday);
2764 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2766 // This is the last such weekday of the month.
2767 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2768 if ($lastinmonth > $daysinmonth) {
2772 // Find the first such weekday <= $startday.
2773 while ($lastinmonth > $startday) {
2777 return $lastinmonth;
2781 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2783 $diff = $weekday - $indexweekday;
2788 // This is the first such weekday of the month equal to or after $startday.
2789 $firstfromindex = $startday + $diff;
2791 return $firstfromindex;
2797 * Calculate the number of days in a given month
2801 * @param int $month The month whose day count is sought
2802 * @param int $year The year of the month whose day count is sought
2805 function days_in_month($month, $year) {
2806 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2810 * Calculate the position in the week of a specific calendar day
2814 * @param int $day The day of the date whose position in the week is sought
2815 * @param int $month The month of the date whose position in the week is sought
2816 * @param int $year The year of the date whose position in the week is sought
2819 function dayofweek($day, $month, $year) {
2820 // I wonder if this is any different from strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));.
2821 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2824 // USER AUTHENTICATION AND LOGIN.
2827 * Returns full login url.
2829 * @return string login url
2831 function get_login_url() {
2834 $url = "$CFG->wwwroot/login/index.php";
2836 if (!empty($CFG->loginhttps)) {
2837 $url = str_replace('http:', 'https:', $url);
2844 * This function checks that the current user is logged in and has the
2845 * required privileges
2847 * This function checks that the current user is logged in, and optionally
2848 * whether they are allowed to be in a particular course and view a particular
2850 * If they are not logged in, then it redirects them to the site login unless
2851 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2852 * case they are automatically logged in as guests.
2853 * If $courseid is given and the user is not enrolled in that course then the
2854 * user is redirected to the course enrolment page.
2855 * If $cm is given and the course module is hidden and the user is not a teacher
2856 * in the course then the user is redirected to the course home page.
2858 * When $cm parameter specified, this function sets page layout to 'module'.
2859 * You need to change it manually later if some other layout needed.
2861 * @package core_access
2864 * @param mixed $courseorid id of the course or course object
2865 * @param bool $autologinguest default true
2866 * @param object $cm course module object
2867 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2868 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2869 * in order to keep redirects working properly. MDL-14495
2870 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2871 * @return mixed Void, exit, and die depending on path
2872 * @throws coding_exception
2873 * @throws require_login_exception
2875 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2876 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2878 // Must not redirect when byteserving already started.
2879 if (!empty($_SERVER['HTTP_RANGE'])) {
2880 $preventredirect = true;
2883 // Setup global $COURSE, themes, language and locale.
2884 if (!empty($courseorid)) {
2885 if (is_object($courseorid)) {
2886 $course = $courseorid;
2887 } else if ($courseorid == SITEID) {
2888 $course = clone($SITE);
2890 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2893 if ($cm->course != $course->id) {
2894 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2896 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2897 if (!($cm instanceof cm_info)) {
2898 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2899 // db queries so this is not really a performance concern, however it is obviously
2900 // better if you use get_fast_modinfo to get the cm before calling this.
2901 $modinfo = get_fast_modinfo($course);
2902 $cm = $modinfo->get_cm($cm->id);
2904 $PAGE->set_cm($cm, $course); // Set's up global $COURSE.
2905 $PAGE->set_pagelayout('incourse');
2907 $PAGE->set_course($course); // Set's up global $COURSE.
2910 // Do not touch global $COURSE via $PAGE->set_course(),
2911 // the reasons is we need to be able to call require_login() at any time!!
2914 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2918 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2919 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2920 // risk leading the user back to the AJAX request URL.
2921 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2922 $setwantsurltome = false;
2925 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2926 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2927 if ($setwantsurltome) {
2928 $SESSION->wantsurl = qualified_me();
2930 redirect(get_login_url());
2933 // If the user is not even logged in yet then make sure they are.
2934 if (!isloggedin()) {
2935 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2936 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2937 // Misconfigured site guest, just redirect to login page.
2938 redirect(get_login_url());
2939 exit; // Never reached.
2941 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2942 complete_user_login($guest);
2943 $USER->autologinguest = true;
2944 $SESSION->lang = $lang;
2946 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2947 if ($preventredirect) {
2948 throw new require_login_exception('You are not logged in');
2951 if ($setwantsurltome) {
2952 $SESSION->wantsurl = qualified_me();
2954 if (!empty($_SERVER['HTTP_REFERER'])) {
2955 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2957 redirect(get_login_url());
2958 exit; // Never reached.
2962 // Loginas as redirection if needed.
2963 if ($course->id != SITEID and session_is_loggedinas()) {
2964 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2965 if ($USER->loginascontext->instanceid != $course->id) {
2966 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2971 // Check whether the user should be changing password (but only if it is REALLY them).
2972 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2973 $userauth = get_auth_plugin($USER->auth);
2974 if ($userauth->can_change_password() and !$preventredirect) {
2975 if ($setwantsurltome) {
2976 $SESSION->wantsurl = qualified_me();
2978 if ($changeurl = $userauth->change_password_url()) {
2979 // Use plugin custom url.
2980 redirect($changeurl);
2982 // Use moodle internal method.
2983 if (empty($CFG->loginhttps)) {
2984 redirect($CFG->wwwroot .'/login/change_password.php');
2986 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2987 redirect($wwwroot .'/login/change_password.php');
2991 print_error('nopasswordchangeforced', 'auth');
2995 // Check that the user account is properly set up.
2996 if (user_not_fully_set_up($USER)) {
2997 if ($preventredirect) {
2998 throw new require_login_exception('User not fully set-up');
3000 if ($setwantsurltome) {
3001 $SESSION->wantsurl = qualified_me();
3003 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
3006 // Make sure the USER has a sesskey set up. Used for CSRF protection.
3009 // Do not bother admins with any formalities.
3010 if (is_siteadmin()) {
3011 // Set accesstime or the user will appear offline which messes up messaging.
3012 user_accesstime_log($course->id);
3016 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
3017 if (!$USER->policyagreed and !is_siteadmin()) {
3018 if (!empty($CFG->sitepolicy) and !isguestuser()) {
3019 if ($preventredirect) {
3020 throw new require_login_exception('Policy not agreed');
3022 if ($setwantsurltome) {
3023 $SESSION->wantsurl = qualified_me();
3025 redirect($CFG->wwwroot .'/user/policy.php');
3026 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
3027 if ($preventredirect) {
3028 throw new require_login_exception('Policy not agreed');
3030 if ($setwantsurltome) {
3031 $SESSION->wantsurl = qualified_me();
3033 redirect($CFG->wwwroot .'/user/policy.php');
3037 // Fetch the system context, the course context, and prefetch its child contexts.
3038 $sysctx = context_system::instance();
3039 $coursecontext = context_course::instance($course->id, MUST_EXIST);
3041 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
3046 // If the site is currently under maintenance, then print a message.
3047 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
3048 if ($preventredirect) {
3049 throw new require_login_exception('Maintenance in progress');
3052 print_maintenance_message();
3055 // Make sure the course itself is not hidden.
3056 if ($course->id == SITEID) {
3057 // Frontpage can not be hidden.
3059 if (is_role_switched($course->id)) {
3060 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3062 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3063 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3064 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3065 if ($preventredirect) {
3066 throw new require_login_exception('Course is hidden');
3068 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3069 // the navigation will mess up when trying to find it.
3070 navigation_node::override_active_url(new moodle_url('/'));
3071 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3076 // Is the user enrolled?
3077 if ($course->id == SITEID) {
3078 // Everybody is enrolled on the frontpage.
3080 if (session_is_loggedinas()) {
3081 // Make sure the REAL person can access this course first.
3082 $realuser = session_get_realuser();
3083 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
3084 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3085 if ($preventredirect) {
3086 throw new require_login_exception('Invalid course login-as access');
3088 echo $OUTPUT->header();
3089 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3095 if (is_role_switched($course->id)) {
3096 // Ok, user had to be inside this course before the switch.
3099 } else if (is_viewing($coursecontext, $USER)) {
3100 // Ok, no need to mess with enrol.
3104 if (isset($USER->enrol['enrolled'][$course->id])) {
3105 if ($USER->enrol['enrolled'][$course->id] > time()) {
3107 if (isset($USER->enrol['tempguest'][$course->id])) {
3108 unset($USER->enrol['tempguest'][$course->id]);
3109 remove_temp_course_roles($coursecontext);
3113 unset($USER->enrol['enrolled'][$course->id]);
3116 if (isset($USER->enrol['tempguest'][$course->id])) {
3117 if ($USER->enrol['tempguest'][$course->id] == 0) {
3119 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3123 unset($USER->enrol['tempguest'][$course->id]);
3124 remove_temp_course_roles($coursecontext);
3130 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3131 if ($until !== false) {
3132 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3134 $until = ENROL_MAX_TIMESTAMP;
3136 $USER->enrol['enrolled'][$course->id] = $until;
3140 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3141 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3142 $enrols = enrol_get_plugins(true);
3143 // First ask all enabled enrol instances in course if they want to auto enrol user.
3144 foreach ($instances as $instance) {
3145 if (!isset($enrols[$instance->enrol])) {
3148 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3149 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3150 if ($until !== false) {
3152 $until = ENROL_MAX_TIMESTAMP;
3154 $USER->enrol['enrolled'][$course->id] = $until;
3159 // If not enrolled yet try to gain temporary guest access.
3161 foreach ($instances as $instance) {
3162 if (!isset($enrols[$instance->enrol])) {
3165 // Get a duration for the guest access, a timestamp in the future or false.
3166 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3167 if ($until !== false and $until > time()) {
3168 $USER->enrol['tempguest'][$course->id] = $until;
3179 if ($preventredirect) {
3180 throw new require_login_exception('Not enrolled');
3182 if ($setwantsurltome) {
3183 $SESSION->wantsurl = qualified_me();
3185 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3189 // Check visibility of activity to current user; includes visible flag, groupmembersonly, conditional availability, etc.
3190 if ($cm && !$cm->uservisible) {
3191 if ($preventredirect) {
3192 throw new require_login_exception('Activity is hidden');
3194 if ($course->id != SITEID) {
3195 $url = new moodle_url('/course/view.php', array('id' => $course->id));
3197 $url = new moodle_url('/');
3199 redirect($url, get_string('activityiscurrentlyhidden'));
3202 // Finally access granted, update lastaccess times.
3203 user_accesstime_log($course->id);
3208 * This function just makes sure a user is logged out.
3210 * @package core_access
3213 function require_logout() {
3219 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
3221 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
3222 foreach ($authsequence as $authname) {
3223 $authplugin = get_auth_plugin($authname);
3224 $authplugin->prelogout_hook();
3228 events_trigger('user_logout', $params);
3229 session_get_instance()->terminate_current();
3234 * Weaker version of require_login()
3236 * This is a weaker version of {@link require_login()} which only requires login
3237 * when called from within a course rather than the site page, unless
3238 * the forcelogin option is turned on.
3239 * @see require_login()
3241 * @package core_access
3244 * @param mixed $courseorid The course object or id in question
3245 * @param bool $autologinguest Allow autologin guests if that is wanted
3246 * @param object $cm Course activity module if known
3247 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3248 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3249 * in order to keep redirects working properly. MDL-14495
3250 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3252 * @throws coding_exception
3254 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3255 global $CFG, $PAGE, $SITE;
3256 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3257 or (!is_object($courseorid) and $courseorid == SITEID);
3258 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3259 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3260 // db queries so this is not really a performance concern, however it is obviously
3261 // better if you use get_fast_modinfo to get the cm before calling this.
3262 if (is_object($courseorid)) {
3263 $course = $courseorid;
3265 $course = clone($SITE);
3267 $modinfo = get_fast_modinfo($course);
3268 $cm = $modinfo->get_cm($cm->id);
3270 if (!empty($CFG->forcelogin)) {
3271 // Login required for both SITE and courses.
3272 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3274 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3275 // Always login for hidden activities.
3276 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3278 } else if ($issite) {
3279 // Login for SITE not required.
3280 if ($cm and empty($cm->visible)) {
3281 // Hidden activities are not accessible without login.
3282 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3283 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3284 // Not-logged-in users do not have any group membership.
3285 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3287 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3288 if (!empty($courseorid)) {
3289 if (is_object($courseorid)) {
3290 $course = $courseorid;
3292 $course = clone($SITE);
3295 if ($cm->course != $course->id) {
3296 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3298 $PAGE->set_cm($cm, $course);
3299 $PAGE->set_pagelayout('incourse');
3301 $PAGE->set_course($course);
3304 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3305 $PAGE->set_course($PAGE->course);
3307 // TODO: verify conditional activities here.
3308 user_accesstime_log(SITEID);
3313 // Course login always required.
3314 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3319 * Require key login. Function terminates with error if key not found or incorrect.
3321 * @uses NO_MOODLE_COOKIES
3322 * @uses PARAM_ALPHANUM
3323 * @param string $script unique script identifier
3324 * @param int $instance optional instance id
3325 * @return int Instance ID
3327 function require_user_key_login($script, $instance=null) {
3330 if (!NO_MOODLE_COOKIES) {
3331 print_error('sessioncookiesdisable');
3335 @session_write_close();
3337 $keyvalue = required_param('key', PARAM_ALPHANUM);
3339 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3340 print_error('invalidkey');
3343 if (!empty($key->validuntil) and $key->validuntil < time()) {
3344 print_error('expiredkey');
3347 if ($key->iprestriction) {
3348 $remoteaddr = getremoteaddr(null);
3349 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3350 print_error('ipmismatch');
3354 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3355 print_error('invaliduserid');
3358 // Emulate normal session.
3359 enrol_check_plugins($user);
3360 session_set_user($user);
3362 // Note we are not using normal login.
3363 if (!defined('USER_KEY_LOGIN')) {
3364 define('USER_KEY_LOGIN', true);
3367 // Return instance id - it might be empty.
3368 return $key->instance;
3372 * Creates a new private user access key.
3374 * @param string $script unique target identifier
3375 * @param int $userid
3376 * @param int $instance optional instance id
3377 * @param string $iprestriction optional ip restricted access
3378 * @param timestamp $validuntil key valid only until given data
3379 * @return string access key value
3381 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3384 $key = new stdClass();
3385 $key->script = $script;
3386 $key->userid = $userid;
3387 $key->instance = $instance;
3388 $key->iprestriction = $iprestriction;
3389 $key->validuntil = $validuntil;
3390 $key->timecreated = time();
3392 // Something long and unique.
3393 $key->value = md5($userid.'_'.time().random_string(40));
3394 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3396 $key->value = md5($userid.'_'.time().random_string(40));
3398 $DB->insert_record('user_private_key', $key);
3403 * Delete the user's new private user access keys for a particular script.
3405 * @param string $script unique target identifier
3406 * @param int $userid
3409 function delete_user_key($script, $userid) {
3411 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3415 * Gets a private user access key (and creates one if one doesn't exist).
3417 * @param string $script unique target identifier
3418 * @param int $userid
3419 * @param int $instance optional instance id
3420 * @param string $iprestriction optional ip restricted access
3421 * @param timestamp $validuntil key valid only until given data
3422 * @return string access key value
3424 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3427 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3428 'instance' => $instance, 'iprestriction' => $iprestriction,
3429 'validuntil' => $validuntil))) {
3432 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3438 * Modify the user table by setting the currently logged in user's last login to now.
3440 * @return bool Always returns true
3442 function update_user_login_times() {
3445 if (isguestuser()) {
3446 // Do not update guest access times/ips for performance.
3452 $user = new stdClass();
3453 $user->id = $USER->id;
3455 // Make sure all users that logged in have some firstaccess.
3456 if ($USER->firstaccess == 0) {
3457 $USER->firstaccess = $user->firstaccess = $now;
3460 // Store the previous current as lastlogin.
3461 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3463 $USER->currentlogin = $user->currentlogin = $now;
3465 // Function user_accesstime_log() may not update immediately, better do it here.
3466 $USER->lastaccess = $user->lastaccess = $now;
3467 $USER->lastip = $user->lastip = getremoteaddr();
3469 $DB->update_record('user', $user);
3474 * Determines if a user has completed setting up their account.
3476 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3479 function user_not_fully_set_up($user) {
3480 if (isguestuser($user)) {
3483 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3487 * Check whether the user has exceeded the bounce threshold
3489 * @param stdClass $user A {@link $USER} object
3490 * @return bool true => User has exceeded bounce threshold
3492 function over_bounce_threshold($user) {
3495 if (empty($CFG->handlebounces)) {
3499 if (empty($user->id)) {
3500 // No real (DB) user, nothing to do here.
3504 // Set sensible defaults.
3505 if (empty($CFG->minbounces)) {
3506 $CFG->minbounces = 10;
3508 if (empty($CFG->bounceratio)) {
3509 $CFG->bounceratio = .20;
3513 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3514 $bouncecount = $bounce->value;
3516 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3517 $sendcount = $send->value;
3519 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3523 * Used to increment or reset email sent count
3525 * @param stdClass $user object containing an id
3526 * @param bool $reset will reset the count to 0
3529 function set_send_count($user, $reset=false) {
3532 if (empty($user->id)) {
3533 // No real (DB) user, nothing to do here.
3537 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3538 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3539 $DB->update_record('user_preferences', $pref);
3540 } else if (!empty($reset)) {
3541 // If it's not there and we're resetting, don't bother. Make a new one.
3542 $pref = new stdClass();
3543 $pref->name = 'email_send_count';
3545 $pref->userid = $user->id;
3546 $DB->insert_record('user_preferences', $pref, false);
3551 * Increment or reset user's email bounce count
3553 * @param stdClass $user object containing an id
3554 * @param bool $reset will reset the count to 0
3556 function set_bounce_count($user, $reset=false) {
3559 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3560 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3561 $DB->update_record('user_preferences', $pref);
3562 } else if (!empty($reset)) {
3563 // If it's not there and we're resetting, don't bother. Make a new one.
3564 $pref = new stdClass();
3565 $pref->name = 'email_bounce_count';
3567 $pref->userid = $user->id;
3568 $DB->insert_record('user_preferences', $pref, false);
3573 * Determines if the logged in user is currently moving an activity
3575 * @param int $courseid The id of the course being tested
3578 function ismoving($courseid) {
3581 if (!empty($USER->activitycopy)) {
3582 return ($USER->activitycopycourse == $courseid);
3588 * Returns a persons full name
3590 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3591 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3594 * @param stdClass $user A {@link $USER} object to get full name of.
3595 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3598 function fullname($user, $override=false) {
3599 global $CFG, $SESSION;
3601 if (!isset($user->firstname) and !isset($user->lastname)) {
3606 if (!empty($CFG->forcefirstname)) {
3607 $user->firstname = $CFG->forcefirstname;
3609 if (!empty($CFG->forcelastname)) {
3610 $user->lastname = $CFG->forcelastname;
3614 if (!empty($SESSION->fullnamedisplay)) {
3615 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3619 // If the fullnamedisplay setting is available, set the template to that.
3620 if (isset($CFG->fullnamedisplay)) {
3621 $template = $CFG->fullnamedisplay;
3623 // If the template is empty, or set to language, or $override is set, return the language string.
3624 if (empty($template) || $template == 'language' || $override) {
3625 return get_string('fullnamedisplay', null, $user);
3628 // Get all of the name fields.
3629 $allnames = get_all_user_name_fields();
3630 $requirednames = array();
3631 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3632 foreach ($allnames as $allname) {
3633 if (strpos($template, $allname) !== false) {
3634 $requirednames[] = $allname;
3635 // If the field is in the template but not set in the user object then notify the programmer that it needs to be fixed.
3636 if (!array_key_exists($allname, $user)) {
3637 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3642 $displayname = $template;
3643 // Switch in the actual data into the template.
3644 foreach ($requirednames as $altname) {
3645 if (isset($user->$altname)) {
3646 // Using empty() on the below if statement causes breakages.
3647 if ((string)$user->$altname == '') {
3648 $displayname = str_replace($altname, 'EMPTY', $displayname);
3650 $displayname = str_replace($altname, $user->$altname, $displayname);
3653 $displayname = str_replace($altname, 'EMPTY', $displayname);
3656 // Tidy up any misc. characters (Not perfect, but gets most characters).