2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
35 /// Date and time constants ///
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 /// Parameter constants - every call to optional_param(), required_param() ///
72 /// or clean_param() should have a specified type of parameter. //////////////
77 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
79 define('PARAM_ALPHA', 'alpha');
82 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
83 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
85 define('PARAM_ALPHAEXT', 'alphaext');
88 * PARAM_ALPHANUM - expected numbers and letters only.
90 define('PARAM_ALPHANUM', 'alphanum');
93 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
95 define('PARAM_ALPHANUMEXT', 'alphanumext');
98 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
100 define('PARAM_AUTH', 'auth');
103 * PARAM_BASE64 - Base 64 encoded format
105 define('PARAM_BASE64', 'base64');
108 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
110 define('PARAM_BOOL', 'bool');
113 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
114 * checked against the list of capabilities in the database.
116 define('PARAM_CAPABILITY', 'capability');
119 * PARAM_CLEANHTML - cleans submitted HTML code. use only for text in HTML format. This cleaning may fix xhtml strictness too.
121 define('PARAM_CLEANHTML', 'cleanhtml');
124 * PARAM_EMAIL - an email address following the RFC
126 define('PARAM_EMAIL', 'email');
129 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
131 define('PARAM_FILE', 'file');
134 * PARAM_FLOAT - a real/floating point number.
136 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
137 * It does not work for languages that use , as a decimal separator.
138 * Instead, do something like
139 * $rawvalue = required_param('name', PARAM_RAW);
140 * // ... other code including require_login, which sets current lang ...
141 * $realvalue = unformat_float($rawvalue);
142 * // ... then use $realvalue
144 define('PARAM_FLOAT', 'float');
147 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
149 define('PARAM_HOST', 'host');
152 * PARAM_INT - integers only, use when expecting only numbers.
154 define('PARAM_INT', 'int');
157 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
159 define('PARAM_LANG', 'lang');
162 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
164 define('PARAM_LOCALURL', 'localurl');
167 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
169 define('PARAM_NOTAGS', 'notags');
172 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
173 * note: the leading slash is not removed, window drive letter is not allowed
175 define('PARAM_PATH', 'path');
178 * PARAM_PEM - Privacy Enhanced Mail format
180 define('PARAM_PEM', 'pem');
183 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
185 define('PARAM_PERMISSION', 'permission');
188 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
190 define('PARAM_RAW', 'raw');
193 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
195 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
198 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
200 define('PARAM_SAFEDIR', 'safedir');
203 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
205 define('PARAM_SAFEPATH', 'safepath');
208 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
210 define('PARAM_SEQUENCE', 'sequence');
213 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
215 define('PARAM_TAG', 'tag');
218 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
220 define('PARAM_TAGLIST', 'taglist');
223 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
225 define('PARAM_TEXT', 'text');
228 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
230 define('PARAM_THEME', 'theme');
233 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
235 define('PARAM_URL', 'url');
238 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user accounts, do NOT use when syncing with external systems!!
240 define('PARAM_USERNAME', 'username');
243 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
245 define('PARAM_STRINGID', 'stringid');
247 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
249 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
250 * It was one of the first types, that is why it is abused so much ;-)
251 * @deprecated since 2.0
253 define('PARAM_CLEAN', 'clean');
256 * PARAM_INTEGER - deprecated alias for PARAM_INT
258 define('PARAM_INTEGER', 'int');
261 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
263 define('PARAM_NUMBER', 'float');
266 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
267 * NOTE: originally alias for PARAM_APLHA
269 define('PARAM_ACTION', 'alphanumext');
272 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
273 * NOTE: originally alias for PARAM_APLHA
275 define('PARAM_FORMAT', 'alphanumext');
278 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
280 define('PARAM_MULTILANG', 'text');
283 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
284 * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
285 * America/Port-au-Prince)
287 define('PARAM_TIMEZONE', 'timezone');
290 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
292 define('PARAM_CLEANFILE', 'file');
295 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
296 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
297 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
298 * NOTE: numbers and underscores are strongly discouraged in plugin names!
300 define('PARAM_COMPONENT', 'component');
303 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
304 * It is usually used together with context id and component.
305 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
307 define('PARAM_AREA', 'area');
310 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
311 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
312 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
314 define('PARAM_PLUGIN', 'plugin');
320 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
322 define('VALUE_REQUIRED', 1);
325 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
327 define('VALUE_OPTIONAL', 2);
330 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
332 define('VALUE_DEFAULT', 0);
335 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
337 define('NULL_NOT_ALLOWED', false);
340 * NULL_ALLOWED - the parameter can be set to null in the database
342 define('NULL_ALLOWED', true);
346 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
348 define('PAGE_COURSE_VIEW', 'course-view');
350 /** Get remote addr constant */
351 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
352 /** Get remote addr constant */
353 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
355 /// Blog access level constant declaration ///
356 define ('BLOG_USER_LEVEL', 1);
357 define ('BLOG_GROUP_LEVEL', 2);
358 define ('BLOG_COURSE_LEVEL', 3);
359 define ('BLOG_SITE_LEVEL', 4);
360 define ('BLOG_GLOBAL_LEVEL', 5);
365 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
366 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
367 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
369 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
371 define('TAG_MAX_LENGTH', 50);
373 /// Password policy constants ///
374 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
375 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
376 define ('PASSWORD_DIGITS', '0123456789');
377 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
379 /// Feature constants ///
380 // Used for plugin_supports() to report features that are, or are not, supported by a module.
382 /** True if module can provide a grade */
383 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
384 /** True if module supports outcomes */
385 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
386 /** True if module supports advanced grading methods */
387 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
388 /** True if module controls the grade visibility over the gradebook */
389 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
391 /** True if module has code to track whether somebody viewed it */
392 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
393 /** True if module has custom completion rules */
394 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
396 /** True if module has no 'view' page (like label) */
397 define('FEATURE_NO_VIEW_LINK', 'viewlink');
398 /** True if module supports outcomes */
399 define('FEATURE_IDNUMBER', 'idnumber');
400 /** True if module supports groups */
401 define('FEATURE_GROUPS', 'groups');
402 /** True if module supports groupings */
403 define('FEATURE_GROUPINGS', 'groupings');
404 /** True if module supports groupmembersonly */
405 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
407 /** Type of module */
408 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
409 /** True if module supports intro editor */
410 define('FEATURE_MOD_INTRO', 'mod_intro');
411 /** True if module has default completion */
412 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
414 define('FEATURE_COMMENT', 'comment');
416 define('FEATURE_RATE', 'rate');
417 /** True if module supports backup/restore of moodle2 format */
418 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
420 /** True if module can show description on course main page */
421 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
423 /** Unspecified module archetype */
424 define('MOD_ARCHETYPE_OTHER', 0);
425 /** Resource-like type module */
426 define('MOD_ARCHETYPE_RESOURCE', 1);
427 /** Assignment module archetype */
428 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
429 /** System (not user-addable) module archetype */
430 define('MOD_ARCHETYPE_SYSTEM', 3);
433 * Security token used for allowing access
434 * from external application such as web services.
435 * Scripts do not use any session, performance is relatively
436 * low because we need to load access info in each request.
437 * Scripts are executed in parallel.
439 define('EXTERNAL_TOKEN_PERMANENT', 0);
442 * Security token used for allowing access
443 * of embedded applications, the code is executed in the
444 * active user session. Token is invalidated after user logs out.
445 * Scripts are executed serially - normal session locking is used.
447 define('EXTERNAL_TOKEN_EMBEDDED', 1);
450 * The home page should be the site home
452 define('HOMEPAGE_SITE', 0);
454 * The home page should be the users my page
456 define('HOMEPAGE_MY', 1);
458 * The home page can be chosen by the user
460 define('HOMEPAGE_USER', 2);
463 * Hub directory url (should be moodle.org)
465 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
469 * Moodle.org url (should be moodle.org)
471 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
474 * Moodle mobile app service name
476 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
479 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
481 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
484 * Course display settings
486 define('COURSE_DISPLAY_SINGLEPAGE', 0); // display all sections on one page
487 define('COURSE_DISPLAY_MULTIPAGE', 1); // split pages into a page per section
489 /// PARAMETER HANDLING ////////////////////////////////////////////////////
492 * Returns a particular value for the named variable, taken from
493 * POST or GET. If the parameter doesn't exist then an error is
494 * thrown because we require this variable.
496 * This function should be used to initialise all required values
497 * in a script that are based on parameters. Usually it will be
499 * $id = required_param('id', PARAM_INT);
501 * Please note the $type parameter is now required and the value can not be array.
503 * @param string $parname the name of the page parameter we want
504 * @param string $type expected type of parameter
507 function required_param($parname, $type) {
508 if (func_num_args() != 2 or empty($parname) or empty($type)) {
509 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
511 if (isset($_POST[$parname])) { // POST has precedence
512 $param = $_POST[$parname];
513 } else if (isset($_GET[$parname])) {
514 $param = $_GET[$parname];
516 print_error('missingparam', '', '', $parname);
519 if (is_array($param)) {
520 debugging('Invalid array parameter detected in required_param(): '.$parname);
521 // TODO: switch to fatal error in Moodle 2.3
522 //print_error('missingparam', '', '', $parname);
523 return required_param_array($parname, $type);
526 return clean_param($param, $type);
530 * Returns a particular array value for the named variable, taken from
531 * POST or GET. If the parameter doesn't exist then an error is
532 * thrown because we require this variable.
534 * This function should be used to initialise all required values
535 * in a script that are based on parameters. Usually it will be
537 * $ids = required_param_array('ids', PARAM_INT);
539 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
541 * @param string $parname the name of the page parameter we want
542 * @param string $type expected type of parameter
545 function required_param_array($parname, $type) {
546 if (func_num_args() != 2 or empty($parname) or empty($type)) {
547 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
549 if (isset($_POST[$parname])) { // POST has precedence
550 $param = $_POST[$parname];
551 } else if (isset($_GET[$parname])) {
552 $param = $_GET[$parname];
554 print_error('missingparam', '', '', $parname);
556 if (!is_array($param)) {
557 print_error('missingparam', '', '', $parname);
561 foreach($param as $key=>$value) {
562 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
563 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
566 $result[$key] = clean_param($value, $type);
573 * Returns a particular value for the named variable, taken from
574 * POST or GET, otherwise returning a given default.
576 * This function should be used to initialise all optional values
577 * in a script that are based on parameters. Usually it will be
579 * $name = optional_param('name', 'Fred', PARAM_TEXT);
581 * Please note the $type parameter is now required and the value can not be array.
583 * @param string $parname the name of the page parameter we want
584 * @param mixed $default the default value to return if nothing is found
585 * @param string $type expected type of parameter
588 function optional_param($parname, $default, $type) {
589 if (func_num_args() != 3 or empty($parname) or empty($type)) {
590 throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
592 if (!isset($default)) {
596 if (isset($_POST[$parname])) { // POST has precedence
597 $param = $_POST[$parname];
598 } else if (isset($_GET[$parname])) {
599 $param = $_GET[$parname];
604 if (is_array($param)) {
605 debugging('Invalid array parameter detected in required_param(): '.$parname);
606 // TODO: switch to $default in Moodle 2.3
608 return optional_param_array($parname, $default, $type);
611 return clean_param($param, $type);
615 * Returns a particular array value for the named variable, taken from
616 * POST or GET, otherwise returning a given default.
618 * This function should be used to initialise all optional values
619 * in a script that are based on parameters. Usually it will be
621 * $ids = optional_param('id', array(), PARAM_INT);
623 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
625 * @param string $parname the name of the page parameter we want
626 * @param mixed $default the default value to return if nothing is found
627 * @param string $type expected type of parameter
630 function optional_param_array($parname, $default, $type) {
631 if (func_num_args() != 3 or empty($parname) or empty($type)) {
632 throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
635 if (isset($_POST[$parname])) { // POST has precedence
636 $param = $_POST[$parname];
637 } else if (isset($_GET[$parname])) {
638 $param = $_GET[$parname];
642 if (!is_array($param)) {
643 debugging('optional_param_array() expects array parameters only: '.$parname);
648 foreach($param as $key=>$value) {
649 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
650 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
653 $result[$key] = clean_param($value, $type);
660 * Strict validation of parameter values, the values are only converted
661 * to requested PHP type. Internally it is using clean_param, the values
662 * before and after cleaning must be equal - otherwise
663 * an invalid_parameter_exception is thrown.
664 * Objects and classes are not accepted.
666 * @param mixed $param
667 * @param string $type PARAM_ constant
668 * @param bool $allownull are nulls valid value?
669 * @param string $debuginfo optional debug information
670 * @return mixed the $param value converted to PHP type
671 * @throws invalid_parameter_exception if $param is not of given type
673 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
674 if (is_null($param)) {
675 if ($allownull == NULL_ALLOWED) {
678 throw new invalid_parameter_exception($debuginfo);
681 if (is_array($param) or is_object($param)) {
682 throw new invalid_parameter_exception($debuginfo);
685 $cleaned = clean_param($param, $type);
687 if ($type == PARAM_FLOAT) {
688 // Do not detect precision loss here.
689 if (is_float($param) or is_int($param)) {
691 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
692 throw new invalid_parameter_exception($debuginfo);
694 } else if ((string)$param !== (string)$cleaned) {
695 // conversion to string is usually lossless
696 throw new invalid_parameter_exception($debuginfo);
703 * Makes sure array contains only the allowed types,
704 * this function does not validate array key names!
706 * $options = clean_param($options, PARAM_INT);
709 * @param array $param the variable array we are cleaning
710 * @param string $type expected format of param after cleaning.
711 * @param bool $recursive clean recursive arrays
714 function clean_param_array(array $param = null, $type, $recursive = false) {
715 $param = (array)$param; // convert null to empty array
716 foreach ($param as $key => $value) {
717 if (is_array($value)) {
719 $param[$key] = clean_param_array($value, $type, true);
721 throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
724 $param[$key] = clean_param($value, $type);
731 * Used by {@link optional_param()} and {@link required_param()} to
732 * clean the variables and/or cast to specific types, based on
735 * $course->format = clean_param($course->format, PARAM_ALPHA);
736 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
739 * @param mixed $param the variable we are cleaning
740 * @param string $type expected format of param after cleaning.
743 function clean_param($param, $type) {
747 if (is_array($param)) {
748 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
749 } else if (is_object($param)) {
750 if (method_exists($param, '__toString')) {
751 $param = $param->__toString();
753 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
758 case PARAM_RAW: // no cleaning at all
759 $param = fix_utf8($param);
762 case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
763 $param = fix_utf8($param);
766 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
767 // this is deprecated!, please use more specific type instead
768 if (is_numeric($param)) {
771 $param = fix_utf8($param);
772 return clean_text($param); // Sweep for scripts, etc
774 case PARAM_CLEANHTML: // clean html fragment
775 $param = fix_utf8($param);
776 $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
780 return (int)$param; // Convert to integer
784 return (float)$param; // Convert to float
786 case PARAM_ALPHA: // Remove everything not a-z
787 return preg_replace('/[^a-zA-Z]/i', '', $param);
789 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
790 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
792 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
793 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
795 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
796 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
798 case PARAM_SEQUENCE: // Remove everything not 0-9,
799 return preg_replace('/[^0-9,]/i', '', $param);
801 case PARAM_BOOL: // Convert to 1 or 0
802 $tempstr = strtolower($param);
803 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
805 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
808 $param = empty($param) ? 0 : 1;
812 case PARAM_NOTAGS: // Strip all tags
813 $param = fix_utf8($param);
814 return strip_tags($param);
816 case PARAM_TEXT: // leave only tags needed for multilang
817 $param = fix_utf8($param);
818 // if the multilang syntax is not correct we strip all tags
819 // because it would break xhtml strict which is required for accessibility standards
820 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
822 if (strpos($param, '</lang>') !== false) {
823 // old and future mutilang syntax
824 $param = strip_tags($param, '<lang>');
825 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
829 foreach ($matches[0] as $match) {
830 if ($match === '</lang>') {
838 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
849 } else if (strpos($param, '</span>') !== false) {
850 // current problematic multilang syntax
851 $param = strip_tags($param, '<span>');
852 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
856 foreach ($matches[0] as $match) {
857 if ($match === '</span>') {
865 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
877 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
878 return strip_tags($param);
880 case PARAM_COMPONENT:
881 // we do not want any guessing here, either the name is correct or not
882 // please note only normalised component names are accepted
883 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
886 if (strpos($param, '__') !== false) {
889 if (strpos($param, 'mod_') === 0) {
890 // module names must not contain underscores because we need to differentiate them from invalid plugin types
891 if (substr_count($param, '_') != 1) {
899 // we do not want any guessing here, either the name is correct or not
900 if (!preg_match('/^[a-z][a-z0-9_]*[a-z0-9]$/', $param)) {
903 if (strpos($param, '__') !== false) {
908 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
909 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
911 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
912 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
914 case PARAM_FILE: // Strip all suspicious characters from filename
915 $param = fix_utf8($param);
916 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
917 $param = preg_replace('~\.\.+~', '', $param);
918 if ($param === '.') {
923 case PARAM_PATH: // Strip all suspicious characters from file path
924 $param = fix_utf8($param);
925 $param = str_replace('\\', '/', $param);
926 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
927 $param = preg_replace('~\.\.+~', '', $param);
928 $param = preg_replace('~//+~', '/', $param);
929 return preg_replace('~/(\./)+~', '/', $param);
931 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
932 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
933 // match ipv4 dotted quad
934 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
935 // confirm values are ok
939 || $match[4] > 255 ) {
940 // hmmm, what kind of dotted quad is this?
943 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
944 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
945 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
947 // all is ok - $param is respected
954 case PARAM_URL: // allow safe ftp, http, mailto urls
955 $param = fix_utf8($param);
956 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
957 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
958 // all is ok, param is respected
960 $param =''; // not really ok
964 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
965 $param = clean_param($param, PARAM_URL);
966 if (!empty($param)) {
967 if (preg_match(':^/:', $param)) {
968 // root-relative, ok!
969 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
970 // absolute, and matches our wwwroot
972 // relative - let's make sure there are no tricks
973 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
983 $param = trim($param);
984 // PEM formatted strings may contain letters/numbers and the symbols
988 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
989 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
990 list($wholething, $body) = $matches;
991 unset($wholething, $matches);
992 $b64 = clean_param($body, PARAM_BASE64);
994 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1002 if (!empty($param)) {
1003 // PEM formatted strings may contain letters/numbers and the symbols
1007 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1010 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1011 // Each line of base64 encoded data must be 64 characters in
1012 // length, except for the last line which may be less than (or
1013 // equal to) 64 characters long.
1014 for ($i=0, $j=count($lines); $i < $j; $i++) {
1016 if (64 < strlen($lines[$i])) {
1022 if (64 != strlen($lines[$i])) {
1026 return implode("\n",$lines);
1032 $param = fix_utf8($param);
1033 // Please note it is not safe to use the tag name directly anywhere,
1034 // it must be processed with s(), urlencode() before embedding anywhere.
1035 // remove some nasties
1036 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1037 //convert many whitespace chars into one
1038 $param = preg_replace('/\s+/', ' ', $param);
1039 $param = textlib::substr(trim($param), 0, TAG_MAX_LENGTH);
1043 $param = fix_utf8($param);
1044 $tags = explode(',', $param);
1046 foreach ($tags as $tag) {
1047 $res = clean_param($tag, PARAM_TAG);
1053 return implode(',', $result);
1058 case PARAM_CAPABILITY:
1059 if (get_capability_info($param)) {
1065 case PARAM_PERMISSION:
1066 $param = (int)$param;
1067 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1074 $param = clean_param($param, PARAM_PLUGIN);
1075 if (empty($param)) {
1077 } else if (exists_auth_plugin($param)) {
1084 $param = clean_param($param, PARAM_SAFEDIR);
1085 if (get_string_manager()->translation_exists($param)) {
1088 return ''; // Specified language is not installed or param malformed
1092 $param = clean_param($param, PARAM_PLUGIN);
1093 if (empty($param)) {
1095 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1097 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1100 return ''; // Specified theme is not installed
1103 case PARAM_USERNAME:
1104 $param = fix_utf8($param);
1105 $param = str_replace(" " , "", $param);
1106 $param = textlib::strtolower($param); // Convert uppercase to lowercase MDL-16919
1107 if (empty($CFG->extendedusernamechars)) {
1108 // regular expression, eliminate all chars EXCEPT:
1109 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1110 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1115 $param = fix_utf8($param);
1116 if (validate_email($param)) {
1122 case PARAM_STRINGID:
1123 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1129 case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1130 $param = fix_utf8($param);
1131 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1132 if (preg_match($timezonepattern, $param)) {
1138 default: // throw error, switched parameters in optional_param or another serious problem
1139 print_error("unknownparamtype", '', '', $type);
1144 * Makes sure the data is using valid utf8, invalid characters are discarded.
1146 * Note: this function is not intended for full objects with methods and private properties.
1148 * @param mixed $value
1149 * @return mixed with proper utf-8 encoding
1151 function fix_utf8($value) {
1152 if (is_null($value) or $value === '') {
1155 } else if (is_string($value)) {
1156 if ((string)(int)$value === $value) {
1161 // Lower error reporting because glibc throws bogus notices.
1162 $olderror = error_reporting();
1163 if ($olderror & E_NOTICE) {
1164 error_reporting($olderror ^ E_NOTICE);
1167 // Note: this duplicates min_fix_utf8() intentionally.
1168 static $buggyiconv = null;
1169 if ($buggyiconv === null) {
1170 $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1174 if (function_exists('mb_convert_encoding')) {
1175 $subst = mb_substitute_character();
1176 mb_substitute_character('');
1177 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1178 mb_substitute_character($subst);
1181 // Warn admins on admin/index.php page.
1186 $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1189 if ($olderror & E_NOTICE) {
1190 error_reporting($olderror);
1195 } else if (is_array($value)) {
1196 foreach ($value as $k=>$v) {
1197 $value[$k] = fix_utf8($v);
1201 } else if (is_object($value)) {
1202 $value = clone($value); // do not modify original
1203 foreach ($value as $k=>$v) {
1204 $value->$k = fix_utf8($v);
1209 // this is some other type, no utf-8 here
1215 * Return true if given value is integer or string with integer value
1217 * @param mixed $value String or Int
1218 * @return bool true if number, false if not
1220 function is_number($value) {
1221 if (is_int($value)) {
1223 } else if (is_string($value)) {
1224 return ((string)(int)$value) === $value;
1231 * Returns host part from url
1232 * @param string $url full url
1233 * @return string host, null if not found
1235 function get_host_from_url($url) {
1236 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1244 * Tests whether anything was returned by text editor
1246 * This function is useful for testing whether something you got back from
1247 * the HTML editor actually contains anything. Sometimes the HTML editor
1248 * appear to be empty, but actually you get back a <br> tag or something.
1250 * @param string $string a string containing HTML.
1251 * @return boolean does the string contain any actual content - that is text,
1252 * images, objects, etc.
1254 function html_is_blank($string) {
1255 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1259 * Set a key in global configuration
1261 * Set a key/value pair in both this session's {@link $CFG} global variable
1262 * and in the 'config' database table for future sessions.
1264 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1265 * In that case it doesn't affect $CFG.
1267 * A NULL value will delete the entry.
1271 * @param string $name the key to set
1272 * @param string $value the value to set (without magic quotes)
1273 * @param string $plugin (optional) the plugin scope, default NULL
1274 * @return bool true or exception
1276 function set_config($name, $value, $plugin=NULL) {
1279 if (empty($plugin)) {
1280 if (!array_key_exists($name, $CFG->config_php_settings)) {
1281 // So it's defined for this invocation at least
1282 if (is_null($value)) {
1285 $CFG->$name = (string)$value; // settings from db are always strings
1289 if ($DB->get_field('config', 'name', array('name'=>$name))) {
1290 if ($value === null) {
1291 $DB->delete_records('config', array('name'=>$name));
1293 $DB->set_field('config', 'value', $value, array('name'=>$name));
1296 if ($value !== null) {
1297 $config = new stdClass();
1298 $config->name = $name;
1299 $config->value = $value;
1300 $DB->insert_record('config', $config, false);
1304 } else { // plugin scope
1305 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1306 if ($value===null) {
1307 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1309 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1312 if ($value !== null) {
1313 $config = new stdClass();
1314 $config->plugin = $plugin;
1315 $config->name = $name;
1316 $config->value = $value;
1317 $DB->insert_record('config_plugins', $config, false);
1326 * Get configuration values from the global config table
1327 * or the config_plugins table.
1329 * If called with one parameter, it will load all the config
1330 * variables for one plugin, and return them as an object.
1332 * If called with 2 parameters it will return a string single
1333 * value or false if the value is not found.
1335 * @param string $plugin full component name
1336 * @param string $name default NULL
1337 * @return mixed hash-like object or single value, return false no config found
1339 function get_config($plugin, $name = NULL) {
1342 // normalise component name
1343 if ($plugin === 'moodle' or $plugin === 'core') {
1347 if (!empty($name)) { // the user is asking for a specific value
1348 if (!empty($plugin)) {
1349 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1350 // setting forced in config file
1351 return $CFG->forced_plugin_settings[$plugin][$name];
1353 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1356 if (array_key_exists($name, $CFG->config_php_settings)) {
1357 // setting force in config file
1358 return $CFG->config_php_settings[$name];
1360 return $DB->get_field('config', 'value', array('name'=>$name));
1365 // the user is after a recordset
1367 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1368 if (isset($CFG->forced_plugin_settings[$plugin])) {
1369 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1370 if (is_null($v) or is_array($v) or is_object($v)) {
1371 // we do not want any extra mess here, just real settings that could be saved in db
1372 unset($localcfg[$n]);
1374 //convert to string as if it went through the DB
1375 $localcfg[$n] = (string)$v;
1380 return (object)$localcfg;
1382 return new stdClass();
1386 // this part is not really used any more, but anyway...
1387 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1388 foreach($CFG->config_php_settings as $n=>$v) {
1389 if (is_null($v) or is_array($v) or is_object($v)) {
1390 // we do not want any extra mess here, just real settings that could be saved in db
1391 unset($localcfg[$n]);
1393 //convert to string as if it went through the DB
1394 $localcfg[$n] = (string)$v;
1397 return (object)$localcfg;
1402 * Removes a key from global configuration
1404 * @param string $name the key to set
1405 * @param string $plugin (optional) the plugin scope
1407 * @return boolean whether the operation succeeded.
1409 function unset_config($name, $plugin=NULL) {
1412 if (empty($plugin)) {
1414 $DB->delete_records('config', array('name'=>$name));
1416 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1423 * Remove all the config variables for a given plugin.
1425 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1426 * @return boolean whether the operation succeeded.
1428 function unset_all_config_for_plugin($plugin) {
1430 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1431 $like = $DB->sql_like('name', '?', true, true, false, '|');
1432 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1433 $DB->delete_records_select('config', $like, $params);
1438 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1440 * All users are verified if they still have the necessary capability.
1442 * @param string $value the value of the config setting.
1443 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1444 * @param bool $include admins, include administrators
1445 * @return array of user objects.
1447 function get_users_from_config($value, $capability, $includeadmins = true) {
1450 if (empty($value) or $value === '$@NONE@$') {
1454 // we have to make sure that users still have the necessary capability,
1455 // it should be faster to fetch them all first and then test if they are present
1456 // instead of validating them one-by-one
1457 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1458 if ($includeadmins) {
1459 $admins = get_admins();
1460 foreach ($admins as $admin) {
1461 $users[$admin->id] = $admin;
1465 if ($value === '$@ALL@$') {
1469 $result = array(); // result in correct order
1470 $allowed = explode(',', $value);
1471 foreach ($allowed as $uid) {
1472 if (isset($users[$uid])) {
1473 $user = $users[$uid];
1474 $result[$user->id] = $user;
1483 * Invalidates browser caches and cached data in temp
1486 function purge_all_caches() {
1489 reset_text_filters_cache();
1490 js_reset_all_caches();
1491 theme_reset_all_caches();
1492 get_string_manager()->reset_caches();
1493 textlib::reset_caches();
1495 // purge all other caches: rss, simplepie, etc.
1496 remove_dir($CFG->cachedir.'', true);
1498 // make sure cache dir is writable, throws exception if not
1499 make_cache_directory('');
1501 // hack: this script may get called after the purifier was initialised,
1502 // but we do not want to verify repeatedly this exists in each call
1503 make_cache_directory('htmlpurifier');
1507 * Get volatile flags
1509 * @param string $type
1510 * @param int $changedsince default null
1511 * @return records array
1513 function get_cache_flags($type, $changedsince=NULL) {
1516 $params = array('type'=>$type, 'expiry'=>time());
1517 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1518 if ($changedsince !== NULL) {
1519 $params['changedsince'] = $changedsince;
1520 $sqlwhere .= " AND timemodified > :changedsince";
1524 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1525 foreach ($flags as $flag) {
1526 $cf[$flag->name] = $flag->value;
1533 * Get volatile flags
1535 * @param string $type
1536 * @param string $name
1537 * @param int $changedsince default null
1538 * @return records array
1540 function get_cache_flag($type, $name, $changedsince=NULL) {
1543 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1545 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1546 if ($changedsince !== NULL) {
1547 $params['changedsince'] = $changedsince;
1548 $sqlwhere .= " AND timemodified > :changedsince";
1551 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1555 * Set a volatile flag
1557 * @param string $type the "type" namespace for the key
1558 * @param string $name the key to set
1559 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1560 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1561 * @return bool Always returns true
1563 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1566 $timemodified = time();
1567 if ($expiry===NULL || $expiry < $timemodified) {
1568 $expiry = $timemodified + 24 * 60 * 60;
1570 $expiry = (int)$expiry;
1573 if ($value === NULL) {
1574 unset_cache_flag($type,$name);
1578 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1579 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1580 return true; //no need to update; helps rcache too
1583 $f->expiry = $expiry;
1584 $f->timemodified = $timemodified;
1585 $DB->update_record('cache_flags', $f);
1587 $f = new stdClass();
1588 $f->flagtype = $type;
1591 $f->expiry = $expiry;
1592 $f->timemodified = $timemodified;
1593 $DB->insert_record('cache_flags', $f);
1599 * Removes a single volatile flag
1602 * @param string $type the "type" namespace for the key
1603 * @param string $name the key to set
1606 function unset_cache_flag($type, $name) {
1608 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1613 * Garbage-collect volatile flags
1615 * @return bool Always returns true
1617 function gc_cache_flags() {
1619 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1623 // USER PREFERENCE API
1626 * Refresh user preference cache. This is used most often for $USER
1627 * object that is stored in session, but it also helps with performance in cron script.
1629 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1632 * @category preference
1634 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1635 * @param int $cachelifetime Cache life time on the current page (in seconds)
1636 * @throws coding_exception
1639 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1641 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1643 if (!isset($user->id)) {
1644 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1647 if (empty($user->id) or isguestuser($user->id)) {
1648 // No permanent storage for not-logged-in users and guest
1649 if (!isset($user->preference)) {
1650 $user->preference = array();
1657 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1658 // Already loaded at least once on this page. Are we up to date?
1659 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1660 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1663 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1664 // no change since the lastcheck on this page
1665 $user->preference['_lastloaded'] = $timenow;
1670 // OK, so we have to reload all preferences
1671 $loadedusers[$user->id] = true;
1672 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1673 $user->preference['_lastloaded'] = $timenow;
1677 * Called from set/unset_user_preferences, so that the prefs can
1678 * be correctly reloaded in different sessions.
1680 * NOTE: internal function, do not call from other code.
1684 * @param integer $userid the user whose prefs were changed.
1686 function mark_user_preferences_changed($userid) {
1689 if (empty($userid) or isguestuser($userid)) {
1690 // no cache flags for guest and not-logged-in users
1694 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1698 * Sets a preference for the specified user.
1700 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1703 * @category preference
1705 * @param string $name The key to set as preference for the specified user
1706 * @param string $value The value to set for the $name key in the specified user's
1707 * record, null means delete current value.
1708 * @param stdClass|int|null $user A moodle user object or id, null means current user
1709 * @throws coding_exception
1710 * @return bool Always true or exception
1712 function set_user_preference($name, $value, $user = null) {
1715 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1716 throw new coding_exception('Invalid preference name in set_user_preference() call');
1719 if (is_null($value)) {
1720 // null means delete current
1721 return unset_user_preference($name, $user);
1722 } else if (is_object($value)) {
1723 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1724 } else if (is_array($value)) {
1725 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1727 $value = (string)$value;
1728 if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1729 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1732 if (is_null($user)) {
1734 } else if (isset($user->id)) {
1735 // $user is valid object
1736 } else if (is_numeric($user)) {
1737 $user = (object)array('id'=>(int)$user);
1739 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1742 check_user_preferences_loaded($user);
1744 if (empty($user->id) or isguestuser($user->id)) {
1745 // no permanent storage for not-logged-in users and guest
1746 $user->preference[$name] = $value;
1750 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1751 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1752 // preference already set to this value
1755 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1758 $preference = new stdClass();
1759 $preference->userid = $user->id;
1760 $preference->name = $name;
1761 $preference->value = $value;
1762 $DB->insert_record('user_preferences', $preference);
1765 // update value in cache
1766 $user->preference[$name] = $value;
1768 // set reload flag for other sessions
1769 mark_user_preferences_changed($user->id);
1775 * Sets a whole array of preferences for the current user
1777 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1780 * @category preference
1782 * @param array $prefarray An array of key/value pairs to be set
1783 * @param stdClass|int|null $user A moodle user object or id, null means current user
1784 * @return bool Always true or exception
1786 function set_user_preferences(array $prefarray, $user = null) {
1787 foreach ($prefarray as $name => $value) {
1788 set_user_preference($name, $value, $user);
1794 * Unsets a preference completely by deleting it from the database
1796 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1799 * @category preference
1801 * @param string $name The key to unset as preference for the specified user
1802 * @param stdClass|int|null $user A moodle user object or id, null means current user
1803 * @throws coding_exception
1804 * @return bool Always true or exception
1806 function unset_user_preference($name, $user = null) {
1809 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1810 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1813 if (is_null($user)) {
1815 } else if (isset($user->id)) {
1816 // $user is valid object
1817 } else if (is_numeric($user)) {
1818 $user = (object)array('id'=>(int)$user);
1820 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1823 check_user_preferences_loaded($user);
1825 if (empty($user->id) or isguestuser($user->id)) {
1826 // no permanent storage for not-logged-in user and guest
1827 unset($user->preference[$name]);
1832 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1834 // delete the preference from cache
1835 unset($user->preference[$name]);
1837 // set reload flag for other sessions
1838 mark_user_preferences_changed($user->id);
1844 * Used to fetch user preference(s)
1846 * If no arguments are supplied this function will return
1847 * all of the current user preferences as an array.
1849 * If a name is specified then this function
1850 * attempts to return that particular preference value. If
1851 * none is found, then the optional value $default is returned,
1854 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1857 * @category preference
1859 * @param string $name Name of the key to use in finding a preference value
1860 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1861 * @param stdClass|int|null $user A moodle user object or id, null means current user
1862 * @throws coding_exception
1863 * @return string|mixed|null A string containing the value of a single preference. An
1864 * array with all of the preferences or null
1866 function get_user_preferences($name = null, $default = null, $user = null) {
1869 if (is_null($name)) {
1871 } else if (is_numeric($name) or $name === '_lastloaded') {
1872 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1875 if (is_null($user)) {
1877 } else if (isset($user->id)) {
1878 // $user is valid object
1879 } else if (is_numeric($user)) {
1880 $user = (object)array('id'=>(int)$user);
1882 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1885 check_user_preferences_loaded($user);
1888 return $user->preference; // All values
1889 } else if (isset($user->preference[$name])) {
1890 return $user->preference[$name]; // The single string value
1892 return $default; // Default value (null if not specified)
1896 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1899 * Given date parts in user time produce a GMT timestamp.
1903 * @param int $year The year part to create timestamp of
1904 * @param int $month The month part to create timestamp of
1905 * @param int $day The day part to create timestamp of
1906 * @param int $hour The hour part to create timestamp of
1907 * @param int $minute The minute part to create timestamp of
1908 * @param int $second The second part to create timestamp of
1909 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1910 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
1911 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1912 * applied only if timezone is 99 or string.
1913 * @return int GMT timestamp
1915 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1917 //save input timezone, required for dst offset check.
1918 $passedtimezone = $timezone;
1920 $timezone = get_user_timezone_offset($timezone);
1922 if (abs($timezone) > 13) { //server time
1923 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1925 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1926 $time = usertime($time, $timezone);
1928 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1929 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1930 $time -= dst_offset_on($time, $passedtimezone);
1939 * Format a date/time (seconds) as weeks, days, hours etc as needed
1941 * Given an amount of time in seconds, returns string
1942 * formatted nicely as weeks, days, hours etc as needed
1950 * @param int $totalsecs Time in seconds
1951 * @param object $str Should be a time object
1952 * @return string A nicely formatted date/time string
1954 function format_time($totalsecs, $str=NULL) {
1956 $totalsecs = abs($totalsecs);
1958 if (!$str) { // Create the str structure the slow way
1959 $str = new stdClass();
1960 $str->day = get_string('day');
1961 $str->days = get_string('days');
1962 $str->hour = get_string('hour');
1963 $str->hours = get_string('hours');
1964 $str->min = get_string('min');
1965 $str->mins = get_string('mins');
1966 $str->sec = get_string('sec');
1967 $str->secs = get_string('secs');
1968 $str->year = get_string('year');
1969 $str->years = get_string('years');
1973 $years = floor($totalsecs/YEARSECS);
1974 $remainder = $totalsecs - ($years*YEARSECS);
1975 $days = floor($remainder/DAYSECS);
1976 $remainder = $totalsecs - ($days*DAYSECS);
1977 $hours = floor($remainder/HOURSECS);
1978 $remainder = $remainder - ($hours*HOURSECS);
1979 $mins = floor($remainder/MINSECS);
1980 $secs = $remainder - ($mins*MINSECS);
1982 $ss = ($secs == 1) ? $str->sec : $str->secs;
1983 $sm = ($mins == 1) ? $str->min : $str->mins;
1984 $sh = ($hours == 1) ? $str->hour : $str->hours;
1985 $sd = ($days == 1) ? $str->day : $str->days;
1986 $sy = ($years == 1) ? $str->year : $str->years;
1994 if ($years) $oyears = $years .' '. $sy;
1995 if ($days) $odays = $days .' '. $sd;
1996 if ($hours) $ohours = $hours .' '. $sh;
1997 if ($mins) $omins = $mins .' '. $sm;
1998 if ($secs) $osecs = $secs .' '. $ss;
2000 if ($years) return trim($oyears .' '. $odays);
2001 if ($days) return trim($odays .' '. $ohours);
2002 if ($hours) return trim($ohours .' '. $omins);
2003 if ($mins) return trim($omins .' '. $osecs);
2004 if ($secs) return $osecs;
2005 return get_string('now');
2009 * Returns a formatted string that represents a date in user time
2011 * Returns a formatted string that represents a date in user time
2012 * <b>WARNING: note that the format is for strftime(), not date().</b>
2013 * Because of a bug in most Windows time libraries, we can't use
2014 * the nicer %e, so we have to use %d which has leading zeroes.
2015 * A lot of the fuss in the function is just getting rid of these leading
2016 * zeroes as efficiently as possible.
2018 * If parameter fixday = true (default), then take off leading
2019 * zero from %d, else maintain it.
2023 * @param int $date the timestamp in UTC, as obtained from the database.
2024 * @param string $format strftime format. You should probably get this using
2025 * get_string('strftime...', 'langconfig');
2026 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2027 * not 99 then daylight saving will not be added.
2028 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2029 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2030 * If false then the leading zero is maintained.
2031 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2032 * @return string the formatted date/time.
2034 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2038 if (empty($format)) {
2039 $format = get_string('strftimedaydatetime', 'langconfig');
2042 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
2044 } else if ($fixday) {
2045 $formatnoday = str_replace('%d', 'DD', $format);
2046 $fixday = ($formatnoday != $format);
2047 $format = $formatnoday;
2050 // Note: This logic about fixing 12-hour time to remove unnecessary leading
2051 // zero is required because on Windows, PHP strftime function does not
2052 // support the correct 'hour without leading zero' parameter (%l).
2053 if (!empty($CFG->nofixhour)) {
2054 // Config.php can force %I not to be fixed.
2056 } else if ($fixhour) {
2057 $formatnohour = str_replace('%I', 'HH', $format);
2058 $fixhour = ($formatnohour != $format);
2059 $format = $formatnohour;
2062 //add daylight saving offset for string timezones only, as we can't get dst for
2063 //float values. if timezone is 99 (user default timezone), then try update dst.
2064 if ((99 == $timezone) || !is_numeric($timezone)) {
2065 $date += dst_offset_on($date, $timezone);
2068 $timezone = get_user_timezone_offset($timezone);
2070 // If we are running under Windows convert to windows encoding and then back to UTF-8
2071 // (because it's impossible to specify UTF-8 to fetch locale info in Win32)
2073 if (abs($timezone) > 13) { /// Server time
2074 $datestring = date_format_string($date, $format, $timezone);
2076 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
2077 $datestring = str_replace('DD', $daystring, $datestring);
2080 $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2081 $datestring = str_replace('HH', $hourstring, $datestring);
2085 $date += (int)($timezone * 3600);
2086 $datestring = date_format_string($date, $format, $timezone);
2088 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
2089 $datestring = str_replace('DD', $daystring, $datestring);
2092 $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2093 $datestring = str_replace('HH', $hourstring, $datestring);
2101 * Returns a formatted date ensuring it is UTF-8.
2103 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2104 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2106 * This function does not do any calculation regarding the user preferences and should
2107 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2108 * to differenciate the use of server time or not (strftime() against gmstrftime()).
2110 * @param int $date the timestamp.
2111 * @param string $format strftime format.
2112 * @param int|float $timezone the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2113 * @return string the formatted date/time.
2116 function date_format_string($date, $format, $tz = 99) {
2118 if (abs($tz) > 13) {
2119 if ($CFG->ostype == 'WINDOWS' and ($localewincharset = get_string('localewincharset', 'langconfig'))) {
2120 $format = textlib::convert($format, 'utf-8', $localewincharset);
2121 $datestring = strftime($format, $date);
2122 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2124 $datestring = strftime($format, $date);
2127 if ($CFG->ostype == 'WINDOWS' and ($localewincharset = get_string('localewincharset', 'langconfig'))) {
2128 $format = textlib::convert($format, 'utf-8', $localewincharset);
2129 $datestring = gmstrftime($format, $date);
2130 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2132 $datestring = gmstrftime($format, $date);
2139 * Given a $time timestamp in GMT (seconds since epoch),
2140 * returns an array that represents the date in user time
2145 * @param int $time Timestamp in GMT
2146 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2147 * dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
2148 * @return array An array that represents the date in user time
2150 function usergetdate($time, $timezone=99) {
2152 //save input timezone, required for dst offset check.
2153 $passedtimezone = $timezone;
2155 $timezone = get_user_timezone_offset($timezone);
2157 if (abs($timezone) > 13) { // Server time
2158 return getdate($time);
2161 //add daylight saving offset for string timezones only, as we can't get dst for
2162 //float values. if timezone is 99 (user default timezone), then try update dst.
2163 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2164 $time += dst_offset_on($time, $passedtimezone);
2167 $time += intval((float)$timezone * HOURSECS);
2169 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2171 //be careful to ensure the returned array matches that produced by getdate() above
2174 $getdate['weekday'],
2181 $getdate['minutes'],
2183 ) = explode('_', $datestring);
2185 // set correct datatype to match with getdate()
2186 $getdate['seconds'] = (int)$getdate['seconds'];
2187 $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
2188 $getdate['year'] = (int)$getdate['year'];
2189 $getdate['mon'] = (int)$getdate['mon'];
2190 $getdate['wday'] = (int)$getdate['wday'];
2191 $getdate['mday'] = (int)$getdate['mday'];
2192 $getdate['hours'] = (int)$getdate['hours'];
2193 $getdate['minutes'] = (int)$getdate['minutes'];
2198 * Given a GMT timestamp (seconds since epoch), offsets it by
2199 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2204 * @param int $date Timestamp in GMT
2205 * @param float|int|string $timezone timezone to calculate GMT time offset before
2206 * calculating user time, 99 is default user timezone
2207 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2210 function usertime($date, $timezone=99) {
2212 $timezone = get_user_timezone_offset($timezone);
2214 if (abs($timezone) > 13) {
2217 return $date - (int)($timezone * HOURSECS);
2221 * Given a time, return the GMT timestamp of the most recent midnight
2222 * for the current user.
2226 * @param int $date Timestamp in GMT
2227 * @param float|int|string $timezone timezone to calculate GMT time offset before
2228 * calculating user midnight time, 99 is default user timezone
2229 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2230 * @return int Returns a GMT timestamp
2232 function usergetmidnight($date, $timezone=99) {
2234 $userdate = usergetdate($date, $timezone);
2236 // Time of midnight of this user's day, in GMT
2237 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2242 * Returns a string that prints the user's timezone
2246 * @param float|int|string $timezone timezone to calculate GMT time offset before
2247 * calculating user timezone, 99 is default user timezone
2248 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2251 function usertimezone($timezone=99) {
2253 $tz = get_user_timezone($timezone);
2255 if (!is_float($tz)) {
2259 if(abs($tz) > 13) { // Server time
2260 return get_string('serverlocaltime');
2263 if($tz == intval($tz)) {
2264 // Don't show .0 for whole hours
2281 * Returns a float which represents the user's timezone difference from GMT in hours
2282 * Checks various settings and picks the most dominant of those which have a value
2286 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2287 * 99 is default user timezone
2288 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2291 function get_user_timezone_offset($tz = 99) {
2295 $tz = get_user_timezone($tz);
2297 if (is_float($tz)) {
2300 $tzrecord = get_timezone_record($tz);
2301 if (empty($tzrecord)) {
2304 return (float)$tzrecord->gmtoff / HOURMINS;
2309 * Returns an int which represents the systems's timezone difference from GMT in seconds
2313 * @param float|int|string $tz timezone for which offset is required.
2314 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2315 * @return int|bool if found, false is timezone 99 or error
2317 function get_timezone_offset($tz) {
2324 if (is_numeric($tz)) {
2325 return intval($tz * 60*60);
2328 if (!$tzrecord = get_timezone_record($tz)) {
2331 return intval($tzrecord->gmtoff * 60);
2335 * Returns a float or a string which denotes the user's timezone
2336 * 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)
2337 * means that for this timezone there are also DST rules to be taken into account
2338 * Checks various settings and picks the most dominant of those which have a value
2342 * @param float|int|string $tz timezone to calculate GMT time offset before
2343 * calculating user timezone, 99 is default user timezone
2344 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2345 * @return float|string
2347 function get_user_timezone($tz = 99) {
2352 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2353 isset($USER->timezone) ? $USER->timezone : 99,
2354 isset($CFG->timezone) ? $CFG->timezone : 99,
2359 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array
2360 while(((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2361 $tz = $next['value'];
2363 return is_numeric($tz) ? (float) $tz : $tz;
2367 * Returns cached timezone record for given $timezonename
2370 * @param string $timezonename name of the timezone
2371 * @return stdClass|bool timezonerecord or false
2373 function get_timezone_record($timezonename) {
2375 static $cache = NULL;
2377 if ($cache === NULL) {
2381 if (isset($cache[$timezonename])) {
2382 return $cache[$timezonename];
2385 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2386 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2390 * Build and store the users Daylight Saving Time (DST) table
2393 * @param int $from_year Start year for the table, defaults to 1971
2394 * @param int $to_year End year for the table, defaults to 2035
2395 * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
2398 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2399 global $CFG, $SESSION, $DB;
2401 $usertz = get_user_timezone($strtimezone);
2403 if (is_float($usertz)) {
2404 // Trivial timezone, no DST
2408 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2409 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2410 unset($SESSION->dst_offsets);
2411 unset($SESSION->dst_range);
2414 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2415 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2416 // This will be the return path most of the time, pretty light computationally
2420 // Reaching here means we either need to extend our table or create it from scratch
2422 // Remember which TZ we calculated these changes for
2423 $SESSION->dst_offsettz = $usertz;
2425 if(empty($SESSION->dst_offsets)) {
2426 // If we 're creating from scratch, put the two guard elements in there
2427 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2429 if(empty($SESSION->dst_range)) {
2430 // If creating from scratch
2431 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2432 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2434 // Fill in the array with the extra years we need to process
2435 $yearstoprocess = array();
2436 for($i = $from; $i <= $to; ++$i) {
2437 $yearstoprocess[] = $i;
2440 // Take note of which years we have processed for future calls
2441 $SESSION->dst_range = array($from, $to);
2444 // If needing to extend the table, do the same
2445 $yearstoprocess = array();
2447 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2448 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2450 if($from < $SESSION->dst_range[0]) {
2451 // Take note of which years we need to process and then note that we have processed them for future calls
2452 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2453 $yearstoprocess[] = $i;
2455 $SESSION->dst_range[0] = $from;
2457 if($to > $SESSION->dst_range[1]) {
2458 // Take note of which years we need to process and then note that we have processed them for future calls
2459 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2460 $yearstoprocess[] = $i;
2462 $SESSION->dst_range[1] = $to;
2466 if(empty($yearstoprocess)) {
2467 // This means that there was a call requesting a SMALLER range than we have already calculated
2471 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2472 // Also, the array is sorted in descending timestamp order!
2476 static $presets_cache = array();
2477 if (!isset($presets_cache[$usertz])) {
2478 $presets_cache[$usertz] = $DB->get_records('timezone', array('name'=>$usertz), 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, std_startday, std_weekday, std_skipweeks, std_time');
2480 if(empty($presets_cache[$usertz])) {
2484 // Remove ending guard (first element of the array)
2485 reset($SESSION->dst_offsets);
2486 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2488 // Add all required change timestamps
2489 foreach($yearstoprocess as $y) {
2490 // Find the record which is in effect for the year $y
2491 foreach($presets_cache[$usertz] as $year => $preset) {
2497 $changes = dst_changes_for_year($y, $preset);
2499 if($changes === NULL) {
2502 if($changes['dst'] != 0) {
2503 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2505 if($changes['std'] != 0) {
2506 $SESSION->dst_offsets[$changes['std']] = 0;
2510 // Put in a guard element at the top
2511 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2512 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2515 krsort($SESSION->dst_offsets);
2521 * Calculates the required DST change and returns a Timestamp Array
2527 * @param int|string $year Int or String Year to focus on
2528 * @param object $timezone Instatiated Timezone object
2529 * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
2531 function dst_changes_for_year($year, $timezone) {
2533 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2537 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2538 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2540 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2541 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2543 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2544 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2546 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2547 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2548 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2550 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2551 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2553 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2557 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2558 * - Note: Daylight saving only works for string timezones and not for float.
2562 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2563 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2564 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2567 function dst_offset_on($time, $strtimezone = NULL) {
2570 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2574 reset($SESSION->dst_offsets);
2575 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2576 if($from <= $time) {
2581 // This is the normal return path
2582 if($offset !== NULL) {
2586 // Reaching this point means we haven't calculated far enough, do it now:
2587 // Calculate extra DST changes if needed and recurse. The recursion always
2588 // moves toward the stopping condition, so will always end.
2591 // We need a year smaller than $SESSION->dst_range[0]
2592 if($SESSION->dst_range[0] == 1971) {
2595 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2596 return dst_offset_on($time, $strtimezone);
2599 // We need a year larger than $SESSION->dst_range[1]
2600 if($SESSION->dst_range[1] == 2035) {
2603 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2604 return dst_offset_on($time, $strtimezone);
2609 * Calculates when the day appears in specific month
2613 * @param int $startday starting day of the month
2614 * @param int $weekday The day when week starts (normally taken from user preferences)
2615 * @param int $month The month whose day is sought
2616 * @param int $year The year of the month whose day is sought
2619 function find_day_in_month($startday, $weekday, $month, $year) {
2621 $daysinmonth = days_in_month($month, $year);
2623 if($weekday == -1) {
2624 // Don't care about weekday, so return:
2625 // abs($startday) if $startday != -1
2626 // $daysinmonth otherwise
2627 return ($startday == -1) ? $daysinmonth : abs($startday);
2630 // From now on we 're looking for a specific weekday
2632 // Give "end of month" its actual value, since we know it
2633 if($startday == -1) {
2634 $startday = -1 * $daysinmonth;
2637 // Starting from day $startday, the sign is the direction
2641 $startday = abs($startday);
2642 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2644 // This is the last such weekday of the month
2645 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2646 if($lastinmonth > $daysinmonth) {
2650 // Find the first such weekday <= $startday
2651 while($lastinmonth > $startday) {
2655 return $lastinmonth;
2660 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2662 $diff = $weekday - $indexweekday;
2667 // This is the first such weekday of the month equal to or after $startday
2668 $firstfromindex = $startday + $diff;
2670 return $firstfromindex;
2676 * Calculate the number of days in a given month
2680 * @param int $month The month whose day count is sought
2681 * @param int $year The year of the month whose day count is sought
2684 function days_in_month($month, $year) {
2685 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2689 * Calculate the position in the week of a specific calendar day
2693 * @param int $day The day of the date whose position in the week is sought
2694 * @param int $month The month of the date whose position in the week is sought
2695 * @param int $year The year of the date whose position in the week is sought
2698 function dayofweek($day, $month, $year) {
2699 // I wonder if this is any different from
2700 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2701 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2704 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2707 * Returns full login url.
2709 * @return string login url
2711 function get_login_url() {
2714 $url = "$CFG->wwwroot/login/index.php";
2716 if (!empty($CFG->loginhttps)) {
2717 $url = str_replace('http:', 'https:', $url);
2724 * This function checks that the current user is logged in and has the
2725 * required privileges
2727 * This function checks that the current user is logged in, and optionally
2728 * whether they are allowed to be in a particular course and view a particular
2730 * If they are not logged in, then it redirects them to the site login unless
2731 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2732 * case they are automatically logged in as guests.
2733 * If $courseid is given and the user is not enrolled in that course then the
2734 * user is redirected to the course enrolment page.
2735 * If $cm is given and the course module is hidden and the user is not a teacher
2736 * in the course then the user is redirected to the course home page.
2738 * When $cm parameter specified, this function sets page layout to 'module'.
2739 * You need to change it manually later if some other layout needed.
2741 * @package core_access
2744 * @param mixed $courseorid id of the course or course object
2745 * @param bool $autologinguest default true
2746 * @param object $cm course module object
2747 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2748 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2749 * in order to keep redirects working properly. MDL-14495
2750 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2751 * @return mixed Void, exit, and die depending on path
2753 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2754 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2756 // setup global $COURSE, themes, language and locale
2757 if (!empty($courseorid)) {
2758 if (is_object($courseorid)) {
2759 $course = $courseorid;
2760 } else if ($courseorid == SITEID) {
2761 $course = clone($SITE);
2763 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2766 if ($cm->course != $course->id) {
2767 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2769 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2770 if (!($cm instanceof cm_info)) {
2771 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2772 // db queries so this is not really a performance concern, however it is obviously
2773 // better if you use get_fast_modinfo to get the cm before calling this.
2774 $modinfo = get_fast_modinfo($course);
2775 $cm = $modinfo->get_cm($cm->id);
2777 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2778 $PAGE->set_pagelayout('incourse');
2780 $PAGE->set_course($course); // set's up global $COURSE
2783 // do not touch global $COURSE via $PAGE->set_course(),
2784 // the reasons is we need to be able to call require_login() at any time!!
2787 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2791 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2792 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2793 // risk leading the user back to the AJAX request URL.
2794 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2795 $setwantsurltome = false;
2798 // If the user is not even logged in yet then make sure they are
2799 if (!isloggedin()) {
2800 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2801 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2802 // misconfigured site guest, just redirect to login page
2803 redirect(get_login_url());
2804 exit; // never reached
2806 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2807 complete_user_login($guest);
2808 $USER->autologinguest = true;
2809 $SESSION->lang = $lang;
2811 //NOTE: $USER->site check was obsoleted by session test cookie,
2812 // $USER->confirmed test is in login/index.php
2813 if ($preventredirect) {
2814 throw new require_login_exception('You are not logged in');
2817 if ($setwantsurltome) {
2818 $SESSION->wantsurl = qualified_me();
2820 if (!empty($_SERVER['HTTP_REFERER'])) {
2821 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2823 redirect(get_login_url());
2824 exit; // never reached
2828 // loginas as redirection if needed
2829 if ($course->id != SITEID and session_is_loggedinas()) {
2830 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2831 if ($USER->loginascontext->instanceid != $course->id) {
2832 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2837 // check whether the user should be changing password (but only if it is REALLY them)
2838 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2839 $userauth = get_auth_plugin($USER->auth);
2840 if ($userauth->can_change_password() and !$preventredirect) {
2841 if ($setwantsurltome) {
2842 $SESSION->wantsurl = qualified_me();
2844 if ($changeurl = $userauth->change_password_url()) {
2845 //use plugin custom url
2846 redirect($changeurl);
2848 //use moodle internal method
2849 if (empty($CFG->loginhttps)) {
2850 redirect($CFG->wwwroot .'/login/change_password.php');
2852 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2853 redirect($wwwroot .'/login/change_password.php');
2857 print_error('nopasswordchangeforced', 'auth');
2861 // Check that the user account is properly set up
2862 if (user_not_fully_set_up($USER)) {
2863 if ($preventredirect) {
2864 throw new require_login_exception('User not fully set-up');
2866 if ($setwantsurltome) {
2867 $SESSION->wantsurl = qualified_me();
2869 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2872 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2875 // Do not bother admins with any formalities
2876 if (is_siteadmin()) {
2877 //set accesstime or the user will appear offline which messes up messaging
2878 user_accesstime_log($course->id);
2882 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2883 if (!$USER->policyagreed and !is_siteadmin()) {
2884 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2885 if ($preventredirect) {
2886 throw new require_login_exception('Policy not agreed');
2888 if ($setwantsurltome) {
2889 $SESSION->wantsurl = qualified_me();
2891 redirect($CFG->wwwroot .'/user/policy.php');
2892 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2893 if ($preventredirect) {
2894 throw new require_login_exception('Policy not agreed');
2896 if ($setwantsurltome) {
2897 $SESSION->wantsurl = qualified_me();
2899 redirect($CFG->wwwroot .'/user/policy.php');
2903 // Fetch the system context, the course context, and prefetch its child contexts
2904 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2905 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2907 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2912 // If the site is currently under maintenance, then print a message
2913 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2914 if ($preventredirect) {
2915 throw new require_login_exception('Maintenance in progress');
2918 print_maintenance_message();
2921 // make sure the course itself is not hidden
2922 if ($course->id == SITEID) {
2923 // frontpage can not be hidden
2925 if (is_role_switched($course->id)) {
2926 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2928 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2929 // originally there was also test of parent category visibility,
2930 // BUT is was very slow in complex queries involving "my courses"
2931 // now it is also possible to simply hide all courses user is not enrolled in :-)
2932 if ($preventredirect) {
2933 throw new require_login_exception('Course is hidden');
2935 // We need to override the navigation URL as the course won't have
2936 // been added to the navigation and thus the navigation will mess up
2937 // when trying to find it.
2938 navigation_node::override_active_url(new moodle_url('/'));
2939 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2944 // is the user enrolled?
2945 if ($course->id == SITEID) {
2946 // everybody is enrolled on the frontpage
2949 if (session_is_loggedinas()) {
2950 // Make sure the REAL person can access this course first
2951 $realuser = session_get_realuser();
2952 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2953 if ($preventredirect) {
2954 throw new require_login_exception('Invalid course login-as access');
2956 echo $OUTPUT->header();
2957 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2963 if (is_role_switched($course->id)) {
2964 // ok, user had to be inside this course before the switch
2967 } else if (is_viewing($coursecontext, $USER)) {
2968 // ok, no need to mess with enrol
2972 if (isset($USER->enrol['enrolled'][$course->id])) {
2973 if ($USER->enrol['enrolled'][$course->id] > time()) {
2975 if (isset($USER->enrol['tempguest'][$course->id])) {
2976 unset($USER->enrol['tempguest'][$course->id]);
2977 remove_temp_course_roles($coursecontext);
2981 unset($USER->enrol['enrolled'][$course->id]);
2984 if (isset($USER->enrol['tempguest'][$course->id])) {
2985 if ($USER->enrol['tempguest'][$course->id] == 0) {
2987 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2991 unset($USER->enrol['tempguest'][$course->id]);
2992 remove_temp_course_roles($coursecontext);
2999 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3000 if ($until !== false) {
3001 // active participants may always access, a timestamp in the future, 0 (always) or false.
3003 $until = ENROL_MAX_TIMESTAMP;
3005 $USER->enrol['enrolled'][$course->id] = $until;
3009 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
3010 $enrols = enrol_get_plugins(true);
3011 // first ask all enabled enrol instances in course if they want to auto enrol user
3012 foreach($instances as $instance) {
3013 if (!isset($enrols[$instance->enrol])) {
3016 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3017 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3018 if ($until !== false) {
3020 $until = ENROL_MAX_TIMESTAMP;
3022 $USER->enrol['enrolled'][$course->id] = $until;
3027 // if not enrolled yet try to gain temporary guest access
3029 foreach($instances as $instance) {
3030 if (!isset($enrols[$instance->enrol])) {
3033 // Get a duration for the guest access, a timestamp in the future or false.
3034 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3035 if ($until !== false and $until > time()) {
3036 $USER->enrol['tempguest'][$course->id] = $until;
3047 if ($preventredirect) {
3048 throw new require_login_exception('Not enrolled');
3050 if ($setwantsurltome) {
3051 $SESSION->wantsurl = qualified_me();
3053 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3057 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
3058 // conditional availability, etc
3059 if ($cm && !$cm->uservisible) {
3060 if ($preventredirect) {
3061 throw new require_login_exception('Activity is hidden');
3063 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
3066 // Finally access granted, update lastaccess times
3067 user_accesstime_log($course->id);
3072 * This function just makes sure a user is logged out.
3074 * @package core_access
3076 function require_logout() {
3082 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
3084 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
3085 foreach($authsequence as $authname) {
3086 $authplugin = get_auth_plugin($authname);
3087 $authplugin->prelogout_hook();
3091 events_trigger('user_logout', $params);
3092 session_get_instance()->terminate_current();
3097 * Weaker version of require_login()
3099 * This is a weaker version of {@link require_login()} which only requires login
3100 * when called from within a course rather than the site page, unless
3101 * the forcelogin option is turned on.
3102 * @see require_login()
3104 * @package core_access
3107 * @param mixed $courseorid The course object or id in question
3108 * @param bool $autologinguest Allow autologin guests if that is wanted
3109 * @param object $cm Course activity module if known
3110 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3111 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3112 * in order to keep redirects working properly. MDL-14495
3113 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3116 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
3117 global $CFG, $PAGE, $SITE;
3118 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3119 or (!is_object($courseorid) and $courseorid == SITEID);
3120 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3121 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
3122 // db queries so this is not really a performance concern, however it is obviously
3123 // better if you use get_fast_modinfo to get the cm before calling this.
3124 if (is_object($courseorid)) {
3125 $course = $courseorid;
3127 $course = clone($SITE);
3129 $modinfo = get_fast_modinfo($course);
3130 $cm = $modinfo->get_cm($cm->id);
3132 if (!empty($CFG->forcelogin)) {
3133 // login required for both SITE and courses
3134 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3136 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3137 // always login for hidden activities
3138 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3140 } else if ($issite) {
3141 //login for SITE not required
3142 if ($cm and empty($cm->visible)) {
3143 // hidden activities are not accessible without login
3144 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3145 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3146 // not-logged-in users do not have any group membership
3147 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3149 // We still need to instatiate PAGE vars properly so that things
3150 // that rely on it like navigation function correctly.
3151 if (!empty($courseorid)) {
3152 if (is_object($courseorid)) {
3153 $course = $courseorid;
3155 $course = clone($SITE);
3158 if ($cm->course != $course->id) {
3159 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3161 $PAGE->set_cm($cm, $course);
3162 $PAGE->set_pagelayout('incourse');
3164 $PAGE->set_course($course);
3167 // If $PAGE->course, and hence $PAGE->context, have not already been set
3168 // up properly, set them up now.
3169 $PAGE->set_course($PAGE->course);
3171 //TODO: verify conditional activities here
3172 user_accesstime_log(SITEID);
3177 // course login always required
3178 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3183 * Require key login. Function terminates with error if key not found or incorrect.
3189 * @uses NO_MOODLE_COOKIES
3190 * @uses PARAM_ALPHANUM
3191 * @param string $script unique script identifier
3192 * @param int $instance optional instance id
3193 * @return int Instance ID
3195 function require_user_key_login($script, $instance=null) {
3196 global $USER, $SESSION, $CFG, $DB;
3198 if (!NO_MOODLE_COOKIES) {
3199 print_error('sessioncookiesdisable');
3203 @session_write_close();
3205 $keyvalue = required_param('key', PARAM_ALPHANUM);
3207 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3208 print_error('invalidkey');
3211 if (!empty($key->validuntil) and $key->validuntil < time()) {
3212 print_error('expiredkey');
3215 if ($key->iprestriction) {
3216 $remoteaddr = getremoteaddr(null);
3217 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3218 print_error('ipmismatch');
3222 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
3223 print_error('invaliduserid');
3226 /// emulate normal session
3227 enrol_check_plugins($user);
3228 session_set_user($user);
3230 /// note we are not using normal login
3231 if (!defined('USER_KEY_LOGIN')) {
3232 define('USER_KEY_LOGIN', true);
3235 /// return instance id - it might be empty
3236 return $key->instance;
3240 * Creates a new private user access key.
3243 * @param string $script unique target identifier
3244 * @param int $userid
3245 * @param int $instance optional instance id
3246 * @param string $iprestriction optional ip restricted access
3247 * @param timestamp $validuntil key valid only until given data
3248 * @return string access key value
3250 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3253 $key = new stdClass();
3254 $key->script = $script;
3255 $key->userid = $userid;
3256 $key->instance = $instance;
3257 $key->iprestriction = $iprestriction;
3258 $key->validuntil = $validuntil;
3259 $key->timecreated = time();
3261 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
3262 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3264 $key->value = md5($userid.'_'.time().random_string(40));
3266 $DB->insert_record('user_private_key', $key);
3271 * Delete the user's new private user access keys for a particular script.
3274 * @param string $script unique target identifier
3275 * @param int $userid
3278 function delete_user_key($script,$userid) {
3280 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3284 * Gets a private user access key (and creates one if one doesn't exist).
3287 * @param string $script unique target identifier
3288 * @param int $userid
3289 * @param int $instance optional instance id
3290 * @param string $iprestriction optional ip restricted access
3291 * @param timestamp $validuntil key valid only until given data
3292 * @return string access key value
3294 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3297 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3298 'instance'=>$instance, 'iprestriction'=>$iprestriction,
3299 'validuntil'=>$validuntil))) {
3302 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3308 * Modify the user table by setting the currently logged in user's
3309 * last login to now.
3313 * @return bool Always returns true
3315 function update_user_login_times() {
3318 if (isguestuser()) {
3319 // Do not update guest access times/ips for performance.
3325 $user = new stdClass();
3326 $user->id = $USER->id;
3328 // Make sure all users that logged in have some firstaccess.
3329 if ($USER->firstaccess == 0) {
3330 $USER->firstaccess = $user->firstaccess = $now;
3333 // Store the previous current as lastlogin.
3334 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3336 $USER->currentlogin = $user->currentlogin = $now;
3338 // Function user_accesstime_log() may not update immediately, better do it here.
3339 $USER->lastaccess = $user->lastaccess = $now;
3340 $USER->lastip = $user->lastip = getremoteaddr();
3342 $DB->update_record('user', $user);
3347 * Determines if a user has completed setting up their account.
3349 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3352 function user_not_fully_set_up($user) {
3353 if (isguestuser($user)) {
3356 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3360 * Check whether the user has exceeded the bounce threshold
3364 * @param user $user A {@link $USER} object
3365 * @return bool true=>User has exceeded bounce threshold
3367 function over_bounce_threshold($user) {
3370 if (empty($CFG->handlebounces)) {
3374 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3378 // set sensible defaults
3379 if (empty($CFG->minbounces)) {
3380 $CFG->minbounces = 10;
3382 if (empty($CFG->bounceratio)) {
3383 $CFG->bounceratio = .20;
3387 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3388 $bouncecount = $bounce->value;
3390 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3391 $sendcount = $send->value;
3393 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3397 * Used to increment or reset email sent count
3400 * @param user $user object containing an id
3401 * @param bool $reset will reset the count to 0
3404 function set_send_count($user,$reset=false) {
3407 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3411 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3412 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3413 $DB->update_record('user_preferences', $pref);
3415 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3417 $pref = new stdClass();
3418 $pref->name = 'email_send_count';
3420 $pref->userid = $user->id;
3421 $DB->insert_record('user_preferences', $pref, false);
3426 * Increment or reset user's email bounce count
3429 * @param user $user object containing an id
3430 * @param bool $reset will reset the count to 0
3432 function set_bounce_count($user,$reset=false) {
3435 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3436 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3437 $DB->update_record('user_preferences', $pref);
3439 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3441 $pref = new stdClass();
3442 $pref->name = 'email_bounce_count';
3444 $pref->userid = $user->id;
3445 $DB->insert_record('user_preferences', $pref, false);
3450 * Keeps track of login attempts
3454 function update_login_count() {
3459 if (empty($SESSION->logincount)) {
3460 $SESSION->logincount = 1;
3462 $SESSION->logincount++;
3465 if ($SESSION->logincount > $max_logins) {
3466 unset($SESSION->wantsurl);
3467 print_error('errortoomanylogins');
3472 * Resets login attempts
3476 function reset_login_count() {
3479 $SESSION->logincount = 0;
3483 * Determines if the currently logged in user is in editing mode.
3484 * Note: originally this function had $userid parameter - it was not usable anyway
3486 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3487 * @todo Deprecated function remove when ready
3490 * @uses DEBUG_DEVELOPER
3493 function isediting() {
3495 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3496 return $PAGE->user_is_editing();
3500 * Determines if the logged in user is currently moving an activity
3503 * @param int $courseid The id of the course being tested
3506 function ismoving($courseid) {
3509 if (!empty($USER->activitycopy)) {
3510 return ($USER->activitycopycourse == $courseid);
3516 * Returns a persons full name
3518 * Given an object containing firstname and lastname
3519 * values, this function returns a string with the
3520 * full name of the person.
3521 * The result may depend on system settings
3522 * or language. 'override' will force both names
3523 * to be used even if system settings specify one.
3527 * @param object $user A {@link $USER} object to get full name of
3528 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3531 function fullname($user, $override=false) {
3532 global $CFG, $SESSION;
3534 if (!isset($user->firstname) and !isset($user->lastname)) {
3539 if (!empty($CFG->forcefirstname)) {
3540 $user->firstname = $CFG->forcefirstname;
3542 if (!empty($CFG->forcelastname)) {
3543 $user->lastname = $CFG->forcelastname;
3547 if (!empty($SESSION->fullnamedisplay)) {
3548 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3551 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3552 return $user->firstname .' '. $user->lastname;
3554 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3555 return $user->lastname .' '. $user->firstname;
3557 } else if ($CFG->fullnamedisplay == 'firstname') {
3559 return get_string('fullnamedisplay', '', $user);
3561 return $user->firstname;
3565 return get_string('fullnamedisplay', '', $user);
3569 * Checks if current user is shown any extra fields when listing users.
3570 * @param object $context Context
3571 * @param array $already Array of fields that we're going to show anyway
3572 * so don't bother listing them
3573 * @return array Array of field names from user table, not including anything
3574 * listed in $already
3576 function get_extra_user_fields($context, $already = array()) {
3579 // Only users with permission get the extra fields
3580 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3584 // Split showuseridentity on comma
3585 if (empty($CFG->showuseridentity)) {
3586 // Explode gives wrong result with empty string
3589 $extra = explode(',', $CFG->showuseridentity);
3592 foreach ($extra as $key => $field) {
3593 if (in_array($field, $already)) {
3594 unset($extra[$key]);
3599 // For consistency, if entries are removed from array, renumber it
3600 // so they are numbered as you would expect
3601 $extra = array_merge($extra);
3607 * If the current user is to be shown extra user fields when listing or
3608 * selecting users, returns a string suitable for including in an SQL select
3609 * clause to retrieve those fields.
3610 * @param object $context Context
3611 * @param string $alias Alias of user table, e.g. 'u' (default none)
3612 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3613 * @param array $already Array of fields that we're going to include anyway
3614 * so don't list them (default none)
3615 * @return string Partial SQL select clause, beginning with comma, for example
3616 * ',u.idnumber,u.department' unless it is blank
3618 function get_extra_user_fields_sql($context, $alias='', $prefix='',
3619 $already = array()) {
3620 $fields = get_extra_user_fields($context, $already);
3622 // Add punctuation for alias
3623 if ($alias !== '') {
3626 foreach ($fields as $field) {
3627 $result .= ', ' . $alias . $field;
3629 $result .= ' AS ' . $prefix . $field;
3636 * Returns the display name of a field in the user table. Works for most fields
3637 * that are commonly displayed to users.
3638 * @param string $field Field name, e.g. 'phone1'
3639 * @return string Text description taken from language file, e.g. 'Phone number'
3641 function get_user_field_name($field) {
3642 // Some fields have language strings which are not the same as field name
3644 case 'phone1' : return get_string('phone');
3646 // Otherwise just use the same lang string
3647 return get_string($field);
3651 * Returns whether a given authentication plugin exists.
3654 * @param string $auth Form of authentication to check for. Defaults to the
3655 * global setting in {@link $CFG}.
3656 * @return boolean Whether the plugin is available.
3658 function exists_auth_plugin($auth) {
3661 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3662 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3668 * Checks if a given plugin is in the list of enabled authentication plugins.