3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * moodlelib.php - Moodle main library
21 * Main library file of miscellaneous general-purpose Moodle functions.
22 * Other main libraries:
23 * - weblib.php - functions that produce web output
24 * - datalib.php - functions that access the database
28 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32 defined('MOODLE_INTERNAL') || die();
34 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
36 /// Date and time constants ///
38 * Time constant - the number of seconds in a year
40 define('YEARSECS', 31536000);
43 * Time constant - the number of seconds in a week
45 define('WEEKSECS', 604800);
48 * Time constant - the number of seconds in a day
50 define('DAYSECS', 86400);
53 * Time constant - the number of seconds in an hour
55 define('HOURSECS', 3600);
58 * Time constant - the number of seconds in a minute
60 define('MINSECS', 60);
63 * Time constant - the number of minutes in a day
65 define('DAYMINS', 1440);
68 * Time constant - the number of minutes in an hour
70 define('HOURMINS', 60);
72 /// Parameter constants - every call to optional_param(), required_param() ///
73 /// or clean_param() should have a specified type of parameter. //////////////
78 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
80 define('PARAM_ALPHA', 'alpha');
83 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
84 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
86 define('PARAM_ALPHAEXT', 'alphaext');
89 * PARAM_ALPHANUM - expected numbers and letters only.
91 define('PARAM_ALPHANUM', 'alphanum');
94 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
96 define('PARAM_ALPHANUMEXT', 'alphanumext');
99 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
101 define('PARAM_AUTH', 'auth');
104 * PARAM_BASE64 - Base 64 encoded format
106 define('PARAM_BASE64', 'base64');
109 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
111 define('PARAM_BOOL', 'bool');
114 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
115 * checked against the list of capabilities in the database.
117 define('PARAM_CAPABILITY', 'capability');
120 * PARAM_CLEANHTML - cleans submitted HTML code. use only for text in HTML format. This cleaning may fix xhtml strictness too.
122 define('PARAM_CLEANHTML', 'cleanhtml');
125 * PARAM_EMAIL - an email address following the RFC
127 define('PARAM_EMAIL', 'email');
130 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
132 define('PARAM_FILE', 'file');
135 * PARAM_FLOAT - a real/floating point number.
137 define('PARAM_FLOAT', 'float');
140 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
142 define('PARAM_HOST', 'host');
145 * PARAM_INT - integers only, use when expecting only numbers.
147 define('PARAM_INT', 'int');
150 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
152 define('PARAM_LANG', 'lang');
155 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
157 define('PARAM_LOCALURL', 'localurl');
160 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
162 define('PARAM_NOTAGS', 'notags');
165 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
166 * note: the leading slash is not removed, window drive letter is not allowed
168 define('PARAM_PATH', 'path');
171 * PARAM_PEM - Privacy Enhanced Mail format
173 define('PARAM_PEM', 'pem');
176 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
178 define('PARAM_PERMISSION', 'permission');
181 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
183 define('PARAM_RAW', 'raw');
186 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
188 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
191 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
193 define('PARAM_SAFEDIR', 'safedir');
196 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
198 define('PARAM_SAFEPATH', 'safepath');
201 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
203 define('PARAM_SEQUENCE', 'sequence');
206 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
208 define('PARAM_TAG', 'tag');
211 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
213 define('PARAM_TAGLIST', 'taglist');
216 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
218 define('PARAM_TEXT', 'text');
221 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
223 define('PARAM_THEME', 'theme');
226 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
228 define('PARAM_URL', 'url');
231 * 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!!
233 define('PARAM_USERNAME', 'username');
236 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
238 define('PARAM_STRINGID', 'stringid');
240 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
242 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
243 * It was one of the first types, that is why it is abused so much ;-)
244 * @deprecated since 2.0
246 define('PARAM_CLEAN', 'clean');
249 * PARAM_INTEGER - deprecated alias for PARAM_INT
251 define('PARAM_INTEGER', 'int');
254 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
256 define('PARAM_NUMBER', 'float');
259 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
260 * NOTE: originally alias for PARAM_APLHA
262 define('PARAM_ACTION', 'alphanumext');
265 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
266 * NOTE: originally alias for PARAM_APLHA
268 define('PARAM_FORMAT', 'alphanumext');
271 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
273 define('PARAM_MULTILANG', 'text');
276 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
277 * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
278 * America/Port-au-Prince)
280 define('PARAM_TIMEZONE', 'timezone');
283 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
285 define('PARAM_CLEANFILE', 'file');
288 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
289 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
290 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
291 * NOTE: numbers and underscores are strongly discouraged in plugin names!
293 define('PARAM_COMPONENT', 'component');
296 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
297 * It is usually used together with context id and component.
298 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
300 define('PARAM_AREA', 'area');
303 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
304 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
305 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
307 define('PARAM_PLUGIN', 'plugin');
313 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
315 define('VALUE_REQUIRED', 1);
318 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
320 define('VALUE_OPTIONAL', 2);
323 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
325 define('VALUE_DEFAULT', 0);
328 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
330 define('NULL_NOT_ALLOWED', false);
333 * NULL_ALLOWED - the parameter can be set to null in the database
335 define('NULL_ALLOWED', true);
339 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
341 define('PAGE_COURSE_VIEW', 'course-view');
343 /** Get remote addr constant */
344 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
345 /** Get remote addr constant */
346 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
348 /// Blog access level constant declaration ///
349 define ('BLOG_USER_LEVEL', 1);
350 define ('BLOG_GROUP_LEVEL', 2);
351 define ('BLOG_COURSE_LEVEL', 3);
352 define ('BLOG_SITE_LEVEL', 4);
353 define ('BLOG_GLOBAL_LEVEL', 5);
358 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
359 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
360 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
362 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
364 define('TAG_MAX_LENGTH', 50);
366 /// Password policy constants ///
367 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
368 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
369 define ('PASSWORD_DIGITS', '0123456789');
370 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
372 /// Feature constants ///
373 // Used for plugin_supports() to report features that are, or are not, supported by a module.
375 /** True if module can provide a grade */
376 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
377 /** True if module supports outcomes */
378 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
379 /** True if module supports advanced grading methods */
380 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
382 /** True if module has code to track whether somebody viewed it */
383 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
384 /** True if module has custom completion rules */
385 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
387 /** True if module has no 'view' page (like label) */
388 define('FEATURE_NO_VIEW_LINK', 'viewlink');
389 /** True if module supports outcomes */
390 define('FEATURE_IDNUMBER', 'idnumber');
391 /** True if module supports groups */
392 define('FEATURE_GROUPS', 'groups');
393 /** True if module supports groupings */
394 define('FEATURE_GROUPINGS', 'groupings');
395 /** True if module supports groupmembersonly */
396 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
398 /** Type of module */
399 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
400 /** True if module supports intro editor */
401 define('FEATURE_MOD_INTRO', 'mod_intro');
402 /** True if module has default completion */
403 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
405 define('FEATURE_COMMENT', 'comment');
407 define('FEATURE_RATE', 'rate');
408 /** True if module supports backup/restore of moodle2 format */
409 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
411 /** True if module can show description on course main page */
412 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
414 /** Unspecified module archetype */
415 define('MOD_ARCHETYPE_OTHER', 0);
416 /** Resource-like type module */
417 define('MOD_ARCHETYPE_RESOURCE', 1);
418 /** Assignment module archetype */
419 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
420 /** System (not user-addable) module archetype */
421 define('MOD_ARCHETYPE_SYSTEM', 3);
424 * Security token used for allowing access
425 * from external application such as web services.
426 * Scripts do not use any session, performance is relatively
427 * low because we need to load access info in each request.
428 * Scripts are executed in parallel.
430 define('EXTERNAL_TOKEN_PERMANENT', 0);
433 * Security token used for allowing access
434 * of embedded applications, the code is executed in the
435 * active user session. Token is invalidated after user logs out.
436 * Scripts are executed serially - normal session locking is used.
438 define('EXTERNAL_TOKEN_EMBEDDED', 1);
441 * The home page should be the site home
443 define('HOMEPAGE_SITE', 0);
445 * The home page should be the users my page
447 define('HOMEPAGE_MY', 1);
449 * The home page can be chosen by the user
451 define('HOMEPAGE_USER', 2);
454 * Hub directory url (should be moodle.org)
456 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
460 * Moodle.org url (should be moodle.org)
462 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
465 * Moodle mobile app service name
467 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
469 /// PARAMETER HANDLING ////////////////////////////////////////////////////
472 * Returns a particular value for the named variable, taken from
473 * POST or GET. If the parameter doesn't exist then an error is
474 * thrown because we require this variable.
476 * This function should be used to initialise all required values
477 * in a script that are based on parameters. Usually it will be
479 * $id = required_param('id', PARAM_INT);
481 * Please note the $type parameter is now required and the value can not be array.
483 * @param string $parname the name of the page parameter we want
484 * @param string $type expected type of parameter
487 function required_param($parname, $type) {
488 if (func_num_args() != 2 or empty($parname) or empty($type)) {
489 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
491 if (isset($_POST[$parname])) { // POST has precedence
492 $param = $_POST[$parname];
493 } else if (isset($_GET[$parname])) {
494 $param = $_GET[$parname];
496 print_error('missingparam', '', '', $parname);
499 if (is_array($param)) {
500 debugging('Invalid array parameter detected in required_param(): '.$parname);
501 // TODO: switch to fatal error in Moodle 2.3
502 //print_error('missingparam', '', '', $parname);
503 return required_param_array($parname, $type);
506 return clean_param($param, $type);
510 * Returns a particular array value for the named variable, taken from
511 * POST or GET. If the parameter doesn't exist then an error is
512 * thrown because we require this variable.
514 * This function should be used to initialise all required values
515 * in a script that are based on parameters. Usually it will be
517 * $ids = required_param_array('ids', PARAM_INT);
519 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
521 * @param string $parname the name of the page parameter we want
522 * @param string $type expected type of parameter
525 function required_param_array($parname, $type) {
526 if (func_num_args() != 2 or empty($parname) or empty($type)) {
527 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
529 if (isset($_POST[$parname])) { // POST has precedence
530 $param = $_POST[$parname];
531 } else if (isset($_GET[$parname])) {
532 $param = $_GET[$parname];
534 print_error('missingparam', '', '', $parname);
536 if (!is_array($param)) {
537 print_error('missingparam', '', '', $parname);
541 foreach($param as $key=>$value) {
542 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
543 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
546 $result[$key] = clean_param($value, $type);
553 * Returns a particular value for the named variable, taken from
554 * POST or GET, otherwise returning a given default.
556 * This function should be used to initialise all optional values
557 * in a script that are based on parameters. Usually it will be
559 * $name = optional_param('name', 'Fred', PARAM_TEXT);
561 * Please note the $type parameter is now required and the value can not be array.
563 * @param string $parname the name of the page parameter we want
564 * @param mixed $default the default value to return if nothing is found
565 * @param string $type expected type of parameter
568 function optional_param($parname, $default, $type) {
569 if (func_num_args() != 3 or empty($parname) or empty($type)) {
570 throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
572 if (!isset($default)) {
576 if (isset($_POST[$parname])) { // POST has precedence
577 $param = $_POST[$parname];
578 } else if (isset($_GET[$parname])) {
579 $param = $_GET[$parname];
584 if (is_array($param)) {
585 debugging('Invalid array parameter detected in required_param(): '.$parname);
586 // TODO: switch to $default in Moodle 2.3
588 return optional_param_array($parname, $default, $type);
591 return clean_param($param, $type);
595 * Returns a particular array value for the named variable, taken from
596 * POST or GET, otherwise returning a given default.
598 * This function should be used to initialise all optional values
599 * in a script that are based on parameters. Usually it will be
601 * $ids = optional_param('id', array(), PARAM_INT);
603 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
605 * @param string $parname the name of the page parameter we want
606 * @param mixed $default the default value to return if nothing is found
607 * @param string $type expected type of parameter
610 function optional_param_array($parname, $default, $type) {
611 if (func_num_args() != 3 or empty($parname) or empty($type)) {
612 throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
615 if (isset($_POST[$parname])) { // POST has precedence
616 $param = $_POST[$parname];
617 } else if (isset($_GET[$parname])) {
618 $param = $_GET[$parname];
622 if (!is_array($param)) {
623 debugging('optional_param_array() expects array parameters only: '.$parname);
628 foreach($param as $key=>$value) {
629 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
630 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
633 $result[$key] = clean_param($value, $type);
640 * Strict validation of parameter values, the values are only converted
641 * to requested PHP type. Internally it is using clean_param, the values
642 * before and after cleaning must be equal - otherwise
643 * an invalid_parameter_exception is thrown.
644 * Objects and classes are not accepted.
646 * @param mixed $param
647 * @param string $type PARAM_ constant
648 * @param bool $allownull are nulls valid value?
649 * @param string $debuginfo optional debug information
650 * @return mixed the $param value converted to PHP type or invalid_parameter_exception
652 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
653 if (is_null($param)) {
654 if ($allownull == NULL_ALLOWED) {
657 throw new invalid_parameter_exception($debuginfo);
660 if (is_array($param) or is_object($param)) {
661 throw new invalid_parameter_exception($debuginfo);
664 $cleaned = clean_param($param, $type);
665 if ((string)$param !== (string)$cleaned) {
666 // conversion to string is usually lossless
667 throw new invalid_parameter_exception($debuginfo);
674 * Makes sure array contains only the allowed types,
675 * this function does not validate array key names!
677 * $options = clean_param($options, PARAM_INT);
680 * @param array $param the variable array we are cleaning
681 * @param string $type expected format of param after cleaning.
682 * @param bool $recursive clean recursive arrays
685 function clean_param_array(array $param = null, $type, $recursive = false) {
686 $param = (array)$param; // convert null to empty array
687 foreach ($param as $key => $value) {
688 if (is_array($value)) {
690 $param[$key] = clean_param_array($value, $type, true);
692 throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
695 $param[$key] = clean_param($value, $type);
702 * Used by {@link optional_param()} and {@link required_param()} to
703 * clean the variables and/or cast to specific types, based on
706 * $course->format = clean_param($course->format, PARAM_ALPHA);
707 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
710 * @param mixed $param the variable we are cleaning
711 * @param string $type expected format of param after cleaning.
714 function clean_param($param, $type) {
718 if (is_array($param)) {
719 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
720 } else if (is_object($param)) {
721 if (method_exists($param, '__toString')) {
722 $param = $param->__toString();
724 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
729 case PARAM_RAW: // no cleaning at all
730 $param = fix_utf8($param);
733 case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
734 $param = fix_utf8($param);
737 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
738 // this is deprecated!, please use more specific type instead
739 if (is_numeric($param)) {
742 $param = fix_utf8($param);
743 return clean_text($param); // Sweep for scripts, etc
745 case PARAM_CLEANHTML: // clean html fragment
746 $param = fix_utf8($param);
747 $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
751 return (int)$param; // Convert to integer
755 return (float)$param; // Convert to float
757 case PARAM_ALPHA: // Remove everything not a-z
758 return preg_replace('/[^a-zA-Z]/i', '', $param);
760 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
761 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
763 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
764 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
766 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
767 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
769 case PARAM_SEQUENCE: // Remove everything not 0-9,
770 return preg_replace('/[^0-9,]/i', '', $param);
772 case PARAM_BOOL: // Convert to 1 or 0
773 $tempstr = strtolower($param);
774 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
776 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
779 $param = empty($param) ? 0 : 1;
783 case PARAM_NOTAGS: // Strip all tags
784 $param = fix_utf8($param);
785 return strip_tags($param);
787 case PARAM_TEXT: // leave only tags needed for multilang
788 $param = fix_utf8($param);
789 // if the multilang syntax is not correct we strip all tags
790 // because it would break xhtml strict which is required for accessibility standards
791 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
793 if (strpos($param, '</lang>') !== false) {
794 // old and future mutilang syntax
795 $param = strip_tags($param, '<lang>');
796 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
800 foreach ($matches[0] as $match) {
801 if ($match === '</lang>') {
809 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
820 } else if (strpos($param, '</span>') !== false) {
821 // current problematic multilang syntax
822 $param = strip_tags($param, '<span>');
823 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
827 foreach ($matches[0] as $match) {
828 if ($match === '</span>') {
836 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
848 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
849 return strip_tags($param);
851 case PARAM_COMPONENT:
852 // we do not want any guessing here, either the name is correct or not
853 // please note only normalised component names are accepted
854 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
857 if (strpos($param, '__') !== false) {
860 if (strpos($param, 'mod_') === 0) {
861 // module names must not contain underscores because we need to differentiate them from invalid plugin types
862 if (substr_count($param, '_') != 1) {
870 // we do not want any guessing here, either the name is correct or not
871 if (!preg_match('/^[a-z][a-z0-9_]*[a-z0-9]$/', $param)) {
874 if (strpos($param, '__') !== false) {
879 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
880 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
882 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
883 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
885 case PARAM_FILE: // Strip all suspicious characters from filename
886 $param = fix_utf8($param);
887 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
888 $param = preg_replace('~\.\.+~', '', $param);
889 if ($param === '.') {
894 case PARAM_PATH: // Strip all suspicious characters from file path
895 $param = fix_utf8($param);
896 $param = str_replace('\\', '/', $param);
897 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
898 $param = preg_replace('~\.\.+~', '', $param);
899 $param = preg_replace('~//+~', '/', $param);
900 return preg_replace('~/(\./)+~', '/', $param);
902 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
903 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
904 // match ipv4 dotted quad
905 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
906 // confirm values are ok
910 || $match[4] > 255 ) {
911 // hmmm, what kind of dotted quad is this?
914 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
915 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
916 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
918 // all is ok - $param is respected
925 case PARAM_URL: // allow safe ftp, http, mailto urls
926 $param = fix_utf8($param);
927 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
928 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
929 // all is ok, param is respected
931 $param =''; // not really ok
935 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
936 $param = clean_param($param, PARAM_URL);
937 if (!empty($param)) {
938 if (preg_match(':^/:', $param)) {
939 // root-relative, ok!
940 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
941 // absolute, and matches our wwwroot
943 // relative - let's make sure there are no tricks
944 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
954 $param = trim($param);
955 // PEM formatted strings may contain letters/numbers and the symbols
959 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
960 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
961 list($wholething, $body) = $matches;
962 unset($wholething, $matches);
963 $b64 = clean_param($body, PARAM_BASE64);
965 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
973 if (!empty($param)) {
974 // PEM formatted strings may contain letters/numbers and the symbols
978 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
981 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
982 // Each line of base64 encoded data must be 64 characters in
983 // length, except for the last line which may be less than (or
984 // equal to) 64 characters long.
985 for ($i=0, $j=count($lines); $i < $j; $i++) {
987 if (64 < strlen($lines[$i])) {
993 if (64 != strlen($lines[$i])) {
997 return implode("\n",$lines);
1003 $param = fix_utf8($param);
1004 // Please note it is not safe to use the tag name directly anywhere,
1005 // it must be processed with s(), urlencode() before embedding anywhere.
1006 // remove some nasties
1007 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1008 //convert many whitespace chars into one
1009 $param = preg_replace('/\s+/', ' ', $param);
1010 $textlib = textlib_get_instance();
1011 $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
1015 $param = fix_utf8($param);
1016 $tags = explode(',', $param);
1018 foreach ($tags as $tag) {
1019 $res = clean_param($tag, PARAM_TAG);
1025 return implode(',', $result);
1030 case PARAM_CAPABILITY:
1031 if (get_capability_info($param)) {
1037 case PARAM_PERMISSION:
1038 $param = (int)$param;
1039 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1046 $param = clean_param($param, PARAM_PLUGIN);
1047 if (empty($param)) {
1049 } else if (exists_auth_plugin($param)) {
1056 $param = clean_param($param, PARAM_SAFEDIR);
1057 if (get_string_manager()->translation_exists($param)) {
1060 return ''; // Specified language is not installed or param malformed
1064 $param = clean_param($param, PARAM_PLUGIN);
1065 if (empty($param)) {
1067 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1069 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1072 return ''; // Specified theme is not installed
1075 case PARAM_USERNAME:
1076 $param = fix_utf8($param);
1077 $param = str_replace(" " , "", $param);
1078 $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
1079 if (empty($CFG->extendedusernamechars)) {
1080 // regular expression, eliminate all chars EXCEPT:
1081 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1082 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1087 $param = fix_utf8($param);
1088 if (validate_email($param)) {
1094 case PARAM_STRINGID:
1095 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1101 case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1102 $param = fix_utf8($param);
1103 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1104 if (preg_match($timezonepattern, $param)) {
1110 default: // throw error, switched parameters in optional_param or another serious problem
1111 print_error("unknownparamtype", '', '', $type);
1116 * Makes sure the data is using valid utf8, invalid characters are discarded.
1118 * Note: this function is not intended for full objects with methods and private properties.
1120 * @param mixed $value
1121 * @return mixed with proper utf-8 encoding
1123 function fix_utf8($value) {
1124 if (is_null($value) or $value === '') {
1127 } else if (is_string($value)) {
1128 if ((string)(int)$value === $value) {
1132 return iconv('UTF-8', 'UTF-8//IGNORE', $value);
1134 } else if (is_array($value)) {
1135 foreach ($value as $k=>$v) {
1136 $value[$k] = fix_utf8($v);
1140 } else if (is_object($value)) {
1141 $value = clone($value); // do not modify original
1142 foreach ($value as $k=>$v) {
1143 $value->$k = fix_utf8($v);
1148 // this is some other type, no utf-8 here
1154 * Return true if given value is integer or string with integer value
1156 * @param mixed $value String or Int
1157 * @return bool true if number, false if not
1159 function is_number($value) {
1160 if (is_int($value)) {
1162 } else if (is_string($value)) {
1163 return ((string)(int)$value) === $value;
1170 * Returns host part from url
1171 * @param string $url full url
1172 * @return string host, null if not found
1174 function get_host_from_url($url) {
1175 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1183 * Tests whether anything was returned by text editor
1185 * This function is useful for testing whether something you got back from
1186 * the HTML editor actually contains anything. Sometimes the HTML editor
1187 * appear to be empty, but actually you get back a <br> tag or something.
1189 * @param string $string a string containing HTML.
1190 * @return boolean does the string contain any actual content - that is text,
1191 * images, objects, etc.
1193 function html_is_blank($string) {
1194 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1198 * Set a key in global configuration
1200 * Set a key/value pair in both this session's {@link $CFG} global variable
1201 * and in the 'config' database table for future sessions.
1203 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1204 * In that case it doesn't affect $CFG.
1206 * A NULL value will delete the entry.
1210 * @param string $name the key to set
1211 * @param string $value the value to set (without magic quotes)
1212 * @param string $plugin (optional) the plugin scope, default NULL
1213 * @return bool true or exception
1215 function set_config($name, $value, $plugin=NULL) {
1218 if (empty($plugin)) {
1219 if (!array_key_exists($name, $CFG->config_php_settings)) {
1220 // So it's defined for this invocation at least
1221 if (is_null($value)) {
1224 $CFG->$name = (string)$value; // settings from db are always strings
1228 if ($DB->get_field('config', 'name', array('name'=>$name))) {
1229 if ($value === null) {
1230 $DB->delete_records('config', array('name'=>$name));
1232 $DB->set_field('config', 'value', $value, array('name'=>$name));
1235 if ($value !== null) {
1236 $config = new stdClass();
1237 $config->name = $name;
1238 $config->value = $value;
1239 $DB->insert_record('config', $config, false);
1243 } else { // plugin scope
1244 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1245 if ($value===null) {
1246 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1248 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1251 if ($value !== null) {
1252 $config = new stdClass();
1253 $config->plugin = $plugin;
1254 $config->name = $name;
1255 $config->value = $value;
1256 $DB->insert_record('config_plugins', $config, false);
1265 * Get configuration values from the global config table
1266 * or the config_plugins table.
1268 * If called with one parameter, it will load all the config
1269 * variables for one plugin, and return them as an object.
1271 * If called with 2 parameters it will return a string single
1272 * value or false if the value is not found.
1274 * @param string $plugin full component name
1275 * @param string $name default NULL
1276 * @return mixed hash-like object or single value, return false no config found
1278 function get_config($plugin, $name = NULL) {
1281 // normalise component name
1282 if ($plugin === 'moodle' or $plugin === 'core') {
1286 if (!empty($name)) { // the user is asking for a specific value
1287 if (!empty($plugin)) {
1288 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1289 // setting forced in config file
1290 return $CFG->forced_plugin_settings[$plugin][$name];
1292 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1295 if (array_key_exists($name, $CFG->config_php_settings)) {
1296 // setting force in config file
1297 return $CFG->config_php_settings[$name];
1299 return $DB->get_field('config', 'value', array('name'=>$name));
1304 // the user is after a recordset
1306 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1307 if (isset($CFG->forced_plugin_settings[$plugin])) {
1308 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1309 if (is_null($v) or is_array($v) or is_object($v)) {
1310 // we do not want any extra mess here, just real settings that could be saved in db
1311 unset($localcfg[$n]);
1313 //convert to string as if it went through the DB
1314 $localcfg[$n] = (string)$v;
1319 return (object)$localcfg;
1321 return new stdClass();
1325 // this part is not really used any more, but anyway...
1326 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1327 foreach($CFG->config_php_settings as $n=>$v) {
1328 if (is_null($v) or is_array($v) or is_object($v)) {
1329 // we do not want any extra mess here, just real settings that could be saved in db
1330 unset($localcfg[$n]);
1332 //convert to string as if it went through the DB
1333 $localcfg[$n] = (string)$v;
1336 return (object)$localcfg;
1341 * Removes a key from global configuration
1343 * @param string $name the key to set
1344 * @param string $plugin (optional) the plugin scope
1346 * @return boolean whether the operation succeeded.
1348 function unset_config($name, $plugin=NULL) {
1351 if (empty($plugin)) {
1353 $DB->delete_records('config', array('name'=>$name));
1355 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1362 * Remove all the config variables for a given plugin.
1364 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1365 * @return boolean whether the operation succeeded.
1367 function unset_all_config_for_plugin($plugin) {
1369 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1370 $like = $DB->sql_like('name', '?', true, true, false, '|');
1371 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1372 $DB->delete_records_select('config', $like, $params);
1377 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1379 * All users are verified if they still have the necessary capability.
1381 * @param string $value the value of the config setting.
1382 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1383 * @param bool $include admins, include administrators
1384 * @return array of user objects.
1386 function get_users_from_config($value, $capability, $includeadmins = true) {
1389 if (empty($value) or $value === '$@NONE@$') {
1393 // we have to make sure that users still have the necessary capability,
1394 // it should be faster to fetch them all first and then test if they are present
1395 // instead of validating them one-by-one
1396 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1397 if ($includeadmins) {
1398 $admins = get_admins();
1399 foreach ($admins as $admin) {
1400 $users[$admin->id] = $admin;
1404 if ($value === '$@ALL@$') {
1408 $result = array(); // result in correct order
1409 $allowed = explode(',', $value);
1410 foreach ($allowed as $uid) {
1411 if (isset($users[$uid])) {
1412 $user = $users[$uid];
1413 $result[$user->id] = $user;
1422 * Invalidates browser caches and cached data in temp
1425 function purge_all_caches() {
1428 reset_text_filters_cache();
1429 js_reset_all_caches();
1430 theme_reset_all_caches();
1431 get_string_manager()->reset_caches();
1433 // purge all other caches: rss, simplepie, etc.
1434 remove_dir($CFG->cachedir.'', true);
1436 // make sure cache dir is writable, throws exception if not
1437 make_cache_directory('');
1439 // hack: this script may get called after the purifier was initialised,
1440 // but we do not want to verify repeatedly this exists in each call
1441 make_cache_directory('htmlpurifier');
1445 * Get volatile flags
1447 * @param string $type
1448 * @param int $changedsince default null
1449 * @return records array
1451 function get_cache_flags($type, $changedsince=NULL) {
1454 $params = array('type'=>$type, 'expiry'=>time());
1455 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1456 if ($changedsince !== NULL) {
1457 $params['changedsince'] = $changedsince;
1458 $sqlwhere .= " AND timemodified > :changedsince";
1462 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1463 foreach ($flags as $flag) {
1464 $cf[$flag->name] = $flag->value;
1471 * Get volatile flags
1473 * @param string $type
1474 * @param string $name
1475 * @param int $changedsince default null
1476 * @return records array
1478 function get_cache_flag($type, $name, $changedsince=NULL) {
1481 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1483 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1484 if ($changedsince !== NULL) {
1485 $params['changedsince'] = $changedsince;
1486 $sqlwhere .= " AND timemodified > :changedsince";
1489 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1493 * Set a volatile flag
1495 * @param string $type the "type" namespace for the key
1496 * @param string $name the key to set
1497 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1498 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1499 * @return bool Always returns true
1501 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1504 $timemodified = time();
1505 if ($expiry===NULL || $expiry < $timemodified) {
1506 $expiry = $timemodified + 24 * 60 * 60;
1508 $expiry = (int)$expiry;
1511 if ($value === NULL) {
1512 unset_cache_flag($type,$name);
1516 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1517 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1518 return true; //no need to update; helps rcache too
1521 $f->expiry = $expiry;
1522 $f->timemodified = $timemodified;
1523 $DB->update_record('cache_flags', $f);
1525 $f = new stdClass();
1526 $f->flagtype = $type;
1529 $f->expiry = $expiry;
1530 $f->timemodified = $timemodified;
1531 $DB->insert_record('cache_flags', $f);
1537 * Removes a single volatile flag
1540 * @param string $type the "type" namespace for the key
1541 * @param string $name the key to set
1544 function unset_cache_flag($type, $name) {
1546 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1551 * Garbage-collect volatile flags
1553 * @return bool Always returns true
1555 function gc_cache_flags() {
1557 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1561 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1564 * Refresh user preference cache. This is used most often for $USER
1565 * object that is stored in session, but it also helps with performance in cron script.
1567 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1569 * @param stdClass $user user object, preferences are preloaded into ->preference property
1570 * @param int $cachelifetime cache life time on the current page (ins seconds)
1573 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1575 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1577 if (!isset($user->id)) {
1578 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1581 if (empty($user->id) or isguestuser($user->id)) {
1582 // No permanent storage for not-logged-in users and guest
1583 if (!isset($user->preference)) {
1584 $user->preference = array();
1591 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1592 // Already loaded at least once on this page. Are we up to date?
1593 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1594 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1597 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1598 // no change since the lastcheck on this page
1599 $user->preference['_lastloaded'] = $timenow;
1604 // OK, so we have to reload all preferences
1605 $loadedusers[$user->id] = true;
1606 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1607 $user->preference['_lastloaded'] = $timenow;
1611 * Called from set/delete_user_preferences, so that the prefs can
1612 * be correctly reloaded in different sessions.
1614 * NOTE: internal function, do not call from other code.
1616 * @param integer $userid the user whose prefs were changed.
1619 function mark_user_preferences_changed($userid) {
1622 if (empty($userid) or isguestuser($userid)) {
1623 // no cache flags for guest and not-logged-in users
1627 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1631 * Sets a preference for the specified user.
1633 * If user object submitted, 'preference' property contains the preferences cache.
1635 * @param string $name The key to set as preference for the specified user
1636 * @param string $value The value to set for the $name key in the specified user's record,
1637 * null means delete current value
1638 * @param stdClass|int $user A moodle user object or id, null means current user
1639 * @return bool always true or exception
1641 function set_user_preference($name, $value, $user = null) {
1644 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1645 throw new coding_exception('Invalid preference name in set_user_preference() call');
1648 if (is_null($value)) {
1649 // null means delete current
1650 return unset_user_preference($name, $user);
1651 } else if (is_object($value)) {
1652 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1653 } else if (is_array($value)) {
1654 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1656 $value = (string)$value;
1657 if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1658 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1661 if (is_null($user)) {
1663 } else if (isset($user->id)) {
1664 // $user is valid object
1665 } else if (is_numeric($user)) {
1666 $user = (object)array('id'=>(int)$user);
1668 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1671 check_user_preferences_loaded($user);
1673 if (empty($user->id) or isguestuser($user->id)) {
1674 // no permanent storage for not-logged-in users and guest
1675 $user->preference[$name] = $value;
1679 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1680 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1681 // preference already set to this value
1684 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1687 $preference = new stdClass();
1688 $preference->userid = $user->id;
1689 $preference->name = $name;
1690 $preference->value = $value;
1691 $DB->insert_record('user_preferences', $preference);
1694 // update value in cache
1695 $user->preference[$name] = $value;
1697 // set reload flag for other sessions
1698 mark_user_preferences_changed($user->id);
1704 * Sets a whole array of preferences for the current user
1706 * If user object submitted, 'preference' property contains the preferences cache.
1708 * @param array $prefarray An array of key/value pairs to be set
1709 * @param stdClass|int $user A moodle user object or id, null means current user
1710 * @return bool always true or exception
1712 function set_user_preferences(array $prefarray, $user = null) {
1713 foreach ($prefarray as $name => $value) {
1714 set_user_preference($name, $value, $user);
1720 * Unsets a preference completely by deleting it from the database
1722 * If user object submitted, 'preference' property contains the preferences cache.
1724 * @param string $name The key to unset as preference for the specified user
1725 * @param stdClass|int $user A moodle user object or id, null means current user
1726 * @return bool always true or exception
1728 function unset_user_preference($name, $user = null) {
1731 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1732 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1735 if (is_null($user)) {
1737 } else if (isset($user->id)) {
1738 // $user is valid object
1739 } else if (is_numeric($user)) {
1740 $user = (object)array('id'=>(int)$user);
1742 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1745 check_user_preferences_loaded($user);
1747 if (empty($user->id) or isguestuser($user->id)) {
1748 // no permanent storage for not-logged-in user and guest
1749 unset($user->preference[$name]);
1754 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1756 // delete the preference from cache
1757 unset($user->preference[$name]);
1759 // set reload flag for other sessions
1760 mark_user_preferences_changed($user->id);
1766 * Used to fetch user preference(s)
1768 * If no arguments are supplied this function will return
1769 * all of the current user preferences as an array.
1771 * If a name is specified then this function
1772 * attempts to return that particular preference value. If
1773 * none is found, then the optional value $default is returned,
1776 * If user object submitted, 'preference' property contains the preferences cache.
1778 * @param string $name Name of the key to use in finding a preference value
1779 * @param mixed $default Value to be returned if the $name key is not set in the user preferences
1780 * @param stdClass|int $user A moodle user object or id, null means current user
1781 * @return mixed string value or default
1783 function get_user_preferences($name = null, $default = null, $user = null) {
1786 if (is_null($name)) {
1788 } else if (is_numeric($name) or $name === '_lastloaded') {
1789 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1792 if (is_null($user)) {
1794 } else if (isset($user->id)) {
1795 // $user is valid object
1796 } else if (is_numeric($user)) {
1797 $user = (object)array('id'=>(int)$user);
1799 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1802 check_user_preferences_loaded($user);
1805 return $user->preference; // All values
1806 } else if (isset($user->preference[$name])) {
1807 return $user->preference[$name]; // The single string value
1809 return $default; // Default value (null if not specified)
1813 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1816 * Given date parts in user time produce a GMT timestamp.
1820 * @param int $year The year part to create timestamp of
1821 * @param int $month The month part to create timestamp of
1822 * @param int $day The day part to create timestamp of
1823 * @param int $hour The hour part to create timestamp of
1824 * @param int $minute The minute part to create timestamp of
1825 * @param int $second The second part to create timestamp of
1826 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1827 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
1828 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1829 * applied only if timezone is 99 or string.
1830 * @return int GMT timestamp
1832 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1834 //save input timezone, required for dst offset check.
1835 $passedtimezone = $timezone;
1837 $timezone = get_user_timezone_offset($timezone);
1839 if (abs($timezone) > 13) { //server time
1840 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1842 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1843 $time = usertime($time, $timezone);
1845 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1846 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1847 $time -= dst_offset_on($time, $passedtimezone);
1856 * Format a date/time (seconds) as weeks, days, hours etc as needed
1858 * Given an amount of time in seconds, returns string
1859 * formatted nicely as weeks, days, hours etc as needed
1867 * @param int $totalsecs Time in seconds
1868 * @param object $str Should be a time object
1869 * @return string A nicely formatted date/time string
1871 function format_time($totalsecs, $str=NULL) {
1873 $totalsecs = abs($totalsecs);
1875 if (!$str) { // Create the str structure the slow way
1876 $str = new stdClass();
1877 $str->day = get_string('day');
1878 $str->days = get_string('days');
1879 $str->hour = get_string('hour');
1880 $str->hours = get_string('hours');
1881 $str->min = get_string('min');
1882 $str->mins = get_string('mins');
1883 $str->sec = get_string('sec');
1884 $str->secs = get_string('secs');
1885 $str->year = get_string('year');
1886 $str->years = get_string('years');
1890 $years = floor($totalsecs/YEARSECS);
1891 $remainder = $totalsecs - ($years*YEARSECS);
1892 $days = floor($remainder/DAYSECS);
1893 $remainder = $totalsecs - ($days*DAYSECS);
1894 $hours = floor($remainder/HOURSECS);
1895 $remainder = $remainder - ($hours*HOURSECS);
1896 $mins = floor($remainder/MINSECS);
1897 $secs = $remainder - ($mins*MINSECS);
1899 $ss = ($secs == 1) ? $str->sec : $str->secs;
1900 $sm = ($mins == 1) ? $str->min : $str->mins;
1901 $sh = ($hours == 1) ? $str->hour : $str->hours;
1902 $sd = ($days == 1) ? $str->day : $str->days;
1903 $sy = ($years == 1) ? $str->year : $str->years;
1911 if ($years) $oyears = $years .' '. $sy;
1912 if ($days) $odays = $days .' '. $sd;
1913 if ($hours) $ohours = $hours .' '. $sh;
1914 if ($mins) $omins = $mins .' '. $sm;
1915 if ($secs) $osecs = $secs .' '. $ss;
1917 if ($years) return trim($oyears .' '. $odays);
1918 if ($days) return trim($odays .' '. $ohours);
1919 if ($hours) return trim($ohours .' '. $omins);
1920 if ($mins) return trim($omins .' '. $osecs);
1921 if ($secs) return $osecs;
1922 return get_string('now');
1926 * Returns a formatted string that represents a date in user time
1928 * Returns a formatted string that represents a date in user time
1929 * <b>WARNING: note that the format is for strftime(), not date().</b>
1930 * Because of a bug in most Windows time libraries, we can't use
1931 * the nicer %e, so we have to use %d which has leading zeroes.
1932 * A lot of the fuss in the function is just getting rid of these leading
1933 * zeroes as efficiently as possible.
1935 * If parameter fixday = true (default), then take off leading
1936 * zero from %d, else maintain it.
1940 * @param int $date the timestamp in UTC, as obtained from the database.
1941 * @param string $format strftime format. You should probably get this using
1942 * get_string('strftime...', 'langconfig');
1943 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
1944 * not 99 then daylight saving will not be added.
1945 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
1946 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1947 * If false then the leading zero is maintained.
1948 * @return string the formatted date/time.
1950 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1954 if (empty($format)) {
1955 $format = get_string('strftimedaydatetime', 'langconfig');
1958 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1960 } else if ($fixday) {
1961 $formatnoday = str_replace('%d', 'DD', $format);
1962 $fixday = ($formatnoday != $format);
1965 //add daylight saving offset for string timezones only, as we can't get dst for
1966 //float values. if timezone is 99 (user default timezone), then try update dst.
1967 if ((99 == $timezone) || !is_numeric($timezone)) {
1968 $date += dst_offset_on($date, $timezone);
1971 $timezone = get_user_timezone_offset($timezone);
1973 if (abs($timezone) > 13) { /// Server time
1975 $datestring = strftime($formatnoday, $date);
1976 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
1977 $datestring = str_replace('DD', $daystring, $datestring);
1979 $datestring = strftime($format, $date);
1982 $date += (int)($timezone * 3600);
1984 $datestring = gmstrftime($formatnoday, $date);
1985 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
1986 $datestring = str_replace('DD', $daystring, $datestring);
1988 $datestring = gmstrftime($format, $date);
1992 /// If we are running under Windows convert from windows encoding to UTF-8
1993 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1995 if ($CFG->ostype == 'WINDOWS') {
1996 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1997 $textlib = textlib_get_instance();
1998 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
2002 // When using the %l (12-hour time with no leading zero), it adds unwanted spaces
2003 $datestring = trim(str_replace(' ', ' ', $datestring));
2008 * Given a $time timestamp in GMT (seconds since epoch),
2009 * returns an array that represents the date in user time
2014 * @param int $time Timestamp in GMT
2015 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2016 * dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
2017 * @return array An array that represents the date in user time
2019 function usergetdate($time, $timezone=99) {
2021 //save input timezone, required for dst offset check.
2022 $passedtimezone = $timezone;
2024 $timezone = get_user_timezone_offset($timezone);
2026 if (abs($timezone) > 13) { // Server time
2027 return getdate($time);
2030 //add daylight saving offset for string timezones only, as we can't get dst for
2031 //float values. if timezone is 99 (user default timezone), then try update dst.
2032 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2033 $time += dst_offset_on($time, $passedtimezone);
2036 $time += intval((float)$timezone * HOURSECS);
2038 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2040 //be careful to ensure the returned array matches that produced by getdate() above
2043 $getdate['weekday'],
2050 $getdate['minutes'],
2052 ) = explode('_', $datestring);
2058 * Given a GMT timestamp (seconds since epoch), offsets it by
2059 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2064 * @param int $date Timestamp in GMT
2065 * @param float|int|string $timezone timezone to calculate GMT time offset before
2066 * calculating user time, 99 is default user timezone
2067 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2070 function usertime($date, $timezone=99) {
2072 $timezone = get_user_timezone_offset($timezone);
2074 if (abs($timezone) > 13) {
2077 return $date - (int)($timezone * HOURSECS);
2081 * Given a time, return the GMT timestamp of the most recent midnight
2082 * for the current user.
2086 * @param int $date Timestamp in GMT
2087 * @param float|int|string $timezone timezone to calculate GMT time offset before
2088 * calculating user midnight time, 99 is default user timezone
2089 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2090 * @return int Returns a GMT timestamp
2092 function usergetmidnight($date, $timezone=99) {
2094 $userdate = usergetdate($date, $timezone);
2096 // Time of midnight of this user's day, in GMT
2097 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2102 * Returns a string that prints the user's timezone
2106 * @param float|int|string $timezone timezone to calculate GMT time offset before
2107 * calculating user timezone, 99 is default user timezone
2108 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2111 function usertimezone($timezone=99) {
2113 $tz = get_user_timezone($timezone);
2115 if (!is_float($tz)) {
2119 if(abs($tz) > 13) { // Server time
2120 return get_string('serverlocaltime');
2123 if($tz == intval($tz)) {
2124 // Don't show .0 for whole hours
2141 * Returns a float which represents the user's timezone difference from GMT in hours
2142 * Checks various settings and picks the most dominant of those which have a value
2146 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2147 * 99 is default user timezone
2148 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2151 function get_user_timezone_offset($tz = 99) {
2155 $tz = get_user_timezone($tz);
2157 if (is_float($tz)) {
2160 $tzrecord = get_timezone_record($tz);
2161 if (empty($tzrecord)) {
2164 return (float)$tzrecord->gmtoff / HOURMINS;
2169 * Returns an int which represents the systems's timezone difference from GMT in seconds
2173 * @param float|int|string $tz timezone for which offset is required.
2174 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2175 * @return int|bool if found, false is timezone 99 or error
2177 function get_timezone_offset($tz) {
2184 if (is_numeric($tz)) {
2185 return intval($tz * 60*60);
2188 if (!$tzrecord = get_timezone_record($tz)) {
2191 return intval($tzrecord->gmtoff * 60);
2195 * Returns a float or a string which denotes the user's timezone
2196 * 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)
2197 * means that for this timezone there are also DST rules to be taken into account
2198 * Checks various settings and picks the most dominant of those which have a value
2202 * @param float|int|string $tz timezone to calculate GMT time offset before
2203 * calculating user timezone, 99 is default user timezone
2204 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2205 * @return float|string
2207 function get_user_timezone($tz = 99) {
2212 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2213 isset($USER->timezone) ? $USER->timezone : 99,
2214 isset($CFG->timezone) ? $CFG->timezone : 99,
2219 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
2220 $tz = $next['value'];
2223 return is_numeric($tz) ? (float) $tz : $tz;
2227 * Returns cached timezone record for given $timezonename
2230 * @param string $timezonename name of the timezone
2231 * @return stdClass|bool timezonerecord or false
2233 function get_timezone_record($timezonename) {
2235 static $cache = NULL;
2237 if ($cache === NULL) {
2241 if (isset($cache[$timezonename])) {
2242 return $cache[$timezonename];
2245 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2246 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2250 * Build and store the users Daylight Saving Time (DST) table
2253 * @param int $from_year Start year for the table, defaults to 1971
2254 * @param int $to_year End year for the table, defaults to 2035
2255 * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
2258 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2259 global $CFG, $SESSION, $DB;
2261 $usertz = get_user_timezone($strtimezone);
2263 if (is_float($usertz)) {
2264 // Trivial timezone, no DST
2268 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2269 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2270 unset($SESSION->dst_offsets);
2271 unset($SESSION->dst_range);
2274 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2275 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2276 // This will be the return path most of the time, pretty light computationally
2280 // Reaching here means we either need to extend our table or create it from scratch
2282 // Remember which TZ we calculated these changes for
2283 $SESSION->dst_offsettz = $usertz;
2285 if(empty($SESSION->dst_offsets)) {
2286 // If we 're creating from scratch, put the two guard elements in there
2287 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2289 if(empty($SESSION->dst_range)) {
2290 // If creating from scratch
2291 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2292 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2294 // Fill in the array with the extra years we need to process
2295 $yearstoprocess = array();
2296 for($i = $from; $i <= $to; ++$i) {
2297 $yearstoprocess[] = $i;
2300 // Take note of which years we have processed for future calls
2301 $SESSION->dst_range = array($from, $to);
2304 // If needing to extend the table, do the same
2305 $yearstoprocess = array();
2307 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2308 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2310 if($from < $SESSION->dst_range[0]) {
2311 // Take note of which years we need to process and then note that we have processed them for future calls
2312 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2313 $yearstoprocess[] = $i;
2315 $SESSION->dst_range[0] = $from;
2317 if($to > $SESSION->dst_range[1]) {
2318 // Take note of which years we need to process and then note that we have processed them for future calls
2319 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2320 $yearstoprocess[] = $i;
2322 $SESSION->dst_range[1] = $to;
2326 if(empty($yearstoprocess)) {
2327 // This means that there was a call requesting a SMALLER range than we have already calculated
2331 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2332 // Also, the array is sorted in descending timestamp order!
2336 static $presets_cache = array();
2337 if (!isset($presets_cache[$usertz])) {
2338 $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');
2340 if(empty($presets_cache[$usertz])) {
2344 // Remove ending guard (first element of the array)
2345 reset($SESSION->dst_offsets);
2346 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2348 // Add all required change timestamps
2349 foreach($yearstoprocess as $y) {
2350 // Find the record which is in effect for the year $y
2351 foreach($presets_cache[$usertz] as $year => $preset) {
2357 $changes = dst_changes_for_year($y, $preset);
2359 if($changes === NULL) {
2362 if($changes['dst'] != 0) {
2363 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2365 if($changes['std'] != 0) {
2366 $SESSION->dst_offsets[$changes['std']] = 0;
2370 // Put in a guard element at the top
2371 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2372 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2375 krsort($SESSION->dst_offsets);
2381 * Calculates the required DST change and returns a Timestamp Array
2387 * @param int|string $year Int or String Year to focus on
2388 * @param object $timezone Instatiated Timezone object
2389 * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
2391 function dst_changes_for_year($year, $timezone) {
2393 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2397 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2398 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2400 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2401 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2403 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2404 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2406 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2407 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2408 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2410 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2411 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2413 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2417 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2418 * - Note: Daylight saving only works for string timezones and not for float.
2422 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2423 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2424 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2427 function dst_offset_on($time, $strtimezone = NULL) {
2430 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2434 reset($SESSION->dst_offsets);
2435 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2436 if($from <= $time) {
2441 // This is the normal return path
2442 if($offset !== NULL) {
2446 // Reaching this point means we haven't calculated far enough, do it now:
2447 // Calculate extra DST changes if needed and recurse. The recursion always
2448 // moves toward the stopping condition, so will always end.
2451 // We need a year smaller than $SESSION->dst_range[0]
2452 if($SESSION->dst_range[0] == 1971) {
2455 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2456 return dst_offset_on($time, $strtimezone);
2459 // We need a year larger than $SESSION->dst_range[1]
2460 if($SESSION->dst_range[1] == 2035) {
2463 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2464 return dst_offset_on($time, $strtimezone);
2469 * Calculates when the day appears in specific month
2473 * @param int $startday starting day of the month
2474 * @param int $weekday The day when week starts (normally taken from user preferences)
2475 * @param int $month The month whose day is sought
2476 * @param int $year The year of the month whose day is sought
2479 function find_day_in_month($startday, $weekday, $month, $year) {
2481 $daysinmonth = days_in_month($month, $year);
2483 if($weekday == -1) {
2484 // Don't care about weekday, so return:
2485 // abs($startday) if $startday != -1
2486 // $daysinmonth otherwise
2487 return ($startday == -1) ? $daysinmonth : abs($startday);
2490 // From now on we 're looking for a specific weekday
2492 // Give "end of month" its actual value, since we know it
2493 if($startday == -1) {
2494 $startday = -1 * $daysinmonth;
2497 // Starting from day $startday, the sign is the direction
2501 $startday = abs($startday);
2502 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2504 // This is the last such weekday of the month
2505 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2506 if($lastinmonth > $daysinmonth) {
2510 // Find the first such weekday <= $startday
2511 while($lastinmonth > $startday) {
2515 return $lastinmonth;
2520 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2522 $diff = $weekday - $indexweekday;
2527 // This is the first such weekday of the month equal to or after $startday
2528 $firstfromindex = $startday + $diff;
2530 return $firstfromindex;
2536 * Calculate the number of days in a given month
2540 * @param int $month The month whose day count is sought
2541 * @param int $year The year of the month whose day count is sought
2544 function days_in_month($month, $year) {
2545 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2549 * Calculate the position in the week of a specific calendar day
2553 * @param int $day The day of the date whose position in the week is sought
2554 * @param int $month The month of the date whose position in the week is sought
2555 * @param int $year The year of the date whose position in the week is sought
2558 function dayofweek($day, $month, $year) {
2559 // I wonder if this is any different from
2560 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2561 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2564 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2567 * Returns full login url.
2569 * @return string login url
2571 function get_login_url() {
2574 $url = "$CFG->wwwroot/login/index.php";
2576 if (!empty($CFG->loginhttps)) {
2577 $url = str_replace('http:', 'https:', $url);
2584 * This function checks that the current user is logged in and has the
2585 * required privileges
2587 * This function checks that the current user is logged in, and optionally
2588 * whether they are allowed to be in a particular course and view a particular
2590 * If they are not logged in, then it redirects them to the site login unless
2591 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2592 * case they are automatically logged in as guests.
2593 * If $courseid is given and the user is not enrolled in that course then the
2594 * user is redirected to the course enrolment page.
2595 * If $cm is given and the course module is hidden and the user is not a teacher
2596 * in the course then the user is redirected to the course home page.
2598 * When $cm parameter specified, this function sets page layout to 'module'.
2599 * You need to change it manually later if some other layout needed.
2601 * @param mixed $courseorid id of the course or course object
2602 * @param bool $autologinguest default true
2603 * @param object $cm course module object
2604 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2605 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2606 * in order to keep redirects working properly. MDL-14495
2607 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2608 * @return mixed Void, exit, and die depending on path
2610 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2611 global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2613 // setup global $COURSE, themes, language and locale
2614 if (!empty($courseorid)) {
2615 if (is_object($courseorid)) {
2616 $course = $courseorid;
2617 } else if ($courseorid == SITEID) {
2618 $course = clone($SITE);
2620 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2623 if ($cm->course != $course->id) {
2624 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2626 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2627 if (!($cm instanceof cm_info)) {
2628 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2629 // db queries so this is not really a performance concern, however it is obviously
2630 // better if you use get_fast_modinfo to get the cm before calling this.
2631 $modinfo = get_fast_modinfo($course);
2632 $cm = $modinfo->get_cm($cm->id);
2634 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2635 $PAGE->set_pagelayout('incourse');
2637 $PAGE->set_course($course); // set's up global $COURSE
2640 // do not touch global $COURSE via $PAGE->set_course(),
2641 // the reasons is we need to be able to call require_login() at any time!!
2644 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2648 // If the user is not even logged in yet then make sure they are
2649 if (!isloggedin()) {
2650 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2651 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2652 // misconfigured site guest, just redirect to login page
2653 redirect(get_login_url());
2654 exit; // never reached
2656 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2657 complete_user_login($guest);
2658 $USER->autologinguest = true;
2659 $SESSION->lang = $lang;
2661 //NOTE: $USER->site check was obsoleted by session test cookie,
2662 // $USER->confirmed test is in login/index.php
2663 if ($preventredirect) {
2664 throw new require_login_exception('You are not logged in');
2667 if ($setwantsurltome) {
2668 // TODO: switch to PAGE->url
2669 $SESSION->wantsurl = $FULLME;
2671 if (!empty($_SERVER['HTTP_REFERER'])) {
2672 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2674 redirect(get_login_url());
2675 exit; // never reached
2679 // loginas as redirection if needed
2680 if ($course->id != SITEID and session_is_loggedinas()) {
2681 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2682 if ($USER->loginascontext->instanceid != $course->id) {
2683 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2688 // check whether the user should be changing password (but only if it is REALLY them)
2689 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2690 $userauth = get_auth_plugin($USER->auth);
2691 if ($userauth->can_change_password() and !$preventredirect) {
2692 $SESSION->wantsurl = $FULLME;
2693 if ($changeurl = $userauth->change_password_url()) {
2694 //use plugin custom url
2695 redirect($changeurl);
2697 //use moodle internal method
2698 if (empty($CFG->loginhttps)) {
2699 redirect($CFG->wwwroot .'/login/change_password.php');
2701 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2702 redirect($wwwroot .'/login/change_password.php');
2706 print_error('nopasswordchangeforced', 'auth');
2710 // Check that the user account is properly set up
2711 if (user_not_fully_set_up($USER)) {
2712 if ($preventredirect) {
2713 throw new require_login_exception('User not fully set-up');
2715 $SESSION->wantsurl = $FULLME;
2716 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2719 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2722 // Do not bother admins with any formalities
2723 if (is_siteadmin()) {
2724 //set accesstime or the user will appear offline which messes up messaging
2725 user_accesstime_log($course->id);
2729 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2730 if (!$USER->policyagreed and !is_siteadmin()) {
2731 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2732 if ($preventredirect) {
2733 throw new require_login_exception('Policy not agreed');
2735 $SESSION->wantsurl = $FULLME;
2736 redirect($CFG->wwwroot .'/user/policy.php');
2737 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2738 if ($preventredirect) {
2739 throw new require_login_exception('Policy not agreed');
2741 $SESSION->wantsurl = $FULLME;
2742 redirect($CFG->wwwroot .'/user/policy.php');
2746 // Fetch the system context, the course context, and prefetch its child contexts
2747 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2748 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2750 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2755 // If the site is currently under maintenance, then print a message
2756 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2757 if ($preventredirect) {
2758 throw new require_login_exception('Maintenance in progress');
2761 print_maintenance_message();
2764 // make sure the course itself is not hidden
2765 if ($course->id == SITEID) {
2766 // frontpage can not be hidden
2768 if (is_role_switched($course->id)) {
2769 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2771 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2772 // originally there was also test of parent category visibility,
2773 // BUT is was very slow in complex queries involving "my courses"
2774 // now it is also possible to simply hide all courses user is not enrolled in :-)
2775 if ($preventredirect) {
2776 throw new require_login_exception('Course is hidden');
2778 // We need to override the navigation URL as the course won't have
2779 // been added to the navigation and thus the navigation will mess up
2780 // when trying to find it.
2781 navigation_node::override_active_url(new moodle_url('/'));
2782 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2787 // is the user enrolled?
2788 if ($course->id == SITEID) {
2789 // everybody is enrolled on the frontpage
2792 if (session_is_loggedinas()) {
2793 // Make sure the REAL person can access this course first
2794 $realuser = session_get_realuser();
2795 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2796 if ($preventredirect) {
2797 throw new require_login_exception('Invalid course login-as access');
2799 echo $OUTPUT->header();
2800 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2806 if (is_role_switched($course->id)) {
2807 // ok, user had to be inside this course before the switch
2810 } else if (is_viewing($coursecontext, $USER)) {
2811 // ok, no need to mess with enrol
2815 if (isset($USER->enrol['enrolled'][$course->id])) {
2816 if ($USER->enrol['enrolled'][$course->id] > time()) {
2818 if (isset($USER->enrol['tempguest'][$course->id])) {
2819 unset($USER->enrol['tempguest'][$course->id]);
2820 remove_temp_course_roles($coursecontext);
2824 unset($USER->enrol['enrolled'][$course->id]);
2827 if (isset($USER->enrol['tempguest'][$course->id])) {
2828 if ($USER->enrol['tempguest'][$course->id] == 0) {
2830 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2834 unset($USER->enrol['tempguest'][$course->id]);
2835 remove_temp_course_roles($coursecontext);
2842 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2843 if ($until !== false) {
2844 // active participants may always access, a timestamp in the future, 0 (always) or false.
2846 $until = ENROL_MAX_TIMESTAMP;
2848 $USER->enrol['enrolled'][$course->id] = $until;
2852 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2853 $enrols = enrol_get_plugins(true);
2854 // first ask all enabled enrol instances in course if they want to auto enrol user
2855 foreach($instances as $instance) {
2856 if (!isset($enrols[$instance->enrol])) {
2859 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2860 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2861 if ($until !== false) {
2863 $until = ENROL_MAX_TIMESTAMP;
2865 $USER->enrol['enrolled'][$course->id] = $until;
2870 // if not enrolled yet try to gain temporary guest access
2872 foreach($instances as $instance) {
2873 if (!isset($enrols[$instance->enrol])) {
2876 // Get a duration for the guest access, a timestamp in the future or false.
2877 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2878 if ($until !== false and $until > time()) {
2879 $USER->enrol['tempguest'][$course->id] = $until;
2890 if ($preventredirect) {
2891 throw new require_login_exception('Not enrolled');
2893 $SESSION->wantsurl = $FULLME;
2894 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2898 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
2899 // conditional availability, etc
2900 if ($cm && !$cm->uservisible) {
2901 if ($preventredirect) {
2902 throw new require_login_exception('Activity is hidden');
2904 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2907 // Finally access granted, update lastaccess times
2908 user_accesstime_log($course->id);
2913 * This function just makes sure a user is logged out.
2917 function require_logout() {
2923 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2925 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2926 foreach($authsequence as $authname) {
2927 $authplugin = get_auth_plugin($authname);
2928 $authplugin->prelogout_hook();
2932 events_trigger('user_logout', $params);
2933 session_get_instance()->terminate_current();
2938 * Weaker version of require_login()
2940 * This is a weaker version of {@link require_login()} which only requires login
2941 * when called from within a course rather than the site page, unless
2942 * the forcelogin option is turned on.
2943 * @see require_login()
2946 * @param mixed $courseorid The course object or id in question
2947 * @param bool $autologinguest Allow autologin guests if that is wanted
2948 * @param object $cm Course activity module if known
2949 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2950 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2951 * in order to keep redirects working properly. MDL-14495
2952 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2955 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2956 global $CFG, $PAGE, $SITE;
2957 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
2958 or (!is_object($courseorid) and $courseorid == SITEID);
2959 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2960 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2961 // db queries so this is not really a performance concern, however it is obviously
2962 // better if you use get_fast_modinfo to get the cm before calling this.
2963 if (is_object($courseorid)) {
2964 $course = $courseorid;
2966 $course = clone($SITE);
2968 $modinfo = get_fast_modinfo($course);
2969 $cm = $modinfo->get_cm($cm->id);
2971 if (!empty($CFG->forcelogin)) {
2972 // login required for both SITE and courses
2973 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2975 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2976 // always login for hidden activities
2977 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2979 } else if ($issite) {
2980 //login for SITE not required
2981 if ($cm and empty($cm->visible)) {
2982 // hidden activities are not accessible without login
2983 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2984 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2985 // not-logged-in users do not have any group membership
2986 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2988 // We still need to instatiate PAGE vars properly so that things
2989 // that rely on it like navigation function correctly.
2990 if (!empty($courseorid)) {
2991 if (is_object($courseorid)) {
2992 $course = $courseorid;
2994 $course = clone($SITE);
2997 if ($cm->course != $course->id) {
2998 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3000 $PAGE->set_cm($cm, $course);
3001 $PAGE->set_pagelayout('incourse');
3003 $PAGE->set_course($course);
3006 // If $PAGE->course, and hence $PAGE->context, have not already been set
3007 // up properly, set them up now.
3008 $PAGE->set_course($PAGE->course);
3010 //TODO: verify conditional activities here
3011 user_accesstime_log(SITEID);
3016 // course login always required
3017 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3022 * Require key login. Function terminates with error if key not found or incorrect.
3028 * @uses NO_MOODLE_COOKIES
3029 * @uses PARAM_ALPHANUM
3030 * @param string $script unique script identifier
3031 * @param int $instance optional instance id
3032 * @return int Instance ID
3034 function require_user_key_login($script, $instance=null) {
3035 global $USER, $SESSION, $CFG, $DB;
3037 if (!NO_MOODLE_COOKIES) {
3038 print_error('sessioncookiesdisable');
3042 @session_write_close();
3044 $keyvalue = required_param('key', PARAM_ALPHANUM);
3046 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3047 print_error('invalidkey');
3050 if (!empty($key->validuntil) and $key->validuntil < time()) {
3051 print_error('expiredkey');
3054 if ($key->iprestriction) {
3055 $remoteaddr = getremoteaddr(null);
3056 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3057 print_error('ipmismatch');
3061 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
3062 print_error('invaliduserid');
3065 /// emulate normal session
3066 enrol_check_plugins($user);
3067 session_set_user($user);
3069 /// note we are not using normal login
3070 if (!defined('USER_KEY_LOGIN')) {
3071 define('USER_KEY_LOGIN', true);
3074 /// return instance id - it might be empty
3075 return $key->instance;
3079 * Creates a new private user access key.
3082 * @param string $script unique target identifier
3083 * @param int $userid
3084 * @param int $instance optional instance id
3085 * @param string $iprestriction optional ip restricted access
3086 * @param timestamp $validuntil key valid only until given data
3087 * @return string access key value
3089 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3092 $key = new stdClass();
3093 $key->script = $script;
3094 $key->userid = $userid;
3095 $key->instance = $instance;
3096 $key->iprestriction = $iprestriction;
3097 $key->validuntil = $validuntil;
3098 $key->timecreated = time();
3100 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
3101 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3103 $key->value = md5($userid.'_'.time().random_string(40));
3105 $DB->insert_record('user_private_key', $key);
3110 * Delete the user's new private user access keys for a particular script.
3113 * @param string $script unique target identifier
3114 * @param int $userid
3117 function delete_user_key($script,$userid) {
3119 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3123 * Gets a private user access key (and creates one if one doesn't exist).
3126 * @param string $script unique target identifier
3127 * @param int $userid
3128 * @param int $instance optional instance id
3129 * @param string $iprestriction optional ip restricted access
3130 * @param timestamp $validuntil key valid only until given data
3131 * @return string access key value
3133 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3136 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3137 'instance'=>$instance, 'iprestriction'=>$iprestriction,
3138 'validuntil'=>$validuntil))) {
3141 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3147 * Modify the user table by setting the currently logged in user's
3148 * last login to now.
3152 * @return bool Always returns true
3154 function update_user_login_times() {
3157 $user = new stdClass();
3158 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3159 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
3161 $user->id = $USER->id;
3163 $DB->update_record('user', $user);
3168 * Determines if a user has completed setting up their account.
3170 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3173 function user_not_fully_set_up($user) {
3174 if (isguestuser($user)) {
3177 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3181 * Check whether the user has exceeded the bounce threshold
3185 * @param user $user A {@link $USER} object
3186 * @return bool true=>User has exceeded bounce threshold
3188 function over_bounce_threshold($user) {
3191 if (empty($CFG->handlebounces)) {
3195 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3199 // set sensible defaults
3200 if (empty($CFG->minbounces)) {
3201 $CFG->minbounces = 10;
3203 if (empty($CFG->bounceratio)) {
3204 $CFG->bounceratio = .20;
3208 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3209 $bouncecount = $bounce->value;
3211 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3212 $sendcount = $send->value;
3214 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3218 * Used to increment or reset email sent count
3221 * @param user $user object containing an id
3222 * @param bool $reset will reset the count to 0
3225 function set_send_count($user,$reset=false) {
3228 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3232 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3233 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3234 $DB->update_record('user_preferences', $pref);
3236 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3238 $pref = new stdClass();
3239 $pref->name = 'email_send_count';
3241 $pref->userid = $user->id;
3242 $DB->insert_record('user_preferences', $pref, false);
3247 * Increment or reset user's email bounce count
3250 * @param user $user object containing an id
3251 * @param bool $reset will reset the count to 0
3253 function set_bounce_count($user,$reset=false) {
3256 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3257 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3258 $DB->update_record('user_preferences', $pref);
3260 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3262 $pref = new stdClass();
3263 $pref->name = 'email_bounce_count';
3265 $pref->userid = $user->id;
3266 $DB->insert_record('user_preferences', $pref, false);
3271 * Keeps track of login attempts
3275 function update_login_count() {
3280 if (empty($SESSION->logincount)) {
3281 $SESSION->logincount = 1;
3283 $SESSION->logincount++;
3286 if ($SESSION->logincount > $max_logins) {
3287 unset($SESSION->wantsurl);
3288 print_error('errortoomanylogins');
3293 * Resets login attempts
3297 function reset_login_count() {
3300 $SESSION->logincount = 0;
3304 * Determines if the currently logged in user is in editing mode.
3305 * Note: originally this function had $userid parameter - it was not usable anyway
3307 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3308 * @todo Deprecated function remove when ready
3311 * @uses DEBUG_DEVELOPER
3314 function isediting() {
3316 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3317 return $PAGE->user_is_editing();
3321 * Determines if the logged in user is currently moving an activity
3324 * @param int $courseid The id of the course being tested
3327 function ismoving($courseid) {
3330 if (!empty($USER->activitycopy)) {
3331 return ($USER->activitycopycourse == $courseid);
3337 * Returns a persons full name
3339 * Given an object containing firstname and lastname
3340 * values, this function returns a string with the
3341 * full name of the person.
3342 * The result may depend on system settings
3343 * or language. 'override' will force both names
3344 * to be used even if system settings specify one.
3348 * @param object $user A {@link $USER} object to get full name of
3349 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3352 function fullname($user, $override=false) {
3353 global $CFG, $SESSION;
3355 if (!isset($user->firstname) and !isset($user->lastname)) {
3360 if (!empty($CFG->forcefirstname)) {
3361 $user->firstname = $CFG->forcefirstname;
3363 if (!empty($CFG->forcelastname)) {
3364 $user->lastname = $CFG->forcelastname;
3368 if (!empty($SESSION->fullnamedisplay)) {
3369 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3372 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3373 return $user->firstname .' '. $user->lastname;
3375 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3376 return $user->lastname .' '. $user->firstname;
3378 } else if ($CFG->fullnamedisplay == 'firstname') {
3380 return get_string('fullnamedisplay', '', $user);
3382 return $user->firstname;
3386 return get_string('fullnamedisplay', '', $user);
3390 * Checks if current user is shown any extra fields when listing users.
3391 * @param object $context Context
3392 * @param array $already Array of fields that we're going to show anyway
3393 * so don't bother listing them
3394 * @return array Array of field names from user table, not including anything
3395 * listed in $already
3397 function get_extra_user_fields($context, $already = array()) {
3400 // Only users with permission get the extra fields
3401 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3405 // Split showuseridentity on comma
3406 if (empty($CFG->showuseridentity)) {
3407 // Explode gives wrong result with empty string
3410 $extra = explode(',', $CFG->showuseridentity);
3413 foreach ($extra as $key => $field) {
3414 if (in_array($field, $already)) {
3415 unset($extra[$key]);
3420 // For consistency, if entries are removed from array, renumber it
3421 // so they are numbered as you would expect
3422 $extra = array_merge($extra);
3428 * If the current user is to be shown extra user fields when listing or
3429 * selecting users, returns a string suitable for including in an SQL select
3430 * clause to retrieve those fields.
3431 * @param object $context Context
3432 * @param string $alias Alias of user table, e.g. 'u' (default none)
3433 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3434 * @param array $already Array of fields that we're going to include anyway
3435 * so don't list them (default none)
3436 * @return string Partial SQL select clause, beginning with comma, for example
3437 * ',u.idnumber,u.department' unless it is blank
3439 function get_extra_user_fields_sql($context, $alias='', $prefix='',
3440 $already = array()) {
3441 $fields = get_extra_user_fields($context, $already);
3443 // Add punctuation for alias
3444 if ($alias !== '') {
3447 foreach ($fields as $field) {
3448 $result .= ', ' . $alias . $field;
3450 $result .= ' AS ' . $prefix . $field;
3457 * Returns the display name of a field in the user table. Works for most fields
3458 * that are commonly displayed to users.
3459 * @param string $field Field name, e.g. 'phone1'
3460 * @return string Text description taken from language file, e.g. 'Phone number'
3462 function get_user_field_name($field) {
3463 // Some fields have language strings which are not the same as field name
3465 case 'phone1' : return get_string('phone');
3467 // Otherwise just use the same lang string
3468 return get_string($field);
3472 * Returns whether a given authentication plugin exists.
3475 * @param string $auth Form of authentication to check for. Defaults to the
3476 * global setting in {@link $CFG}.
3477 * @return boolean Whether the plugin is available.
3479 function exists_auth_plugin($auth) {
3482 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3483 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3489 * Checks if a given plugin is in the list of enabled authentication plugins.
3491 * @param string $auth Authentication plugin.
3492 * @return boolean Whether the plugin is enabled.
3494 function is_enabled_auth($auth) {
3499 $enabled = get_enabled_auth_plugins();
3501 return in_array($auth, $enabled);
3505 * Returns an authentication plugin instance.
3508 * @param string $auth name of authentication plugin
3509 * @return auth_plugin_base An instance of the required authentication plugin.
3511 function get_auth_plugin($auth) {
3514 // check the plugin exists first
3515 if (! exists_auth_plugin($auth)) {
3516 print_error('authpluginnotfound', 'debug', '', $auth);
3519 // return auth plugin instance
3520 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3521 $class = "auth_plugin_$auth";
3526 * Returns array of active auth plugins.
3528 * @param bool $fix fix $CFG->auth if needed
3531 function get_enabled_auth_plugins($fix=false) {
3534 $default = array('manual', 'nologin');
3536 if (empty($CFG->auth)) {
3539 $auths = explode(',', $CFG->auth);
3543 $auths = array_unique($auths);
3544 foreach($auths as $k=>$authname) {
3545 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3549 $newconfig = implode(',', $auths);
3550 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3551 set_config('auth', $newconfig);
3555 return (array_merge($default, $auths));
3559 * Returns true if an internal authentication method is being used.
3560 * if method not specified then, global default is assumed
3562 * @param string $auth Form of authentication required
3565 function is_internal_auth($auth) {
3566 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3567 return $authplugin->is_internal();
3571 * Returns true if the user is a 'restored' one
3573 * Used in the login process to inform the user
3574 * and allow him/her to reset the password
3578 * @param string $username username to be checked
3581 function is_restored_user($username) {
3584 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3588 * Returns an array of user fields
3590 * @return array User field/column names
3592 function get_user_fieldnames() {
3595 $fieldarray = $DB->get_columns('user');
3596 unset($fieldarray['id']);
3597 $fieldarray = array_keys($fieldarray);
3603 * Creates a bare-bones user record
3605 * @todo Outline auth types and provide code example
3607 * @param string $username New user's username to add to record
3608 * @param string $password New user's password to add to record
3609 * @param string $auth Form of authentication required
3610 * @return stdClass A complete user object
3612 function create_user_record($username, $password, $auth = 'manual') {
3615 //just in case check text case
3616 $username = trim(moodle_strtolower($username));
3618 $authplugin = get_auth_plugin($auth);
3620 $newuser = new stdClass();
3622 if ($newinfo = $authplugin->get_userinfo($username)) {
3623 $newinfo = truncate_userinfo($newinfo);
3624 foreach ($newinfo as $key => $value){
3625 $newuser->$key = $value;
3629 if (!empty($newuser->email)) {
3630 if (email_is_not_allowed($newuser->email)) {
3631 unset($newuser->email);
3635 if (!isset($newuser->city)) {
3636 $newuser->city = '';
3639 $newuser->auth = $auth;
3640 $newuser->username = $username;
3643 // user CFG lang for user if $newuser->lang is empty
3644 // or $user->lang is not an installed language
3645 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3646 $newuser->lang = $CFG->lang;
3648 $newuser->confirmed = 1;
3649 $newuser->lastip = getremoteaddr();
3650 $newuser->timecreated = time();
3651 $newuser->timemodified = $newuser->timecreated;
3652 $newuser->mnethostid = $CFG->mnet_localhost_id;
3654 $newuser->id = $DB->insert_record('user', $newuser);
3655 $user = get_complete_user_data('id', $newuser->id);
3656 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3657 set_user_preference('auth_forcepasswordchange', 1, $user);
3659 update_internal_user_password($user, $password);
3661 // fetch full user record for the event, the complete user data contains too much info
3662 // and we want to be consistent with other places that trigger this event
3663 events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
3669 * Will update a local user record from an external source.
3670 * (MNET users can not be updated using this method!)
3672 * @param string $username user's username to update the record
3673 * @return stdClass A complete user object
3675 function update_user_record($username) {
3678 $username = trim(moodle_strtolower($username)); /// just in case check text case
3680 $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
3682 $userauth = get_auth_plugin($oldinfo->auth);
3684 if ($newinfo = $userauth->get_userinfo($username)) {
3685 $newinfo = truncate_userinfo($newinfo);
3686 foreach ($newinfo as $key => $value){
3687 $key = strtolower($key);
3688 if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id'
3689 or $key === 'auth' or $key === 'mnethostid' or $key ===&n