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') {
2120 $localewincharset = get_string('localewincharset', 'langconfig');
2121 $format = textlib::convert($format, 'utf-8', $localewincharset);
2122 $datestring = strftime($format, $date);
2123 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2125 $datestring = strftime($format, $date);
2128 if ($CFG->ostype == 'WINDOWS') {
2129 $localewincharset = get_string('localewincharset', 'langconfig');
2130 $format = textlib::convert($format, 'utf-8', $localewincharset);
2131 $datestring = gmstrftime($format, $date);
2132 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2134 $datestring = gmstrftime($format, $date);
2141 * Given a $time timestamp in GMT (seconds since epoch),
2142 * returns an array that represents the date in user time
2147 * @param int $time Timestamp in GMT
2148 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2149 * dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
2150 * @return array An array that represents the date in user time
2152 function usergetdate($time, $timezone=99) {
2154 //save input timezone, required for dst offset check.
2155 $passedtimezone = $timezone;
2157 $timezone = get_user_timezone_offset($timezone);
2159 if (abs($timezone) > 13) { // Server time
2160 return getdate($time);
2163 //add daylight saving offset for string timezones only, as we can't get dst for
2164 //float values. if timezone is 99 (user default timezone), then try update dst.
2165 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2166 $time += dst_offset_on($time, $passedtimezone);
2169 $time += intval((float)$timezone * HOURSECS);
2171 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2173 //be careful to ensure the returned array matches that produced by getdate() above
2176 $getdate['weekday'],
2183 $getdate['minutes'],
2185 ) = explode('_', $datestring);
2187 // set correct datatype to match with getdate()
2188 $getdate['seconds'] = (int)$getdate['seconds'];
2189 $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
2190 $getdate['year'] = (int)$getdate['year'];
2191 $getdate['mon'] = (int)$getdate['mon'];
2192 $getdate['wday'] = (int)$getdate['wday'];
2193 $getdate['mday'] = (int)$getdate['mday'];
2194 $getdate['hours'] = (int)$getdate['hours'];
2195 $getdate['minutes'] = (int)$getdate['minutes'];
2200 * Given a GMT timestamp (seconds since epoch), offsets it by
2201 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2206 * @param int $date Timestamp in GMT
2207 * @param float|int|string $timezone timezone to calculate GMT time offset before
2208 * calculating user time, 99 is default user timezone
2209 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2212 function usertime($date, $timezone=99) {
2214 $timezone = get_user_timezone_offset($timezone);
2216 if (abs($timezone) > 13) {
2219 return $date - (int)($timezone * HOURSECS);
2223 * Given a time, return the GMT timestamp of the most recent midnight
2224 * for the current user.
2228 * @param int $date Timestamp in GMT
2229 * @param float|int|string $timezone timezone to calculate GMT time offset before
2230 * calculating user midnight time, 99 is default user timezone
2231 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2232 * @return int Returns a GMT timestamp
2234 function usergetmidnight($date, $timezone=99) {
2236 $userdate = usergetdate($date, $timezone);
2238 // Time of midnight of this user's day, in GMT
2239 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2244 * Returns a string that prints the user's timezone
2248 * @param float|int|string $timezone timezone to calculate GMT time offset before
2249 * calculating user timezone, 99 is default user timezone
2250 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2253 function usertimezone($timezone=99) {
2255 $tz = get_user_timezone($timezone);
2257 if (!is_float($tz)) {
2261 if(abs($tz) > 13) { // Server time
2262 return get_string('serverlocaltime');
2265 if($tz == intval($tz)) {
2266 // Don't show .0 for whole hours
2283 * Returns a float which represents the user's timezone difference from GMT in hours
2284 * Checks various settings and picks the most dominant of those which have a value
2288 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2289 * 99 is default user timezone
2290 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2293 function get_user_timezone_offset($tz = 99) {
2297 $tz = get_user_timezone($tz);
2299 if (is_float($tz)) {
2302 $tzrecord = get_timezone_record($tz);
2303 if (empty($tzrecord)) {
2306 return (float)$tzrecord->gmtoff / HOURMINS;
2311 * Returns an int which represents the systems's timezone difference from GMT in seconds
2315 * @param float|int|string $tz timezone for which offset is required.
2316 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2317 * @return int|bool if found, false is timezone 99 or error
2319 function get_timezone_offset($tz) {
2326 if (is_numeric($tz)) {
2327 return intval($tz * 60*60);
2330 if (!$tzrecord = get_timezone_record($tz)) {
2333 return intval($tzrecord->gmtoff * 60);
2337 * Returns a float or a string which denotes the user's timezone
2338 * 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)
2339 * means that for this timezone there are also DST rules to be taken into account
2340 * Checks various settings and picks the most dominant of those which have a value
2344 * @param float|int|string $tz timezone to calculate GMT time offset before
2345 * calculating user timezone, 99 is default user timezone
2346 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2347 * @return float|string
2349 function get_user_timezone($tz = 99) {
2354 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2355 isset($USER->timezone) ? $USER->timezone : 99,
2356 isset($CFG->timezone) ? $CFG->timezone : 99,
2361 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array
2362 while(((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2363 $tz = $next['value'];
2365 return is_numeric($tz) ? (float) $tz : $tz;
2369 * Returns cached timezone record for given $timezonename
2372 * @param string $timezonename name of the timezone
2373 * @return stdClass|bool timezonerecord or false
2375 function get_timezone_record($timezonename) {
2377 static $cache = NULL;
2379 if ($cache === NULL) {
2383 if (isset($cache[$timezonename])) {
2384 return $cache[$timezonename];
2387 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2388 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2392 * Build and store the users Daylight Saving Time (DST) table
2395 * @param int $from_year Start year for the table, defaults to 1971
2396 * @param int $to_year End year for the table, defaults to 2035
2397 * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
2400 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2401 global $CFG, $SESSION, $DB;
2403 $usertz = get_user_timezone($strtimezone);
2405 if (is_float($usertz)) {
2406 // Trivial timezone, no DST
2410 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2411 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2412 unset($SESSION->dst_offsets);
2413 unset($SESSION->dst_range);
2416 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2417 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2418 // This will be the return path most of the time, pretty light computationally
2422 // Reaching here means we either need to extend our table or create it from scratch
2424 // Remember which TZ we calculated these changes for
2425 $SESSION->dst_offsettz = $usertz;
2427 if(empty($SESSION->dst_offsets)) {
2428 // If we 're creating from scratch, put the two guard elements in there
2429 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2431 if(empty($SESSION->dst_range)) {
2432 // If creating from scratch
2433 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2434 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2436 // Fill in the array with the extra years we need to process
2437 $yearstoprocess = array();
2438 for($i = $from; $i <= $to; ++$i) {
2439 $yearstoprocess[] = $i;
2442 // Take note of which years we have processed for future calls
2443 $SESSION->dst_range = array($from, $to);
2446 // If needing to extend the table, do the same
2447 $yearstoprocess = array();
2449 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2450 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2452 if($from < $SESSION->dst_range[0]) {
2453 // Take note of which years we need to process and then note that we have processed them for future calls
2454 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2455 $yearstoprocess[] = $i;
2457 $SESSION->dst_range[0] = $from;
2459 if($to > $SESSION->dst_range[1]) {
2460 // Take note of which years we need to process and then note that we have processed them for future calls
2461 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2462 $yearstoprocess[] = $i;
2464 $SESSION->dst_range[1] = $to;
2468 if(empty($yearstoprocess)) {
2469 // This means that there was a call requesting a SMALLER range than we have already calculated
2473 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2474 // Also, the array is sorted in descending timestamp order!
2478 static $presets_cache = array();
2479 if (!isset($presets_cache[$usertz])) {
2480 $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');
2482 if(empty($presets_cache[$usertz])) {
2486 // Remove ending guard (first element of the array)
2487 reset($SESSION->dst_offsets);
2488 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2490 // Add all required change timestamps
2491 foreach($yearstoprocess as $y) {
2492 // Find the record which is in effect for the year $y
2493 foreach($presets_cache[$usertz] as $year => $preset) {
2499 $changes = dst_changes_for_year($y, $preset);
2501 if($changes === NULL) {
2504 if($changes['dst'] != 0) {
2505 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2507 if($changes['std'] != 0) {
2508 $SESSION->dst_offsets[$changes['std']] = 0;
2512 // Put in a guard element at the top
2513 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2514 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2517 krsort($SESSION->dst_offsets);
2523 * Calculates the required DST change and returns a Timestamp Array
2529 * @param int|string $year Int or String Year to focus on
2530 * @param object $timezone Instatiated Timezone object
2531 * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
2533 function dst_changes_for_year($year, $timezone) {
2535 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2539 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2540 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2542 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2543 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2545 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2546 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2548 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2549 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2550 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2552 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2553 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2555 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2559 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2560 * - Note: Daylight saving only works for string timezones and not for float.
2564 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2565 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2566 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2569 function dst_offset_on($time, $strtimezone = NULL) {
2572 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2576 reset($SESSION->dst_offsets);
2577 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2578 if($from <= $time) {
2583 // This is the normal return path
2584 if($offset !== NULL) {
2588 // Reaching this point means we haven't calculated far enough, do it now:
2589 // Calculate extra DST changes if needed and recurse. The recursion always
2590 // moves toward the stopping condition, so will always end.
2593 // We need a year smaller than $SESSION->dst_range[0]
2594 if($SESSION->dst_range[0] == 1971) {
2597 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2598 return dst_offset_on($time, $strtimezone);
2601 // We need a year larger than $SESSION->dst_range[1]
2602 if($SESSION->dst_range[1] == 2035) {
2605 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2606 return dst_offset_on($time, $strtimezone);
2611 * Calculates when the day appears in specific month
2615 * @param int $startday starting day of the month
2616 * @param int $weekday The day when week starts (normally taken from user preferences)
2617 * @param int $month The month whose day is sought
2618 * @param int $year The year of the month whose day is sought
2621 function find_day_in_month($startday, $weekday, $month, $year) {
2623 $daysinmonth = days_in_month($month, $year);
2625 if($weekday == -1) {
2626 // Don't care about weekday, so return:
2627 // abs($startday) if $startday != -1
2628 // $daysinmonth otherwise
2629 return ($startday == -1) ? $daysinmonth : abs($startday);
2632 // From now on we 're looking for a specific weekday
2634 // Give "end of month" its actual value, since we know it
2635 if($startday == -1) {
2636 $startday = -1 * $daysinmonth;
2639 // Starting from day $startday, the sign is the direction
2643 $startday = abs($startday);
2644 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2646 // This is the last such weekday of the month
2647 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2648 if($lastinmonth > $daysinmonth) {
2652 // Find the first such weekday <= $startday
2653 while($lastinmonth > $startday) {
2657 return $lastinmonth;
2662 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2664 $diff = $weekday - $indexweekday;
2669 // This is the first such weekday of the month equal to or after $startday
2670 $firstfromindex = $startday + $diff;
2672 return $firstfromindex;
2678 * Calculate the number of days in a given month
2682 * @param int $month The month whose day count is sought
2683 * @param int $year The year of the month whose day count is sought
2686 function days_in_month($month, $year) {
2687 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2691 * Calculate the position in the week of a specific calendar day
2695 * @param int $day The day of the date whose position in the week is sought
2696 * @param int $month The month of the date whose position in the week is sought
2697 * @param int $year The year of the date whose position in the week is sought
2700 function dayofweek($day, $month, $year) {
2701 // I wonder if this is any different from
2702 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2703 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2706 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2709 * Returns full login url.
2711 * @return string login url
2713 function get_login_url() {
2716 $url = "$CFG->wwwroot/login/index.php";
2718 if (!empty($CFG->loginhttps)) {
2719 $url = str_replace('http:', 'https:', $url);
2726 * This function checks that the current user is logged in and has the
2727 * required privileges
2729 * This function checks that the current user is logged in, and optionally
2730 * whether they are allowed to be in a particular course and view a particular
2732 * If they are not logged in, then it redirects them to the site login unless
2733 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2734 * case they are automatically logged in as guests.
2735 * If $courseid is given and the user is not enrolled in that course then the
2736 * user is redirected to the course enrolment page.
2737 * If $cm is given and the course module is hidden and the user is not a teacher
2738 * in the course then the user is redirected to the course home page.
2740 * When $cm parameter specified, this function sets page layout to 'module'.
2741 * You need to change it manually later if some other layout needed.
2743 * @package core_access
2746 * @param mixed $courseorid id of the course or course object
2747 * @param bool $autologinguest default true
2748 * @param object $cm course module object
2749 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2750 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2751 * in order to keep redirects working properly. MDL-14495
2752 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2753 * @return mixed Void, exit, and die depending on path
2755 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2756 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2758 // setup global $COURSE, themes, language and locale
2759 if (!empty($courseorid)) {
2760 if (is_object($courseorid)) {
2761 $course = $courseorid;
2762 } else if ($courseorid == SITEID) {
2763 $course = clone($SITE);
2765 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2768 if ($cm->course != $course->id) {
2769 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2771 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2772 if (!($cm instanceof cm_info)) {
2773 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2774 // db queries so this is not really a performance concern, however it is obviously
2775 // better if you use get_fast_modinfo to get the cm before calling this.
2776 $modinfo = get_fast_modinfo($course);
2777 $cm = $modinfo->get_cm($cm->id);
2779 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2780 $PAGE->set_pagelayout('incourse');
2782 $PAGE->set_course($course); // set's up global $COURSE
2785 // do not touch global $COURSE via $PAGE->set_course(),
2786 // the reasons is we need to be able to call require_login() at any time!!
2789 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2793 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2794 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2795 // risk leading the user back to the AJAX request URL.
2796 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2797 $setwantsurltome = false;
2800 // If the user is not even logged in yet then make sure they are
2801 if (!isloggedin()) {
2802 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2803 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2804 // misconfigured site guest, just redirect to login page
2805 redirect(get_login_url());
2806 exit; // never reached
2808 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2809 complete_user_login($guest);
2810 $USER->autologinguest = true;
2811 $SESSION->lang = $lang;
2813 //NOTE: $USER->site check was obsoleted by session test cookie,
2814 // $USER->confirmed test is in login/index.php
2815 if ($preventredirect) {
2816 throw new require_login_exception('You are not logged in');
2819 if ($setwantsurltome) {
2820 $SESSION->wantsurl = qualified_me();
2822 if (!empty($_SERVER['HTTP_REFERER'])) {
2823 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2825 redirect(get_login_url());
2826 exit; // never reached
2830 // loginas as redirection if needed
2831 if ($course->id != SITEID and session_is_loggedinas()) {
2832 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2833 if ($USER->loginascontext->instanceid != $course->id) {
2834 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2839 // check whether the user should be changing password (but only if it is REALLY them)
2840 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2841 $userauth = get_auth_plugin($USER->auth);
2842 if ($userauth->can_change_password() and !$preventredirect) {
2843 if ($setwantsurltome) {
2844 $SESSION->wantsurl = qualified_me();
2846 if ($changeurl = $userauth->change_password_url()) {
2847 //use plugin custom url
2848 redirect($changeurl);
2850 //use moodle internal method
2851 if (empty($CFG->loginhttps)) {
2852 redirect($CFG->wwwroot .'/login/change_password.php');
2854 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2855 redirect($wwwroot .'/login/change_password.php');
2859 print_error('nopasswordchangeforced', 'auth');
2863 // Check that the user account is properly set up
2864 if (user_not_fully_set_up($USER)) {
2865 if ($preventredirect) {
2866 throw new require_login_exception('User not fully set-up');
2868 if ($setwantsurltome) {
2869 $SESSION->wantsurl = qualified_me();
2871 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2874 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2877 // Do not bother admins with any formalities
2878 if (is_siteadmin()) {
2879 //set accesstime or the user will appear offline which messes up messaging
2880 user_accesstime_log($course->id);
2884 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2885 if (!$USER->policyagreed and !is_siteadmin()) {
2886 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2887 if ($preventredirect) {
2888 throw new require_login_exception('Policy not agreed');
2890 if ($setwantsurltome) {
2891 $SESSION->wantsurl = qualified_me();
2893 redirect($CFG->wwwroot .'/user/policy.php');
2894 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2895 if ($preventredirect) {
2896 throw new require_login_exception('Policy not agreed');
2898 if ($setwantsurltome) {
2899 $SESSION->wantsurl = qualified_me();
2901 redirect($CFG->wwwroot .'/user/policy.php');
2905 // Fetch the system context, the course context, and prefetch its child contexts
2906 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2907 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2909 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2914 // If the site is currently under maintenance, then print a message
2915 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2916 if ($preventredirect) {
2917 throw new require_login_exception('Maintenance in progress');
2920 print_maintenance_message();
2923 // make sure the course itself is not hidden
2924 if ($course->id == SITEID) {
2925 // frontpage can not be hidden
2927 if (is_role_switched($course->id)) {
2928 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2930 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2931 // originally there was also test of parent category visibility,
2932 // BUT is was very slow in complex queries involving "my courses"
2933 // now it is also possible to simply hide all courses user is not enrolled in :-)
2934 if ($preventredirect) {
2935 throw new require_login_exception('Course is hidden');
2937 // We need to override the navigation URL as the course won't have
2938 // been added to the navigation and thus the navigation will mess up
2939 // when trying to find it.
2940 navigation_node::override_active_url(new moodle_url('/'));
2941 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2946 // is the user enrolled?
2947 if ($course->id == SITEID) {
2948 // everybody is enrolled on the frontpage
2951 if (session_is_loggedinas()) {
2952 // Make sure the REAL person can access this course first
2953 $realuser = session_get_realuser();
2954 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2955 if ($preventredirect) {
2956 throw new require_login_exception('Invalid course login-as access');
2958 echo $OUTPUT->header();
2959 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2965 if (is_role_switched($course->id)) {
2966 // ok, user had to be inside this course before the switch
2969 } else if (is_viewing($coursecontext, $USER)) {
2970 // ok, no need to mess with enrol
2974 if (isset($USER->enrol['enrolled'][$course->id])) {
2975 if ($USER->enrol['enrolled'][$course->id] > time()) {
2977 if (isset($USER->enrol['tempguest'][$course->id])) {
2978 unset($USER->enrol['tempguest'][$course->id]);
2979 remove_temp_course_roles($coursecontext);
2983 unset($USER->enrol['enrolled'][$course->id]);
2986 if (isset($USER->enrol['tempguest'][$course->id])) {
2987 if ($USER->enrol['tempguest'][$course->id] == 0) {
2989 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2993 unset($USER->enrol['tempguest'][$course->id]);
2994 remove_temp_course_roles($coursecontext);
3001 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3002 if ($until !== false) {
3003 // active participants may always access, a timestamp in the future, 0 (always) or false.
3005 $until = ENROL_MAX_TIMESTAMP;
3007 $USER->enrol['enrolled'][$course->id] = $until;
3011 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
3012 $enrols = enrol_get_plugins(true);
3013 // first ask all enabled enrol instances in course if they want to auto enrol user
3014 foreach($instances as $instance) {
3015 if (!isset($enrols[$instance->enrol])) {
3018 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3019 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3020 if ($until !== false) {
3022 $until = ENROL_MAX_TIMESTAMP;
3024 $USER->enrol['enrolled'][$course->id] = $until;
3029 // if not enrolled yet try to gain temporary guest access
3031 foreach($instances as $instance) {
3032 if (!isset($enrols[$instance->enrol])) {
3035 // Get a duration for the guest access, a timestamp in the future or false.
3036 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3037 if ($until !== false and $until > time()) {
3038 $USER->enrol['tempguest'][$course->id] = $until;
3049 if ($preventredirect) {
3050 throw new require_login_exception('Not enrolled');
3052 if ($setwantsurltome) {
3053 $SESSION->wantsurl = qualified_me();
3055 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3059 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
3060 // conditional availability, etc
3061 if ($cm && !$cm->uservisible) {
3062 if ($preventredirect) {
3063 throw new require_login_exception('Activity is hidden');
3065 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
3068 // Finally access granted, update lastaccess times
3069 user_accesstime_log($course->id);
3074 * This function just makes sure a user is logged out.
3076 * @package core_access
3078 function require_logout() {
3084 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
3086 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
3087 foreach($authsequence as $authname) {
3088 $authplugin = get_auth_plugin($authname);
3089 $authplugin->prelogout_hook();
3093 events_trigger('user_logout', $params);
3094 session_get_instance()->terminate_current();
3099 * Weaker version of require_login()
3101 * This is a weaker version of {@link require_login()} which only requires login
3102 * when called from within a course rather than the site page, unless
3103 * the forcelogin option is turned on.
3104 * @see require_login()
3106 * @package core_access
3109 * @param mixed $courseorid The course object or id in question
3110 * @param bool $autologinguest Allow autologin guests if that is wanted
3111 * @param object $cm Course activity module if known
3112 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3113 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3114 * in order to keep redirects working properly. MDL-14495
3115 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3118 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
3119 global $CFG, $PAGE, $SITE;
3120 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3121 or (!is_object($courseorid) and $courseorid == SITEID);
3122 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3123 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
3124 // db queries so this is not really a performance concern, however it is obviously
3125 // better if you use get_fast_modinfo to get the cm before calling this.
3126 if (is_object($courseorid)) {
3127 $course = $courseorid;
3129 $course = clone($SITE);
3131 $modinfo = get_fast_modinfo($course);
3132 $cm = $modinfo->get_cm($cm->id);
3134 if (!empty($CFG->forcelogin)) {
3135 // login required for both SITE and courses
3136 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3138 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3139 // always login for hidden activities
3140 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3142 } else if ($issite) {
3143 //login for SITE not required
3144 if ($cm and empty($cm->visible)) {
3145 // hidden activities are not accessible without login
3146 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3147 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3148 // not-logged-in users do not have any group membership
3149 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3151 // We still need to instatiate PAGE vars properly so that things
3152 // that rely on it like navigation function correctly.
3153 if (!empty($courseorid)) {
3154 if (is_object($courseorid)) {
3155 $course = $courseorid;
3157 $course = clone($SITE);
3160 if ($cm->course != $course->id) {
3161 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3163 $PAGE->set_cm($cm, $course);
3164 $PAGE->set_pagelayout('incourse');
3166 $PAGE->set_course($course);
3169 // If $PAGE->course, and hence $PAGE->context, have not already been set
3170 // up properly, set them up now.
3171 $PAGE->set_course($PAGE->course);
3173 //TODO: verify conditional activities here
3174 user_accesstime_log(SITEID);
3179 // course login always required
3180 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3185 * Require key login. Function terminates with error if key not found or incorrect.
3191 * @uses NO_MOODLE_COOKIES
3192 * @uses PARAM_ALPHANUM
3193 * @param string $script unique script identifier
3194 * @param int $instance optional instance id
3195 * @return int Instance ID
3197 function require_user_key_login($script, $instance=null) {
3198 global $USER, $SESSION, $CFG, $DB;
3200 if (!NO_MOODLE_COOKIES) {
3201 print_error('sessioncookiesdisable');
3205 @session_write_close();
3207 $keyvalue = required_param('key', PARAM_ALPHANUM);
3209 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3210 print_error('invalidkey');
3213 if (!empty($key->validuntil) and $key->validuntil < time()) {
3214 print_error('expiredkey');
3217 if ($key->iprestriction) {
3218 $remoteaddr = getremoteaddr(null);
3219 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3220 print_error('ipmismatch');
3224 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
3225 print_error('invaliduserid');
3228 /// emulate normal session
3229 enrol_check_plugins($user);
3230 session_set_user($user);
3232 /// note we are not using normal login
3233 if (!defined('USER_KEY_LOGIN')) {
3234 define('USER_KEY_LOGIN', true);
3237 /// return instance id - it might be empty
3238 return $key->instance;
3242 * Creates a new private user access key.
3245 * @param string $script unique target identifier
3246 * @param int $userid
3247 * @param int $instance optional instance id
3248 * @param string $iprestriction optional ip restricted access
3249 * @param timestamp $validuntil key valid only until given data
3250 * @return string access key value
3252 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3255 $key = new stdClass();
3256 $key->script = $script;
3257 $key->userid = $userid;
3258 $key->instance = $instance;
3259 $key->iprestriction = $iprestriction;
3260 $key->validuntil = $validuntil;
3261 $key->timecreated = time();
3263 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
3264 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3266 $key->value = md5($userid.'_'.time().random_string(40));
3268 $DB->insert_record('user_private_key', $key);
3273 * Delete the user's new private user access keys for a particular script.
3276 * @param string $script unique target identifier
3277 * @param int $userid
3280 function delete_user_key($script,$userid) {
3282 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3286 * Gets a private user access key (and creates one if one doesn't exist).
3289 * @param string $script unique target identifier
3290 * @param int $userid
3291 * @param int $instance optional instance id
3292 * @param string $iprestriction optional ip restricted access
3293 * @param timestamp $validuntil key valid only until given data
3294 * @return string access key value
3296 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3299 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3300 'instance'=>$instance, 'iprestriction'=>$iprestriction,
3301 'validuntil'=>$validuntil))) {
3304 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3310 * Modify the user table by setting the currently logged in user's
3311 * last login to now.
3315 * @return bool Always returns true
3317 function update_user_login_times() {
3320 if (isguestuser()) {
3321 // Do not update guest access times/ips for performance.
3327 $user = new stdClass();
3328 $user->id = $USER->id;
3330 // Make sure all users that logged in have some firstaccess.
3331 if ($USER->firstaccess == 0) {
3332 $USER->firstaccess = $user->firstaccess = $now;
3335 // Store the previous current as lastlogin.
3336 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3338 $USER->currentlogin = $user->currentlogin = $now;
3340 // Function user_accesstime_log() may not update immediately, better do it here.
3341 $USER->lastaccess = $user->lastaccess = $now;
3342 $USER->lastip = $user->lastip = getremoteaddr();
3344 $DB->update_record('user', $user);
3349 * Determines if a user has completed setting up their account.
3351 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3354 function user_not_fully_set_up($user) {
3355 if (isguestuser($user)) {
3358 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3362 * Check whether the user has exceeded the bounce threshold
3366 * @param user $user A {@link $USER} object
3367 * @return bool true=>User has exceeded bounce threshold
3369 function over_bounce_threshold($user) {
3372 if (empty($CFG->handlebounces)) {
3376 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3380 // set sensible defaults
3381 if (empty($CFG->minbounces)) {
3382 $CFG->minbounces = 10;
3384 if (empty($CFG->bounceratio)) {
3385 $CFG->bounceratio = .20;
3389 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3390 $bouncecount = $bounce->value;
3392 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3393 $sendcount = $send->value;
3395 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3399 * Used to increment or reset email sent count
3402 * @param user $user object containing an id
3403 * @param bool $reset will reset the count to 0
3406 function set_send_count($user,$reset=false) {
3409 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3413 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3414 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3415 $DB->update_record('user_preferences', $pref);
3417 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3419 $pref = new stdClass();
3420 $pref->name = 'email_send_count';
3422 $pref->userid = $user->id;
3423 $DB->insert_record('user_preferences', $pref, false);
3428 * Increment or reset user's email bounce count
3431 * @param user $user object containing an id
3432 * @param bool $reset will reset the count to 0
3434 function set_bounce_count($user,$reset=false) {
3437 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3438 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3439 $DB->update_record('user_preferences', $pref);
3441 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3443 $pref = new stdClass();
3444 $pref->name = 'email_bounce_count';
3446 $pref->userid = $user->id;
3447 $DB->insert_record('user_preferences', $pref, false);
3452 * Keeps track of login attempts
3456 function update_login_count() {
3461 if (empty($SESSION->logincount)) {
3462 $SESSION->logincount = 1;
3464 $SESSION->logincount++;
3467 if ($SESSION->logincount > $max_logins) {
3468 unset($SESSION->wantsurl);
3469 print_error('errortoomanylogins');
3474 * Resets login attempts
3478 function reset_login_count() {
3481 $SESSION->logincount = 0;
3485 * Determines if the currently logged in user is in editing mode.
3486 * Note: originally this function had $userid parameter - it was not usable anyway
3488 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3489 * @todo Deprecated function remove when ready
3492 * @uses DEBUG_DEVELOPER
3495 function isediting() {
3497 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3498 return $PAGE->user_is_editing();
3502 * Determines if the logged in user is currently moving an activity
3505 * @param int $courseid The id of the course being tested
3508 function ismoving($courseid) {
3511 if (!empty($USER->activitycopy)) {
3512 return ($USER->activitycopycourse == $courseid);
3518 * Returns a persons full name
3520 * Given an object containing firstname and lastname
3521 * values, this function returns a string with the
3522 * full name of the person.
3523 * The result may depend on system settings
3524 * or language. 'override' will force both names
3525 * to be used even if system settings specify one.
3529 * @param object $user A {@link $USER} object to get full name of
3530 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3533 function fullname($user, $override=false) {
3534 global $CFG, $SESSION;
3536 if (!isset($user->firstname) and !isset($user->lastname)) {
3541 if (!empty($CFG->forcefirstname)) {
3542 $user->firstname = $CFG->forcefirstname;
3544 if (!empty($CFG->forcelastname)) {
3545 $user->lastname = $CFG->forcelastname;
3549 if (!empty($SESSION->fullnamedisplay)) {
3550 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3553 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3554 return $user->firstname .' '. $user->lastname;
3556 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3557 return $user->lastname .' '. $user->firstname;
3559 } else if ($CFG->fullnamedisplay == 'firstname') {
3561 return get_string('fullnamedisplay', '', $user);
3563 return $user->firstname;
3567 return get_string('fullnamedisplay', '', $user);
3571 * Checks if current user is shown any extra fields when listing users.
3572 * @param object $context Context
3573 * @param array $already Array of fields that we're going to show anyway
3574 * so don't bother listing them
3575 * @return array Array of field names from user table, not including anything
3576 * listed in $already
3578 function get_extra_user_fields($context, $already = array()) {
3581 // Only users with permission get the extra fields
3582 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3586 // Split showuseridentity on comma
3587 if (empty($CFG->showuseridentity)) {
3588 // Explode gives wrong result with empty string
3591 $extra = explode(',', $CFG->showuseridentity);
3594 foreach ($extra as $key => $field) {
3595 if (in_array($field, $already)) {
3596 unset($extra[$key]);
3601 // For consistency, if entries are removed from array, renumber it
3602 // so they are numbered as you would expect
3603 $extra = array_merge($extra);
3609 * If the current user is to be shown extra user fields when listing or
3610 * selecting users, returns a string suitable for including in an SQL select
3611 * clause to retrieve those fields.
3612 * @param object $context Context
3613 * @param string $alias Alias of user table, e.g. 'u' (default none)
3614 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3615 * @param array $already Array of fields that we're going to include anyway
3616 * so don't list them (default none)
3617 * @return string Partial SQL select clause, beginning with comma, for example
3618 * ',u.idnumber,u.department' unless it is blank
3620 function get_extra_user_fields_sql($context, $alias='', $prefix='',
3621 $already = array()) {
3622 $fields = get_extra_user_fields($context, $already);
3624 // Add punctuation for alias
3625 if ($alias !== '') {
3628 foreach ($fields as $field) {
3629 $result .= ', ' . $alias . $field;
3631 $result .= ' AS ' . $prefix . $field;
3638 * Returns the display name of a field in the user table. Works for most fields
3639 * that are commonly displayed to users.
3640 * @param string $field Field name, e.g. 'phone1'
3641 * @return string Text description taken from language file, e.g. 'Phone number'
3643 function get_user_field_name($field) {
3644 // Some fields have language strings which are not the same as field name
3646 case 'phone1' : return get_string('phone');
3648 // Otherwise just use the same lang string
3649 return get_string($field);
3653 * Returns whether a given authentication plugin exists.
3656 * @param string $auth Form of authentication to check for. Defaults to the
3657 * global setting in {@link $CFG}.
3658 * @return boolean Whether the plugin is available.
3660 function exists_auth_plugin($auth) {
3663 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3664 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");