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');
380 /** True if module has code to track whether somebody viewed it */
381 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
382 /** True if module has custom completion rules */
383 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
385 /** True if module has no 'view' page (like label) */
386 define('FEATURE_NO_VIEW_LINK', 'viewlink');
387 /** True if module supports outcomes */
388 define('FEATURE_IDNUMBER', 'idnumber');
389 /** True if module supports groups */
390 define('FEATURE_GROUPS', 'groups');
391 /** True if module supports groupings */
392 define('FEATURE_GROUPINGS', 'groupings');
393 /** True if module supports groupmembersonly */
394 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
396 /** Type of module */
397 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
398 /** True if module supports intro editor */
399 define('FEATURE_MOD_INTRO', 'mod_intro');
400 /** True if module has default completion */
401 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
403 define('FEATURE_COMMENT', 'comment');
405 define('FEATURE_RATE', 'rate');
406 /** True if module supports backup/restore of moodle2 format */
407 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
409 /** True if module can show description on course main page */
410 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
412 /** Unspecified module archetype */
413 define('MOD_ARCHETYPE_OTHER', 0);
414 /** Resource-like type module */
415 define('MOD_ARCHETYPE_RESOURCE', 1);
416 /** Assignment module archetype */
417 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
420 * Security token used for allowing access
421 * from external application such as web services.
422 * Scripts do not use any session, performance is relatively
423 * low because we need to load access info in each request.
424 * Scripts are executed in parallel.
426 define('EXTERNAL_TOKEN_PERMANENT', 0);
429 * Security token used for allowing access
430 * of embedded applications, the code is executed in the
431 * active user session. Token is invalidated after user logs out.
432 * Scripts are executed serially - normal session locking is used.
434 define('EXTERNAL_TOKEN_EMBEDDED', 1);
437 * The home page should be the site home
439 define('HOMEPAGE_SITE', 0);
441 * The home page should be the users my page
443 define('HOMEPAGE_MY', 1);
445 * The home page can be chosen by the user
447 define('HOMEPAGE_USER', 2);
450 * Hub directory url (should be moodle.org)
452 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
456 * Moodle.org url (should be moodle.org)
458 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
461 * Moodle mobile app service name
463 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
465 /// PARAMETER HANDLING ////////////////////////////////////////////////////
468 * Returns a particular value for the named variable, taken from
469 * POST or GET. If the parameter doesn't exist then an error is
470 * thrown because we require this variable.
472 * This function should be used to initialise all required values
473 * in a script that are based on parameters. Usually it will be
475 * $id = required_param('id', PARAM_INT);
477 * Please note the $type parameter is now required and the value can not be array.
479 * @param string $parname the name of the page parameter we want
480 * @param string $type expected type of parameter
483 function required_param($parname, $type) {
484 if (func_num_args() != 2 or empty($parname) or empty($type)) {
485 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
487 if (isset($_POST[$parname])) { // POST has precedence
488 $param = $_POST[$parname];
489 } else if (isset($_GET[$parname])) {
490 $param = $_GET[$parname];
492 print_error('missingparam', '', '', $parname);
495 if (is_array($param)) {
496 debugging('Invalid array parameter detected in required_param(): '.$parname);
497 // TODO: switch to fatal error in Moodle 2.3
498 //print_error('missingparam', '', '', $parname);
499 return required_param_array($parname, $type);
502 return clean_param($param, $type);
506 * Returns a particular array value for the named variable, taken from
507 * POST or GET. If the parameter doesn't exist then an error is
508 * thrown because we require this variable.
510 * This function should be used to initialise all required values
511 * in a script that are based on parameters. Usually it will be
513 * $ids = required_param_array('ids', PARAM_INT);
515 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
517 * @param string $parname the name of the page parameter we want
518 * @param string $type expected type of parameter
521 function required_param_array($parname, $type) {
522 if (func_num_args() != 2 or empty($parname) or empty($type)) {
523 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
525 if (isset($_POST[$parname])) { // POST has precedence
526 $param = $_POST[$parname];
527 } else if (isset($_GET[$parname])) {
528 $param = $_GET[$parname];
530 print_error('missingparam', '', '', $parname);
532 if (!is_array($param)) {
533 print_error('missingparam', '', '', $parname);
537 foreach($param as $key=>$value) {
538 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
539 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
542 $result[$key] = clean_param($value, $type);
549 * Returns a particular value for the named variable, taken from
550 * POST or GET, otherwise returning a given default.
552 * This function should be used to initialise all optional values
553 * in a script that are based on parameters. Usually it will be
555 * $name = optional_param('name', 'Fred', PARAM_TEXT);
557 * Please note the $type parameter is now required and the value can not be array.
559 * @param string $parname the name of the page parameter we want
560 * @param mixed $default the default value to return if nothing is found
561 * @param string $type expected type of parameter
564 function optional_param($parname, $default, $type) {
565 if (func_num_args() != 3 or empty($parname) or empty($type)) {
566 throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
568 if (!isset($default)) {
572 if (isset($_POST[$parname])) { // POST has precedence
573 $param = $_POST[$parname];
574 } else if (isset($_GET[$parname])) {
575 $param = $_GET[$parname];
580 if (is_array($param)) {
581 debugging('Invalid array parameter detected in required_param(): '.$parname);
582 // TODO: switch to $default in Moodle 2.3
584 return optional_param_array($parname, $default, $type);
587 return clean_param($param, $type);
591 * Returns a particular array value for the named variable, taken from
592 * POST or GET, otherwise returning a given default.
594 * This function should be used to initialise all optional values
595 * in a script that are based on parameters. Usually it will be
597 * $ids = optional_param('id', array(), PARAM_INT);
599 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
601 * @param string $parname the name of the page parameter we want
602 * @param mixed $default the default value to return if nothing is found
603 * @param string $type expected type of parameter
606 function optional_param_array($parname, $default, $type) {
607 if (func_num_args() != 3 or empty($parname) or empty($type)) {
608 throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
611 if (isset($_POST[$parname])) { // POST has precedence
612 $param = $_POST[$parname];
613 } else if (isset($_GET[$parname])) {
614 $param = $_GET[$parname];
618 if (!is_array($param)) {
619 debugging('optional_param_array() expects array parameters only: '.$parname);
624 foreach($param as $key=>$value) {
625 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
626 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
629 $result[$key] = clean_param($value, $type);
636 * Strict validation of parameter values, the values are only converted
637 * to requested PHP type. Internally it is using clean_param, the values
638 * before and after cleaning must be equal - otherwise
639 * an invalid_parameter_exception is thrown.
640 * Objects and classes are not accepted.
642 * @param mixed $param
643 * @param string $type PARAM_ constant
644 * @param bool $allownull are nulls valid value?
645 * @param string $debuginfo optional debug information
646 * @return mixed the $param value converted to PHP type or invalid_parameter_exception
648 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
649 if (is_null($param)) {
650 if ($allownull == NULL_ALLOWED) {
653 throw new invalid_parameter_exception($debuginfo);
656 if (is_array($param) or is_object($param)) {
657 throw new invalid_parameter_exception($debuginfo);
660 $cleaned = clean_param($param, $type);
661 if ((string)$param !== (string)$cleaned) {
662 // conversion to string is usually lossless
663 throw new invalid_parameter_exception($debuginfo);
670 * Makes sure array contains only the allowed types,
671 * this function does not validate array key names!
673 * $options = clean_param($options, PARAM_INT);
676 * @param array $param the variable array we are cleaning
677 * @param string $type expected format of param after cleaning.
678 * @param bool $recursive clean recursive arrays
681 function clean_param_array(array $param = null, $type, $recursive = false) {
682 $param = (array)$param; // convert null to empty array
683 foreach ($param as $key => $value) {
684 if (is_array($value)) {
686 $param[$key] = clean_param_array($value, $type, true);
688 throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
691 $param[$key] = clean_param($value, $type);
698 * Used by {@link optional_param()} and {@link required_param()} to
699 * clean the variables and/or cast to specific types, based on
702 * $course->format = clean_param($course->format, PARAM_ALPHA);
703 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
706 * @param mixed $param the variable we are cleaning
707 * @param string $type expected format of param after cleaning.
710 function clean_param($param, $type) {
714 if (is_array($param)) {
715 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
716 } else if (is_object($param)) {
717 if (method_exists($param, '__toString')) {
718 $param = $param->__toString();
720 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
725 case PARAM_RAW: // no cleaning at all
726 $param = fix_utf8($param);
729 case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
730 $param = fix_utf8($param);
733 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
734 // this is deprecated!, please use more specific type instead
735 if (is_numeric($param)) {
738 $param = fix_utf8($param);
739 return clean_text($param); // Sweep for scripts, etc
741 case PARAM_CLEANHTML: // clean html fragment
742 $param = fix_utf8($param);
743 $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
747 return (int)$param; // Convert to integer
751 return (float)$param; // Convert to float
753 case PARAM_ALPHA: // Remove everything not a-z
754 return preg_replace('/[^a-zA-Z]/i', '', $param);
756 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
757 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
759 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
760 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
762 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
763 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
765 case PARAM_SEQUENCE: // Remove everything not 0-9,
766 return preg_replace('/[^0-9,]/i', '', $param);
768 case PARAM_BOOL: // Convert to 1 or 0
769 $tempstr = strtolower($param);
770 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
772 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
775 $param = empty($param) ? 0 : 1;
779 case PARAM_NOTAGS: // Strip all tags
780 $param = fix_utf8($param);
781 return strip_tags($param);
783 case PARAM_TEXT: // leave only tags needed for multilang
784 $param = fix_utf8($param);
785 // if the multilang syntax is not correct we strip all tags
786 // because it would break xhtml strict which is required for accessibility standards
787 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
789 if (strpos($param, '</lang>') !== false) {
790 // old and future mutilang syntax
791 $param = strip_tags($param, '<lang>');
792 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
796 foreach ($matches[0] as $match) {
797 if ($match === '</lang>') {
805 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
816 } else if (strpos($param, '</span>') !== false) {
817 // current problematic multilang syntax
818 $param = strip_tags($param, '<span>');
819 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
823 foreach ($matches[0] as $match) {
824 if ($match === '</span>') {
832 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
844 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
845 return strip_tags($param);
847 case PARAM_COMPONENT:
848 // we do not want any guessing here, either the name is correct or not
849 // please note only normalised component names are accepted
850 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
853 if (strpos($param, '__') !== false) {
856 if (strpos($param, 'mod_') === 0) {
857 // module names must not contain underscores because we need to differentiate them from invalid plugin types
858 if (substr_count($param, '_') != 1) {
866 // we do not want any guessing here, either the name is correct or not
867 if (!preg_match('/^[a-z][a-z0-9_]*[a-z0-9]$/', $param)) {
870 if (strpos($param, '__') !== false) {
875 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
876 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
878 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
879 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
881 case PARAM_FILE: // Strip all suspicious characters from filename
882 $param = fix_utf8($param);
883 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
884 $param = preg_replace('~\.\.+~', '', $param);
885 if ($param === '.') {
890 case PARAM_PATH: // Strip all suspicious characters from file path
891 $param = fix_utf8($param);
892 $param = str_replace('\\', '/', $param);
893 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
894 $param = preg_replace('~\.\.+~', '', $param);
895 $param = preg_replace('~//+~', '/', $param);
896 return preg_replace('~/(\./)+~', '/', $param);
898 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
899 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
900 // match ipv4 dotted quad
901 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
902 // confirm values are ok
906 || $match[4] > 255 ) {
907 // hmmm, what kind of dotted quad is this?
910 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
911 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
912 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
914 // all is ok - $param is respected
921 case PARAM_URL: // allow safe ftp, http, mailto urls
922 $param = fix_utf8($param);
923 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
924 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
925 // all is ok, param is respected
927 $param =''; // not really ok
931 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
932 $param = clean_param($param, PARAM_URL);
933 if (!empty($param)) {
934 if (preg_match(':^/:', $param)) {
935 // root-relative, ok!
936 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
937 // absolute, and matches our wwwroot
939 // relative - let's make sure there are no tricks
940 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
950 $param = trim($param);
951 // PEM formatted strings may contain letters/numbers and the symbols
955 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
956 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
957 list($wholething, $body) = $matches;
958 unset($wholething, $matches);
959 $b64 = clean_param($body, PARAM_BASE64);
961 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
969 if (!empty($param)) {
970 // PEM formatted strings may contain letters/numbers and the symbols
974 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
977 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
978 // Each line of base64 encoded data must be 64 characters in
979 // length, except for the last line which may be less than (or
980 // equal to) 64 characters long.
981 for ($i=0, $j=count($lines); $i < $j; $i++) {
983 if (64 < strlen($lines[$i])) {
989 if (64 != strlen($lines[$i])) {
993 return implode("\n",$lines);
999 $param = fix_utf8($param);
1000 // Please note it is not safe to use the tag name directly anywhere,
1001 // it must be processed with s(), urlencode() before embedding anywhere.
1002 // remove some nasties
1003 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1004 //convert many whitespace chars into one
1005 $param = preg_replace('/\s+/', ' ', $param);
1006 $textlib = textlib_get_instance();
1007 $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
1011 $param = fix_utf8($param);
1012 $tags = explode(',', $param);
1014 foreach ($tags as $tag) {
1015 $res = clean_param($tag, PARAM_TAG);
1021 return implode(',', $result);
1026 case PARAM_CAPABILITY:
1027 if (get_capability_info($param)) {
1033 case PARAM_PERMISSION:
1034 $param = (int)$param;
1035 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1042 $param = clean_param($param, PARAM_PLUGIN);
1043 if (empty($param)) {
1045 } else if (exists_auth_plugin($param)) {
1052 $param = clean_param($param, PARAM_SAFEDIR);
1053 if (get_string_manager()->translation_exists($param)) {
1056 return ''; // Specified language is not installed or param malformed
1060 $param = clean_param($param, PARAM_PLUGIN);
1061 if (empty($param)) {
1063 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1065 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1068 return ''; // Specified theme is not installed
1071 case PARAM_USERNAME:
1072 $param = fix_utf8($param);
1073 $param = str_replace(" " , "", $param);
1074 $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
1075 if (empty($CFG->extendedusernamechars)) {
1076 // regular expression, eliminate all chars EXCEPT:
1077 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1078 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1083 $param = fix_utf8($param);
1084 if (validate_email($param)) {
1090 case PARAM_STRINGID:
1091 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1097 case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1098 $param = fix_utf8($param);
1099 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1100 if (preg_match($timezonepattern, $param)) {
1106 default: // throw error, switched parameters in optional_param or another serious problem
1107 print_error("unknownparamtype", '', '', $type);
1112 * Makes sure the data is using valid utf8, invalid characters are discarded.
1114 * Note: this function is not intended for full objects with methods and private properties.
1116 * @param mixed $value
1117 * @return mixed with proper utf-8 encoding
1119 function fix_utf8($value) {
1120 if (is_null($value) or $value === '') {
1123 } else if (is_string($value)) {
1124 if ((string)(int)$value === $value) {
1128 return iconv('UTF-8', 'UTF-8//IGNORE', $value);
1130 } else if (is_array($value)) {
1131 foreach ($value as $k=>$v) {
1132 $value[$k] = fix_utf8($v);
1136 } else if (is_object($value)) {
1137 $value = clone($value); // do not modify original
1138 foreach ($value as $k=>$v) {
1139 $value->$k = fix_utf8($v);
1144 // this is some other type, no utf-8 here
1150 * Return true if given value is integer or string with integer value
1152 * @param mixed $value String or Int
1153 * @return bool true if number, false if not
1155 function is_number($value) {
1156 if (is_int($value)) {
1158 } else if (is_string($value)) {
1159 return ((string)(int)$value) === $value;
1166 * Returns host part from url
1167 * @param string $url full url
1168 * @return string host, null if not found
1170 function get_host_from_url($url) {
1171 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1179 * Tests whether anything was returned by text editor
1181 * This function is useful for testing whether something you got back from
1182 * the HTML editor actually contains anything. Sometimes the HTML editor
1183 * appear to be empty, but actually you get back a <br> tag or something.
1185 * @param string $string a string containing HTML.
1186 * @return boolean does the string contain any actual content - that is text,
1187 * images, objects, etc.
1189 function html_is_blank($string) {
1190 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1194 * Set a key in global configuration
1196 * Set a key/value pair in both this session's {@link $CFG} global variable
1197 * and in the 'config' database table for future sessions.
1199 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1200 * In that case it doesn't affect $CFG.
1202 * A NULL value will delete the entry.
1206 * @param string $name the key to set
1207 * @param string $value the value to set (without magic quotes)
1208 * @param string $plugin (optional) the plugin scope, default NULL
1209 * @return bool true or exception
1211 function set_config($name, $value, $plugin=NULL) {
1214 if (empty($plugin)) {
1215 if (!array_key_exists($name, $CFG->config_php_settings)) {
1216 // So it's defined for this invocation at least
1217 if (is_null($value)) {
1220 $CFG->$name = (string)$value; // settings from db are always strings
1224 if ($DB->get_field('config', 'name', array('name'=>$name))) {
1225 if ($value === null) {
1226 $DB->delete_records('config', array('name'=>$name));
1228 $DB->set_field('config', 'value', $value, array('name'=>$name));
1231 if ($value !== null) {
1232 $config = new stdClass();
1233 $config->name = $name;
1234 $config->value = $value;
1235 $DB->insert_record('config', $config, false);
1239 } else { // plugin scope
1240 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1241 if ($value===null) {
1242 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1244 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1247 if ($value !== null) {
1248 $config = new stdClass();
1249 $config->plugin = $plugin;
1250 $config->name = $name;
1251 $config->value = $value;
1252 $DB->insert_record('config_plugins', $config, false);
1261 * Get configuration values from the global config table
1262 * or the config_plugins table.
1264 * If called with one parameter, it will load all the config
1265 * variables for one plugin, and return them as an object.
1267 * If called with 2 parameters it will return a string single
1268 * value or false if the value is not found.
1270 * @param string $plugin full component name
1271 * @param string $name default NULL
1272 * @return mixed hash-like object or single value, return false no config found
1274 function get_config($plugin, $name = NULL) {
1277 // normalise component name
1278 if ($plugin === 'moodle' or $plugin === 'core') {
1282 if (!empty($name)) { // the user is asking for a specific value
1283 if (!empty($plugin)) {
1284 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1285 // setting forced in config file
1286 return $CFG->forced_plugin_settings[$plugin][$name];
1288 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1291 if (array_key_exists($name, $CFG->config_php_settings)) {
1292 // setting force in config file
1293 return $CFG->config_php_settings[$name];
1295 return $DB->get_field('config', 'value', array('name'=>$name));
1300 // the user is after a recordset
1302 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1303 if (isset($CFG->forced_plugin_settings[$plugin])) {
1304 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1305 if (is_null($v) or is_array($v) or is_object($v)) {
1306 // we do not want any extra mess here, just real settings that could be saved in db
1307 unset($localcfg[$n]);
1309 //convert to string as if it went through the DB
1310 $localcfg[$n] = (string)$v;
1315 return (object)$localcfg;
1321 // this part is not really used any more, but anyway...
1322 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1323 foreach($CFG->config_php_settings as $n=>$v) {
1324 if (is_null($v) or is_array($v) or is_object($v)) {
1325 // we do not want any extra mess here, just real settings that could be saved in db
1326 unset($localcfg[$n]);
1328 //convert to string as if it went through the DB
1329 $localcfg[$n] = (string)$v;
1332 return (object)$localcfg;
1337 * Removes a key from global configuration
1339 * @param string $name the key to set
1340 * @param string $plugin (optional) the plugin scope
1342 * @return boolean whether the operation succeeded.
1344 function unset_config($name, $plugin=NULL) {
1347 if (empty($plugin)) {
1349 $DB->delete_records('config', array('name'=>$name));
1351 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1358 * Remove all the config variables for a given plugin.
1360 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1361 * @return boolean whether the operation succeeded.
1363 function unset_all_config_for_plugin($plugin) {
1365 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1366 $like = $DB->sql_like('name', '?', true, true, false, '|');
1367 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1368 $DB->delete_records_select('config', $like, $params);
1373 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1375 * All users are verified if they still have the necessary capability.
1377 * @param string $value the value of the config setting.
1378 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1379 * @param bool $include admins, include administrators
1380 * @return array of user objects.
1382 function get_users_from_config($value, $capability, $includeadmins = true) {
1385 if (empty($value) or $value === '$@NONE@$') {
1389 // we have to make sure that users still have the necessary capability,
1390 // it should be faster to fetch them all first and then test if they are present
1391 // instead of validating them one-by-one
1392 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1393 if ($includeadmins) {
1394 $admins = get_admins();
1395 foreach ($admins as $admin) {
1396 $users[$admin->id] = $admin;
1400 if ($value === '$@ALL@$') {
1404 $result = array(); // result in correct order
1405 $allowed = explode(',', $value);
1406 foreach ($allowed as $uid) {
1407 if (isset($users[$uid])) {
1408 $user = $users[$uid];
1409 $result[$user->id] = $user;
1418 * Invalidates browser caches and cached data in temp
1421 function purge_all_caches() {
1424 reset_text_filters_cache();
1425 js_reset_all_caches();
1426 theme_reset_all_caches();
1427 get_string_manager()->reset_caches();
1429 // purge all other caches: rss, simplepie, etc.
1430 remove_dir($CFG->cachedir.'', true);
1432 // make sure cache dir is writable, throws exception if not
1433 make_cache_directory('');
1435 // hack: this script may get called after the purifier was initialised,
1436 // but we do not want to verify repeatedly this exists in each call
1437 make_cache_directory('htmlpurifier');
1443 * Get volatile flags
1445 * @param string $type
1446 * @param int $changedsince default null
1447 * @return records array
1449 function get_cache_flags($type, $changedsince=NULL) {
1452 $params = array('type'=>$type, 'expiry'=>time());
1453 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1454 if ($changedsince !== NULL) {
1455 $params['changedsince'] = $changedsince;
1456 $sqlwhere .= " AND timemodified > :changedsince";
1460 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1461 foreach ($flags as $flag) {
1462 $cf[$flag->name] = $flag->value;
1469 * Get volatile flags
1471 * @param string $type
1472 * @param string $name
1473 * @param int $changedsince default null
1474 * @return records array
1476 function get_cache_flag($type, $name, $changedsince=NULL) {
1479 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1481 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1482 if ($changedsince !== NULL) {
1483 $params['changedsince'] = $changedsince;
1484 $sqlwhere .= " AND timemodified > :changedsince";
1487 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1491 * Set a volatile flag
1493 * @param string $type the "type" namespace for the key
1494 * @param string $name the key to set
1495 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1496 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1497 * @return bool Always returns true
1499 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1502 $timemodified = time();
1503 if ($expiry===NULL || $expiry < $timemodified) {
1504 $expiry = $timemodified + 24 * 60 * 60;
1506 $expiry = (int)$expiry;
1509 if ($value === NULL) {
1510 unset_cache_flag($type,$name);
1514 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1515 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1516 return true; //no need to update; helps rcache too
1519 $f->expiry = $expiry;
1520 $f->timemodified = $timemodified;
1521 $DB->update_record('cache_flags', $f);
1523 $f = new stdClass();
1524 $f->flagtype = $type;
1527 $f->expiry = $expiry;
1528 $f->timemodified = $timemodified;
1529 $DB->insert_record('cache_flags', $f);
1535 * Removes a single volatile flag
1538 * @param string $type the "type" namespace for the key
1539 * @param string $name the key to set
1542 function unset_cache_flag($type, $name) {
1544 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1549 * Garbage-collect volatile flags
1551 * @return bool Always returns true
1553 function gc_cache_flags() {
1555 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1559 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1562 * Refresh user preference cache. This is used most often for $USER
1563 * object that is stored in session, but it also helps with performance in cron script.
1565 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1567 * @param stdClass $user user object, preferences are preloaded into ->preference property
1568 * @param int $cachelifetime cache life time on the current page (ins seconds)
1571 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1573 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1575 if (!isset($user->id)) {
1576 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1579 if (empty($user->id) or isguestuser($user->id)) {
1580 // No permanent storage for not-logged-in users and guest
1581 if (!isset($user->preference)) {
1582 $user->preference = array();
1589 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1590 // Already loaded at least once on this page. Are we up to date?
1591 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1592 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1595 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1596 // no change since the lastcheck on this page
1597 $user->preference['_lastloaded'] = $timenow;
1602 // OK, so we have to reload all preferences
1603 $loadedusers[$user->id] = true;
1604 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1605 $user->preference['_lastloaded'] = $timenow;
1609 * Called from set/delete_user_preferences, so that the prefs can
1610 * be correctly reloaded in different sessions.
1612 * NOTE: internal function, do not call from other code.
1614 * @param integer $userid the user whose prefs were changed.
1617 function mark_user_preferences_changed($userid) {
1620 if (empty($userid) or isguestuser($userid)) {
1621 // no cache flags for guest and not-logged-in users
1625 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1629 * Sets a preference for the specified user.
1631 * If user object submitted, 'preference' property contains the preferences cache.
1633 * @param string $name The key to set as preference for the specified user
1634 * @param string $value The value to set for the $name key in the specified user's record,
1635 * null means delete current value
1636 * @param stdClass|int $user A moodle user object or id, null means current user
1637 * @return bool always true or exception
1639 function set_user_preference($name, $value, $user = null) {
1642 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1643 throw new coding_exception('Invalid preference name in set_user_preference() call');
1646 if (is_null($value)) {
1647 // null means delete current
1648 return unset_user_preference($name, $user);
1649 } else if (is_object($value)) {
1650 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1651 } else if (is_array($value)) {
1652 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1654 $value = (string)$value;
1656 if (is_null($user)) {
1658 } else if (isset($user->id)) {
1659 // $user is valid object
1660 } else if (is_numeric($user)) {
1661 $user = (object)array('id'=>(int)$user);
1663 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1666 check_user_preferences_loaded($user);
1668 if (empty($user->id) or isguestuser($user->id)) {
1669 // no permanent storage for not-logged-in users and guest
1670 $user->preference[$name] = $value;
1674 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1675 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1676 // preference already set to this value
1679 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1682 $preference = new stdClass();
1683 $preference->userid = $user->id;
1684 $preference->name = $name;
1685 $preference->value = $value;
1686 $DB->insert_record('user_preferences', $preference);
1689 // update value in cache
1690 $user->preference[$name] = $value;
1692 // set reload flag for other sessions
1693 mark_user_preferences_changed($user->id);
1699 * Sets a whole array of preferences for the current user
1701 * If user object submitted, 'preference' property contains the preferences cache.
1703 * @param array $prefarray An array of key/value pairs to be set
1704 * @param stdClass|int $user A moodle user object or id, null means current user
1705 * @return bool always true or exception
1707 function set_user_preferences(array $prefarray, $user = null) {
1708 foreach ($prefarray as $name => $value) {
1709 set_user_preference($name, $value, $user);
1715 * Unsets a preference completely by deleting it from the database
1717 * If user object submitted, 'preference' property contains the preferences cache.
1719 * @param string $name The key to unset as preference for the specified user
1720 * @param stdClass|int $user A moodle user object or id, null means current user
1721 * @return bool always true or exception
1723 function unset_user_preference($name, $user = null) {
1726 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1727 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1730 if (is_null($user)) {
1732 } else if (isset($user->id)) {
1733 // $user is valid object
1734 } else if (is_numeric($user)) {
1735 $user = (object)array('id'=>(int)$user);
1737 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1740 check_user_preferences_loaded($user);
1742 if (empty($user->id) or isguestuser($user->id)) {
1743 // no permanent storage for not-logged-in user and guest
1744 unset($user->preference[$name]);
1749 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1751 // delete the preference from cache
1752 unset($user->preference[$name]);
1754 // set reload flag for other sessions
1755 mark_user_preferences_changed($user->id);
1761 * Used to fetch user preference(s)
1763 * If no arguments are supplied this function will return
1764 * all of the current user preferences as an array.
1766 * If a name is specified then this function
1767 * attempts to return that particular preference value. If
1768 * none is found, then the optional value $default is returned,
1771 * If user object submitted, 'preference' property contains the preferences cache.
1773 * @param string $name Name of the key to use in finding a preference value
1774 * @param mixed $default Value to be returned if the $name key is not set in the user preferences
1775 * @param stdClass|int $user A moodle user object or id, null means current user
1776 * @return mixed string value or default
1778 function get_user_preferences($name = null, $default = null, $user = null) {
1781 if (is_null($name)) {
1783 } else if (is_numeric($name) or $name === '_lastloaded') {
1784 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1787 if (is_null($user)) {
1789 } else if (isset($user->id)) {
1790 // $user is valid object
1791 } else if (is_numeric($user)) {
1792 $user = (object)array('id'=>(int)$user);
1794 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1797 check_user_preferences_loaded($user);
1800 return $user->preference; // All values
1801 } else if (isset($user->preference[$name])) {
1802 return $user->preference[$name]; // The single string value
1804 return $default; // Default value (null if not specified)
1808 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1811 * Given date parts in user time produce a GMT timestamp.
1813 * @todo Finish documenting this function
1814 * @param int $year The year part to create timestamp of
1815 * @param int $month The month part to create timestamp of
1816 * @param int $day The day part to create timestamp of
1817 * @param int $hour The hour part to create timestamp of
1818 * @param int $minute The minute part to create timestamp of
1819 * @param int $second The second part to create timestamp of
1820 * @param mixed $timezone Timezone modifier, if 99 then use default user's timezone
1821 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1822 * applied only if timezone is 99 or string.
1823 * @return int timestamp
1825 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1827 //save input timezone, required for dst offset check.
1828 $passedtimezone = $timezone;
1830 $timezone = get_user_timezone_offset($timezone);
1832 if (abs($timezone) > 13) { //server time
1833 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1835 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1836 $time = usertime($time, $timezone);
1838 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1839 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1840 $time -= dst_offset_on($time, $passedtimezone);
1849 * Format a date/time (seconds) as weeks, days, hours etc as needed
1851 * Given an amount of time in seconds, returns string
1852 * formatted nicely as weeks, days, hours etc as needed
1858 * @param int $totalsecs Time in seconds
1859 * @param object $str Should be a time object
1860 * @return string A nicely formatted date/time string
1862 function format_time($totalsecs, $str=NULL) {
1864 $totalsecs = abs($totalsecs);
1866 if (!$str) { // Create the str structure the slow way
1867 $str->day = get_string('day');
1868 $str->days = get_string('days');
1869 $str->hour = get_string('hour');
1870 $str->hours = get_string('hours');
1871 $str->min = get_string('min');
1872 $str->mins = get_string('mins');
1873 $str->sec = get_string('sec');
1874 $str->secs = get_string('secs');
1875 $str->year = get_string('year');
1876 $str->years = get_string('years');
1880 $years = floor($totalsecs/YEARSECS);
1881 $remainder = $totalsecs - ($years*YEARSECS);
1882 $days = floor($remainder/DAYSECS);
1883 $remainder = $totalsecs - ($days*DAYSECS);
1884 $hours = floor($remainder/HOURSECS);
1885 $remainder = $remainder - ($hours*HOURSECS);
1886 $mins = floor($remainder/MINSECS);
1887 $secs = $remainder - ($mins*MINSECS);
1889 $ss = ($secs == 1) ? $str->sec : $str->secs;
1890 $sm = ($mins == 1) ? $str->min : $str->mins;
1891 $sh = ($hours == 1) ? $str->hour : $str->hours;
1892 $sd = ($days == 1) ? $str->day : $str->days;
1893 $sy = ($years == 1) ? $str->year : $str->years;
1901 if ($years) $oyears = $years .' '. $sy;
1902 if ($days) $odays = $days .' '. $sd;
1903 if ($hours) $ohours = $hours .' '. $sh;
1904 if ($mins) $omins = $mins .' '. $sm;
1905 if ($secs) $osecs = $secs .' '. $ss;
1907 if ($years) return trim($oyears .' '. $odays);
1908 if ($days) return trim($odays .' '. $ohours);
1909 if ($hours) return trim($ohours .' '. $omins);
1910 if ($mins) return trim($omins .' '. $osecs);
1911 if ($secs) return $osecs;
1912 return get_string('now');
1916 * Returns a formatted string that represents a date in user time
1918 * Returns a formatted string that represents a date in user time
1919 * <b>WARNING: note that the format is for strftime(), not date().</b>
1920 * Because of a bug in most Windows time libraries, we can't use
1921 * the nicer %e, so we have to use %d which has leading zeroes.
1922 * A lot of the fuss in the function is just getting rid of these leading
1923 * zeroes as efficiently as possible.
1925 * If parameter fixday = true (default), then take off leading
1926 * zero from %d, else maintain it.
1928 * @param int $date the timestamp in UTC, as obtained from the database.
1929 * @param string $format strftime format. You should probably get this using
1930 * get_string('strftime...', 'langconfig');
1931 * @param mixed $timezone by default, uses the user's time zone. if numeric and
1932 * not 99 then daylight saving will not be added.
1933 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1934 * If false then the leading zero is maintained.
1935 * @return string the formatted date/time.
1937 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1941 if (empty($format)) {
1942 $format = get_string('strftimedaydatetime', 'langconfig');
1945 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1947 } else if ($fixday) {
1948 $formatnoday = str_replace('%d', 'DD', $format);
1949 $fixday = ($formatnoday != $format);
1952 //add daylight saving offset for string timezones only, as we can't get dst for
1953 //float values. if timezone is 99 (user default timezone), then try update dst.
1954 if ((99 == $timezone) || !is_numeric($timezone)) {
1955 $date += dst_offset_on($date, $timezone);
1958 $timezone = get_user_timezone_offset($timezone);
1960 if (abs($timezone) > 13) { /// Server time
1962 $datestring = strftime($formatnoday, $date);
1963 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
1964 $datestring = str_replace('DD', $daystring, $datestring);
1966 $datestring = strftime($format, $date);
1969 $date += (int)($timezone * 3600);
1971 $datestring = gmstrftime($formatnoday, $date);
1972 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
1973 $datestring = str_replace('DD', $daystring, $datestring);
1975 $datestring = gmstrftime($format, $date);
1979 /// If we are running under Windows convert from windows encoding to UTF-8
1980 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1982 if ($CFG->ostype == 'WINDOWS') {
1983 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1984 $textlib = textlib_get_instance();
1985 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1993 * Given a $time timestamp in GMT (seconds since epoch),
1994 * returns an array that represents the date in user time
1996 * @todo Finish documenting this function
1998 * @param int $time Timestamp in GMT
1999 * @param mixed $timezone offset time with timezone, if float and not 99, then no
2000 * dst offset is applyed
2001 * @return array An array that represents the date in user time
2003 function usergetdate($time, $timezone=99) {
2005 //save input timezone, required for dst offset check.
2006 $passedtimezone = $timezone;
2008 $timezone = get_user_timezone_offset($timezone);
2010 if (abs($timezone) > 13) { // Server time
2011 return getdate($time);
2014 //add daylight saving offset for string timezones only, as we can't get dst for
2015 //float values. if timezone is 99 (user default timezone), then try update dst.
2016 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2017 $time += dst_offset_on($time, $passedtimezone);
2020 $time += intval((float)$timezone * HOURSECS);
2022 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2024 //be careful to ensure the returned array matches that produced by getdate() above
2027 $getdate['weekday'],
2034 $getdate['minutes'],
2036 ) = explode('_', $datestring);
2042 * Given a GMT timestamp (seconds since epoch), offsets it by
2043 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2046 * @param int $date Timestamp in GMT
2047 * @param float $timezone
2050 function usertime($date, $timezone=99) {
2052 $timezone = get_user_timezone_offset($timezone);
2054 if (abs($timezone) > 13) {
2057 return $date - (int)($timezone * HOURSECS);
2061 * Given a time, return the GMT timestamp of the most recent midnight
2062 * for the current user.
2064 * @param int $date Timestamp in GMT
2065 * @param float $timezone Defaults to user's timezone
2066 * @return int Returns a GMT timestamp
2068 function usergetmidnight($date, $timezone=99) {
2070 $userdate = usergetdate($date, $timezone);
2072 // Time of midnight of this user's day, in GMT
2073 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2078 * Returns a string that prints the user's timezone
2080 * @param float $timezone The user's timezone
2083 function usertimezone($timezone=99) {
2085 $tz = get_user_timezone($timezone);
2087 if (!is_float($tz)) {
2091 if(abs($tz) > 13) { // Server time
2092 return get_string('serverlocaltime');
2095 if($tz == intval($tz)) {
2096 // Don't show .0 for whole hours
2113 * Returns a float which represents the user's timezone difference from GMT in hours
2114 * Checks various settings and picks the most dominant of those which have a value
2118 * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
2121 function get_user_timezone_offset($tz = 99) {
2125 $tz = get_user_timezone($tz);
2127 if (is_float($tz)) {
2130 $tzrecord = get_timezone_record($tz);
2131 if (empty($tzrecord)) {
2134 return (float)$tzrecord->gmtoff / HOURMINS;
2139 * Returns an int which represents the systems's timezone difference from GMT in seconds
2142 * @param mixed $tz timezone
2143 * @return int if found, false is timezone 99 or error
2145 function get_timezone_offset($tz) {
2152 if (is_numeric($tz)) {
2153 return intval($tz * 60*60);
2156 if (!$tzrecord = get_timezone_record($tz)) {
2159 return intval($tzrecord->gmtoff * 60);
2163 * Returns a float or a string which denotes the user's timezone
2164 * 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)
2165 * means that for this timezone there are also DST rules to be taken into account
2166 * Checks various settings and picks the most dominant of those which have a value
2170 * @param mixed $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
2173 function get_user_timezone($tz = 99) {
2178 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2179 isset($USER->timezone) ? $USER->timezone : 99,
2180 isset($CFG->timezone) ? $CFG->timezone : 99,
2185 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
2186 $tz = $next['value'];
2189 return is_numeric($tz) ? (float) $tz : $tz;
2193 * Returns cached timezone record for given $timezonename
2197 * @param string $timezonename
2198 * @return mixed timezonerecord object or false
2200 function get_timezone_record($timezonename) {
2202 static $cache = NULL;
2204 if ($cache === NULL) {
2208 if (isset($cache[$timezonename])) {
2209 return $cache[$timezonename];
2212 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2213 WHERE name = ? ORDER BY year DESC', array($timezonename), true);
2217 * Build and store the users Daylight Saving Time (DST) table
2222 * @param mixed $from_year Start year for the table, defaults to 1971
2223 * @param mixed $to_year End year for the table, defaults to 2035
2224 * @param mixed $strtimezone, if null or 99 then user's default timezone is used
2227 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2228 global $CFG, $SESSION, $DB;
2230 $usertz = get_user_timezone($strtimezone);
2232 if (is_float($usertz)) {
2233 // Trivial timezone, no DST
2237 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2238 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2239 unset($SESSION->dst_offsets);
2240 unset($SESSION->dst_range);
2243 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2244 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2245 // This will be the return path most of the time, pretty light computationally
2249 // Reaching here means we either need to extend our table or create it from scratch
2251 // Remember which TZ we calculated these changes for
2252 $SESSION->dst_offsettz = $usertz;
2254 if(empty($SESSION->dst_offsets)) {
2255 // If we 're creating from scratch, put the two guard elements in there
2256 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2258 if(empty($SESSION->dst_range)) {
2259 // If creating from scratch
2260 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2261 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2263 // Fill in the array with the extra years we need to process
2264 $yearstoprocess = array();
2265 for($i = $from; $i <= $to; ++$i) {
2266 $yearstoprocess[] = $i;
2269 // Take note of which years we have processed for future calls
2270 $SESSION->dst_range = array($from, $to);
2273 // If needing to extend the table, do the same
2274 $yearstoprocess = array();
2276 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2277 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2279 if($from < $SESSION->dst_range[0]) {
2280 // Take note of which years we need to process and then note that we have processed them for future calls
2281 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2282 $yearstoprocess[] = $i;
2284 $SESSION->dst_range[0] = $from;
2286 if($to > $SESSION->dst_range[1]) {
2287 // Take note of which years we need to process and then note that we have processed them for future calls
2288 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2289 $yearstoprocess[] = $i;
2291 $SESSION->dst_range[1] = $to;
2295 if(empty($yearstoprocess)) {
2296 // This means that there was a call requesting a SMALLER range than we have already calculated
2300 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2301 // Also, the array is sorted in descending timestamp order!
2305 static $presets_cache = array();
2306 if (!isset($presets_cache[$usertz])) {
2307 $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');
2309 if(empty($presets_cache[$usertz])) {
2313 // Remove ending guard (first element of the array)
2314 reset($SESSION->dst_offsets);
2315 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2317 // Add all required change timestamps
2318 foreach($yearstoprocess as $y) {
2319 // Find the record which is in effect for the year $y
2320 foreach($presets_cache[$usertz] as $year => $preset) {
2326 $changes = dst_changes_for_year($y, $preset);
2328 if($changes === NULL) {
2331 if($changes['dst'] != 0) {
2332 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2334 if($changes['std'] != 0) {
2335 $SESSION->dst_offsets[$changes['std']] = 0;
2339 // Put in a guard element at the top
2340 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2341 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2344 krsort($SESSION->dst_offsets);
2350 * Calculates the required DST change and returns a Timestamp Array
2354 * @param mixed $year Int or String Year to focus on
2355 * @param object $timezone Instatiated Timezone object
2356 * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
2358 function dst_changes_for_year($year, $timezone) {
2360 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2364 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2365 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2367 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2368 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2370 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2371 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2373 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2374 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2375 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2377 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2378 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2380 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2384 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2385 * - Note: Daylight saving only works for string timezones and not for float.
2388 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2389 * @param mixed $strtimezone timezone for which offset is expected, if 99 or null
2390 * then user's default timezone is used.
2393 function dst_offset_on($time, $strtimezone = NULL) {
2396 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2400 reset($SESSION->dst_offsets);
2401 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2402 if($from <= $time) {
2407 // This is the normal return path
2408 if($offset !== NULL) {
2412 // Reaching this point means we haven't calculated far enough, do it now:
2413 // Calculate extra DST changes if needed and recurse. The recursion always
2414 // moves toward the stopping condition, so will always end.
2417 // We need a year smaller than $SESSION->dst_range[0]
2418 if($SESSION->dst_range[0] == 1971) {
2421 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2422 return dst_offset_on($time, $strtimezone);
2425 // We need a year larger than $SESSION->dst_range[1]
2426 if($SESSION->dst_range[1] == 2035) {
2429 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2430 return dst_offset_on($time, $strtimezone);
2437 * @todo Document what this function does
2438 * @param int $startday
2439 * @param int $weekday
2444 function find_day_in_month($startday, $weekday, $month, $year) {
2446 $daysinmonth = days_in_month($month, $year);
2448 if($weekday == -1) {
2449 // Don't care about weekday, so return:
2450 // abs($startday) if $startday != -1
2451 // $daysinmonth otherwise
2452 return ($startday == -1) ? $daysinmonth : abs($startday);
2455 // From now on we 're looking for a specific weekday
2457 // Give "end of month" its actual value, since we know it
2458 if($startday == -1) {
2459 $startday = -1 * $daysinmonth;
2462 // Starting from day $startday, the sign is the direction
2466 $startday = abs($startday);
2467 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2469 // This is the last such weekday of the month
2470 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2471 if($lastinmonth > $daysinmonth) {
2475 // Find the first such weekday <= $startday
2476 while($lastinmonth > $startday) {
2480 return $lastinmonth;
2485 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2487 $diff = $weekday - $indexweekday;
2492 // This is the first such weekday of the month equal to or after $startday
2493 $firstfromindex = $startday + $diff;
2495 return $firstfromindex;
2501 * Calculate the number of days in a given month
2503 * @param int $month The month whose day count is sought
2504 * @param int $year The year of the month whose day count is sought
2507 function days_in_month($month, $year) {
2508 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2512 * Calculate the position in the week of a specific calendar day
2514 * @param int $day The day of the date whose position in the week is sought
2515 * @param int $month The month of the date whose position in the week is sought
2516 * @param int $year The year of the date whose position in the week is sought
2519 function dayofweek($day, $month, $year) {
2520 // I wonder if this is any different from
2521 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2522 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2525 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2528 * Returns full login url.
2530 * @return string login url
2532 function get_login_url() {
2535 $url = "$CFG->wwwroot/login/index.php";
2537 if (!empty($CFG->loginhttps)) {
2538 $url = str_replace('http:', 'https:', $url);
2545 * This function checks that the current user is logged in and has the
2546 * required privileges
2548 * This function checks that the current user is logged in, and optionally
2549 * whether they are allowed to be in a particular course and view a particular
2551 * If they are not logged in, then it redirects them to the site login unless
2552 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2553 * case they are automatically logged in as guests.
2554 * If $courseid is given and the user is not enrolled in that course then the
2555 * user is redirected to the course enrolment page.
2556 * If $cm is given and the course module is hidden and the user is not a teacher
2557 * in the course then the user is redirected to the course home page.
2559 * When $cm parameter specified, this function sets page layout to 'module'.
2560 * You need to change it manually later if some other layout needed.
2562 * @param mixed $courseorid id of the course or course object
2563 * @param bool $autologinguest default true
2564 * @param object $cm course module object
2565 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2566 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2567 * in order to keep redirects working properly. MDL-14495
2568 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2569 * @return mixed Void, exit, and die depending on path
2571 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2572 global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2574 // setup global $COURSE, themes, language and locale
2575 if (!empty($courseorid)) {
2576 if (is_object($courseorid)) {
2577 $course = $courseorid;
2578 } else if ($courseorid == SITEID) {
2579 $course = clone($SITE);
2581 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2584 if ($cm->course != $course->id) {
2585 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2587 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2588 if (!($cm instanceof cm_info)) {
2589 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2590 // db queries so this is not really a performance concern, however it is obviously
2591 // better if you use get_fast_modinfo to get the cm before calling this.
2592 $modinfo = get_fast_modinfo($course);
2593 $cm = $modinfo->get_cm($cm->id);
2595 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2596 $PAGE->set_pagelayout('incourse');
2598 $PAGE->set_course($course); // set's up global $COURSE
2601 // do not touch global $COURSE via $PAGE->set_course(),
2602 // the reasons is we need to be able to call require_login() at any time!!
2605 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2609 // If the user is not even logged in yet then make sure they are
2610 if (!isloggedin()) {
2611 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2612 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2613 // misconfigured site guest, just redirect to login page
2614 redirect(get_login_url());
2615 exit; // never reached
2617 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2618 complete_user_login($guest);
2619 $USER->autologinguest = true;
2620 $SESSION->lang = $lang;
2622 //NOTE: $USER->site check was obsoleted by session test cookie,
2623 // $USER->confirmed test is in login/index.php
2624 if ($preventredirect) {
2625 throw new require_login_exception('You are not logged in');
2628 if ($setwantsurltome) {
2629 // TODO: switch to PAGE->url
2630 $SESSION->wantsurl = $FULLME;
2632 if (!empty($_SERVER['HTTP_REFERER'])) {
2633 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2635 redirect(get_login_url());
2636 exit; // never reached
2640 // loginas as redirection if needed
2641 if ($course->id != SITEID and session_is_loggedinas()) {
2642 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2643 if ($USER->loginascontext->instanceid != $course->id) {
2644 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2649 // check whether the user should be changing password (but only if it is REALLY them)
2650 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2651 $userauth = get_auth_plugin($USER->auth);
2652 if ($userauth->can_change_password() and !$preventredirect) {
2653 $SESSION->wantsurl = $FULLME;
2654 if ($changeurl = $userauth->change_password_url()) {
2655 //use plugin custom url
2656 redirect($changeurl);
2658 //use moodle internal method
2659 if (empty($CFG->loginhttps)) {
2660 redirect($CFG->wwwroot .'/login/change_password.php');
2662 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2663 redirect($wwwroot .'/login/change_password.php');
2667 print_error('nopasswordchangeforced', 'auth');
2671 // Check that the user account is properly set up
2672 if (user_not_fully_set_up($USER)) {
2673 if ($preventredirect) {
2674 throw new require_login_exception('User not fully set-up');
2676 $SESSION->wantsurl = $FULLME;
2677 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2680 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2683 // Do not bother admins with any formalities
2684 if (is_siteadmin()) {
2685 //set accesstime or the user will appear offline which messes up messaging
2686 user_accesstime_log($course->id);
2690 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2691 if (!$USER->policyagreed and !is_siteadmin()) {
2692 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2693 if ($preventredirect) {
2694 throw new require_login_exception('Policy not agreed');
2696 $SESSION->wantsurl = $FULLME;
2697 redirect($CFG->wwwroot .'/user/policy.php');
2698 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2699 if ($preventredirect) {
2700 throw new require_login_exception('Policy not agreed');
2702 $SESSION->wantsurl = $FULLME;
2703 redirect($CFG->wwwroot .'/user/policy.php');
2707 // Fetch the system context, the course context, and prefetch its child contexts
2708 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2709 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2711 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2716 // If the site is currently under maintenance, then print a message
2717 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2718 if ($preventredirect) {
2719 throw new require_login_exception('Maintenance in progress');
2722 print_maintenance_message();
2725 // make sure the course itself is not hidden
2726 if ($course->id == SITEID) {
2727 // frontpage can not be hidden
2729 if (is_role_switched($course->id)) {
2730 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2732 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2733 // originally there was also test of parent category visibility,
2734 // BUT is was very slow in complex queries involving "my courses"
2735 // now it is also possible to simply hide all courses user is not enrolled in :-)
2736 if ($preventredirect) {
2737 throw new require_login_exception('Course is hidden');
2739 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2744 // is the user enrolled?
2745 if ($course->id == SITEID) {
2746 // everybody is enrolled on the frontpage
2749 if (session_is_loggedinas()) {
2750 // Make sure the REAL person can access this course first
2751 $realuser = session_get_realuser();
2752 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2753 if ($preventredirect) {
2754 throw new require_login_exception('Invalid course login-as access');
2756 echo $OUTPUT->header();
2757 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2761 // very simple enrolment caching - changes in course setting are not reflected immediately
2762 if (!isset($USER->enrol)) {
2763 $USER->enrol = array();
2764 $USER->enrol['enrolled'] = array();
2765 $USER->enrol['tempguest'] = array();
2770 if (is_viewing($coursecontext, $USER)) {
2771 // ok, no need to mess with enrol
2775 if (isset($USER->enrol['enrolled'][$course->id])) {
2776 if ($USER->enrol['enrolled'][$course->id] == 0) {
2778 } else if ($USER->enrol['enrolled'][$course->id] > time()) {
2782 unset($USER->enrol['enrolled'][$course->id]);
2785 if (isset($USER->enrol['tempguest'][$course->id])) {
2786 if ($USER->enrol['tempguest'][$course->id] == 0) {
2788 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2792 unset($USER->enrol['tempguest'][$course->id]);
2793 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2799 } else if (is_enrolled($coursecontext, $USER, '', true)) {
2800 // active participants may always access
2801 // TODO: refactor this into some new function
2803 $sql = "SELECT MAX(ue.timeend)
2804 FROM {user_enrolments} ue
2805 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2806 JOIN {user} u ON u.id = ue.userid
2807 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0
2808 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
2809 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE,
2810 'userid'=>$USER->id, 'courseid'=>$coursecontext->instanceid, 'now1'=>$now, 'now2'=>$now);
2811 $until = $DB->get_field_sql($sql, $params);
2812 if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) {
2813 $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD;
2816 $USER->enrol['enrolled'][$course->id] = $until;
2819 // remove traces of previous temp guest access
2820 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2823 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2824 $enrols = enrol_get_plugins(true);
2825 // first ask all enabled enrol instances in course if they want to auto enrol user
2826 foreach($instances as $instance) {
2827 if (!isset($enrols[$instance->enrol])) {
2830 // Get a duration for the guestaccess, a timestamp in the future or false.
2831 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2832 if ($until !== false) {
2833 $USER->enrol['enrolled'][$course->id] = $until;
2834 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2839 // if not enrolled yet try to gain temporary guest access
2841 foreach($instances as $instance) {
2842 if (!isset($enrols[$instance->enrol])) {
2845 // Get a duration for the guestaccess, a timestamp in the future or false.
2846 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2847 if ($until !== false) {
2848 $USER->enrol['tempguest'][$course->id] = $until;
2858 if ($preventredirect) {
2859 throw new require_login_exception('Not enrolled');
2861 $SESSION->wantsurl = $FULLME;
2862 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2866 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
2867 // conditional availability, etc
2868 if ($cm && !$cm->uservisible) {
2869 if ($preventredirect) {
2870 throw new require_login_exception('Activity is hidden');
2872 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2875 // Finally access granted, update lastaccess times
2876 user_accesstime_log($course->id);
2881 * This function just makes sure a user is logged out.
2885 function require_logout() {
2891 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2893 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2894 foreach($authsequence as $authname) {
2895 $authplugin = get_auth_plugin($authname);
2896 $authplugin->prelogout_hook();
2900 events_trigger('user_logout', $params);
2901 session_get_instance()->terminate_current();
2906 * Weaker version of require_login()
2908 * This is a weaker version of {@link require_login()} which only requires login
2909 * when called from within a course rather than the site page, unless
2910 * the forcelogin option is turned on.
2911 * @see require_login()
2914 * @param mixed $courseorid The course object or id in question
2915 * @param bool $autologinguest Allow autologin guests if that is wanted
2916 * @param object $cm Course activity module if known
2917 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2918 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2919 * in order to keep redirects working properly. MDL-14495
2920 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2923 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2924 global $CFG, $PAGE, $SITE;
2925 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
2926 or (!is_object($courseorid) and $courseorid == SITEID);
2927 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2928 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2929 // db queries so this is not really a performance concern, however it is obviously
2930 // better if you use get_fast_modinfo to get the cm before calling this.
2931 if (is_object($courseorid)) {
2932 $course = $courseorid;
2934 $course = clone($SITE);
2936 $modinfo = get_fast_modinfo($course);
2937 $cm = $modinfo->get_cm($cm->id);
2939 if (!empty($CFG->forcelogin)) {
2940 // login required for both SITE and courses
2941 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2943 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2944 // always login for hidden activities
2945 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2947 } else if ($issite) {
2948 //login for SITE not required
2949 if ($cm and empty($cm->visible)) {
2950 // hidden activities are not accessible without login
2951 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2952 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2953 // not-logged-in users do not have any group membership
2954 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2956 // We still need to instatiate PAGE vars properly so that things
2957 // that rely on it like navigation function correctly.
2958 if (!empty($courseorid)) {
2959 if (is_object($courseorid)) {
2960 $course = $courseorid;
2962 $course = clone($SITE);
2965 if ($cm->course != $course->id) {
2966 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2968 $PAGE->set_cm($cm, $course);
2969 $PAGE->set_pagelayout('incourse');
2971 $PAGE->set_course($course);
2974 // If $PAGE->course, and hence $PAGE->context, have not already been set
2975 // up properly, set them up now.
2976 $PAGE->set_course($PAGE->course);
2978 //TODO: verify conditional activities here
2979 user_accesstime_log(SITEID);
2984 // course login always required
2985 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2990 * Require key login. Function terminates with error if key not found or incorrect.
2996 * @uses NO_MOODLE_COOKIES
2997 * @uses PARAM_ALPHANUM
2998 * @param string $script unique script identifier
2999 * @param int $instance optional instance id
3000 * @return int Instance ID
3002 function require_user_key_login($script, $instance=null) {
3003 global $USER, $SESSION, $CFG, $DB;
3005 if (!NO_MOODLE_COOKIES) {
3006 print_error('sessioncookiesdisable');
3010 @session_write_close();
3012 $keyvalue = required_param('key', PARAM_ALPHANUM);
3014 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3015 print_error('invalidkey');
3018 if (!empty($key->validuntil) and $key->validuntil < time()) {
3019 print_error('expiredkey');
3022 if ($key->iprestriction) {
3023 $remoteaddr = getremoteaddr(null);
3024 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3025 print_error('ipmismatch');
3029 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
3030 print_error('invaliduserid');
3033 /// emulate normal session
3034 session_set_user($user);
3036 /// note we are not using normal login
3037 if (!defined('USER_KEY_LOGIN')) {
3038 define('USER_KEY_LOGIN', true);
3041 /// return instance id - it might be empty
3042 return $key->instance;
3046 * Creates a new private user access key.
3049 * @param string $script unique target identifier
3050 * @param int $userid
3051 * @param int $instance optional instance id
3052 * @param string $iprestriction optional ip restricted access
3053 * @param timestamp $validuntil key valid only until given data
3054 * @return string access key value
3056 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3059 $key = new stdClass();
3060 $key->script = $script;
3061 $key->userid = $userid;
3062 $key->instance = $instance;
3063 $key->iprestriction = $iprestriction;
3064 $key->validuntil = $validuntil;
3065 $key->timecreated = time();
3067 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
3068 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3070 $key->value = md5($userid.'_'.time().random_string(40));
3072 $DB->insert_record('user_private_key', $key);
3077 * Delete the user's new private user access keys for a particular script.
3080 * @param string $script unique target identifier
3081 * @param int $userid
3084 function delete_user_key($script,$userid) {
3086 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3090 * Gets a private user access key (and creates one if one doesn't exist).
3093 * @param string $script unique target identifier
3094 * @param int $userid
3095 * @param int $instance optional instance id
3096 * @param string $iprestriction optional ip restricted access
3097 * @param timestamp $validuntil key valid only until given data
3098 * @return string access key value
3100 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3103 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3104 'instance'=>$instance, 'iprestriction'=>$iprestriction,
3105 'validuntil'=>$validuntil))) {
3108 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3114 * Modify the user table by setting the currently logged in user's
3115 * last login to now.
3119 * @return bool Always returns true
3121 function update_user_login_times() {
3124 $user = new stdClass();
3125 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3126 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
3128 $user->id = $USER->id;
3130 $DB->update_record('user', $user);
3135 * Determines if a user has completed setting up their account.
3137 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3140 function user_not_fully_set_up($user) {
3141 if (isguestuser($user)) {
3144 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3148 * Check whether the user has exceeded the bounce threshold
3152 * @param user $user A {@link $USER} object
3153 * @return bool true=>User has exceeded bounce threshold
3155 function over_bounce_threshold($user) {
3158 if (empty($CFG->handlebounces)) {
3162 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3166 // set sensible defaults
3167 if (empty($CFG->minbounces)) {
3168 $CFG->minbounces = 10;
3170 if (empty($CFG->bounceratio)) {
3171 $CFG->bounceratio = .20;
3175 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3176 $bouncecount = $bounce->value;
3178 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3179 $sendcount = $send->value;
3181 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3185 * Used to increment or reset email sent count
3188 * @param user $user object containing an id
3189 * @param bool $reset will reset the count to 0
3192 function set_send_count($user,$reset=false) {
3195 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3199 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3200 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3201 $DB->update_record('user_preferences', $pref);
3203 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3205 $pref = new stdClass();
3206 $pref->name = 'email_send_count';
3208 $pref->userid = $user->id;
3209 $DB->insert_record('user_preferences', $pref, false);
3214 * Increment or reset user's email bounce count
3217 * @param user $user object containing an id
3218 * @param bool $reset will reset the count to 0
3220 function set_bounce_count($user,$reset=false) {
3223 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3224 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3225 $DB->update_record('user_preferences', $pref);
3227 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3229 $pref = new stdClass();
3230 $pref->name = 'email_bounce_count';
3232 $pref->userid = $user->id;
3233 $DB->insert_record('user_preferences', $pref, false);
3238 * Keeps track of login attempts
3242 function update_login_count() {
3247 if (empty($SESSION->logincount)) {
3248 $SESSION->logincount = 1;
3250 $SESSION->logincount++;
3253 if ($SESSION->logincount > $max_logins) {
3254 unset($SESSION->wantsurl);
3255 print_error('errortoomanylogins');
3260 * Resets login attempts
3264 function reset_login_count() {
3267 $SESSION->logincount = 0;
3271 * Determines if the currently logged in user is in editing mode.
3272 * Note: originally this function had $userid parameter - it was not usable anyway
3274 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3275 * @todo Deprecated function remove when ready
3278 * @uses DEBUG_DEVELOPER
3281 function isediting() {
3283 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3284 return $PAGE->user_is_editing();
3288 * Determines if the logged in user is currently moving an activity
3291 * @param int $courseid The id of the course being tested
3294 function ismoving($courseid) {
3297 if (!empty($USER->activitycopy)) {
3298 return ($USER->activitycopycourse == $courseid);
3304 * Returns a persons full name
3306 * Given an object containing firstname and lastname
3307 * values, this function returns a string with the
3308 * full name of the person.
3309 * The result may depend on system settings
3310 * or language. 'override' will force both names
3311 * to be used even if system settings specify one.
3315 * @param object $user A {@link $USER} object to get full name of
3316 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3319 function fullname($user, $override=false) {
3320 global $CFG, $SESSION;
3322 if (!isset($user->firstname) and !isset($user->lastname)) {
3327 if (!empty($CFG->forcefirstname)) {
3328 $user->firstname = $CFG->forcefirstname;
3330 if (!empty($CFG->forcelastname)) {
3331 $user->lastname = $CFG->forcelastname;
3335 if (!empty($SESSION->fullnamedisplay)) {
3336 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3339 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3340 return $user->firstname .' '. $user->lastname;
3342 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3343 return $user->lastname .' '. $user->firstname;
3345 } else if ($CFG->fullnamedisplay == 'firstname') {
3347 return get_string('fullnamedisplay', '', $user);
3349 return $user->firstname;
3353 return get_string('fullnamedisplay', '', $user);
3357 * Returns whether a given authentication plugin exists.
3360 * @param string $auth Form of authentication to check for. Defaults to the
3361 * global setting in {@link $CFG}.
3362 * @return boolean Whether the plugin is available.
3364 function exists_auth_plugin($auth) {
3367 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3368 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3374 * Checks if a given plugin is in the list of enabled authentication plugins.
3376 * @param string $auth Authentication plugin.
3377 * @return boolean Whether the plugin is enabled.
3379 function is_enabled_auth($auth) {
3384 $enabled = get_enabled_auth_plugins();
3386 return in_array($auth, $enabled);
3390 * Returns an authentication plugin instance.
3393 * @param string $auth name of authentication plugin
3394 * @return auth_plugin_base An instance of the required authentication plugin.
3396 function get_auth_plugin($auth) {
3399 // check the plugin exists first
3400 if (! exists_auth_plugin($auth)) {
3401 print_error('authpluginnotfound', 'debug', '', $auth);
3404 // return auth plugin instance
3405 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3406 $class = "auth_plugin_$auth";
3411 * Returns array of active auth plugins.
3413 * @param bool $fix fix $CFG->auth if needed
3416 function get_enabled_auth_plugins($fix=false) {
3419 $default = array('manual', 'nologin');
3421 if (empty($CFG->auth)) {
3424 $auths = explode(',', $CFG->auth);
3428 $auths = array_unique($auths);
3429 foreach($auths as $k=>$authname) {
3430 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3434 $newconfig = implode(',', $auths);
3435 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3436 set_config('auth', $newconfig);
3440 return (array_merge($default, $auths));
3444 * Returns true if an internal authentication method is being used.
3445 * if method not specified then, global default is assumed
3447 * @param string $auth Form of authentication required
3450 function is_internal_auth($auth) {
3451 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3452 return $authplugin->is_internal();
3456 * Returns true if the user is a 'restored' one
3458 * Used in the login process to inform the user
3459 * and allow him/her to reset the password
3463 * @param string $username username to be checked
3466 function is_restored_user($username) {
3469 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3473 * Returns an array of user fields
3475 * @return array User field/column names
3477 function get_user_fieldnames() {
3480 $fieldarray = $DB->get_columns('user');
3481 unset($fieldarray['id']);
3482 $fieldarray = array_keys($fieldarray);
3488 * Creates a bare-bones user record
3490 * @todo Outline auth types and provide code example
3492 * @param string $username New user's username to add to record
3493 * @param string $password New user's password to add to record
3494 * @param string $auth Form of authentication required
3495 * @return stdClass A complete user object
3497 function create_user_record($username, $password, $auth = 'manual') {
3500 //just in case check text case
3501 $username = trim(moodle_strtolower($username));
3503 $authplugin = get_auth_plugin($auth);
3505 $newuser = new stdClass();
3507 if ($newinfo = $authplugin->get_userinfo($username)) {
3508 $newinfo = truncate_userinfo($newinfo);
3509 foreach ($newinfo as $key => $value){
3510 $newuser->$key = $value;
3514 if (!empty($newuser->email)) {
3515 if (email_is_not_allowed($newuser->email)) {
3516 unset($newuser->email);
3520 if (!isset($newuser->city)) {
3521 $newuser->city = '';
3524 $newuser->auth = $auth;
3525 $newuser->username = $username;
3528 // user CFG lang for user if $newuser->lang is empty
3529 // or $user->lang is not an installed language
3530 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3531 $newuser->lang = $CFG->lang;
3533 $newuser->confirmed = 1;
3534 $newuser->lastip = getremoteaddr();
3535 $newuser->timemodified = time();
3536 $newuser->mnethostid = $CFG->mnet_localhost_id;
3538 $newuser->id = $DB->insert_record('user', $newuser);
3539 $user = get_complete_user_data('id', $newuser->id);
3540 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3541 set_user_preference('auth_forcepasswordchange', 1, $user);
3543 update_internal_user_password($user, $password);
3545 // fetch full user record for the event, the complete user data contains too much info
3546 // and we want to be consistent with other places that trigger this event
3547 events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
3553 * Will update a local user record from an external source.
3554 * (MNET users can not be updated using this method!)
3556 * @param string $username user's username to update the record
3557 * @return stdClass A complete user object
3559 function update_user_record($username) {
3562 $username = trim(moodle_strtolower($username)); /// just in case check text case
3564 $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
3566 $userauth = get_auth_plugin($oldinfo->auth);
3568 if ($newinfo = $userauth->get_userinfo($username)) {
3569 $newinfo = truncate_userinfo($newinfo);
3570 foreach ($newinfo as $key => $value){
3571 $key = strtolower($key);
3572 if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id'
3573 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3574 // unknown or must not be changed
3577 $confval = $userauth->config->{'field_updatelocal_' . $key};
3578 $lockval = $userauth->config->{'field_lock_' . $key};
3579 if (empty($confval) || empty($lockval)) {
3582 if ($confval === 'onlogin') {
3583 // MDL-4207 Don't overwrite modified user profile values with
3584 // empty LDAP values when 'unlocked if empty' is set. The purpose
3585 // of the setting 'unlocked if empty' is to allow the user to fill
3586 // in a value for the selected field _if LDAP is giving
3587 // nothing_ for this field. Thus it makes sense to let this value
3588 // stand in until LDAP is giving a value for this field.
3589 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3590 if ((string)$oldinfo->$key !== (string)$value) {
3591 $newuser[$key] = (string)$value;
3597 $newuser['id'] = $oldinfo->id;
3598 $DB->update_record('user', $newuser);
3599 // fetch full user record for the event, the complete user data contains too much info
3600 // and we want to be consistent with other places that trigger this event
3601 events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id)));
3605 return get_complete_user_data('id', $oldinfo->id);
3609 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3610 * which may have large fields
3612 * @todo Add vartype handling to ensure $info is an array
3614 * @param array $info Array of user properties to truncate if needed
3615 * @return array The now truncated information that was passed in
3617 function truncate_userinfo($info) {
3618 // define the limits
3628 'institution' => 40,
3636 $textlib = textlib_get_instance();
3637 // apply where needed
3638 foreach (array_keys($info) as $key) {
3639 if (!empty($limit[$key])) {
3640 $info[$key] = trim($textlib->substr($info[$key],0, $limit[$key]));
3648 * Marks user deleted in internal user database and notifies the auth plugin.
3649 * Also unenrols user from all roles and does other cleanup.
3651 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3653 * @param stdClass $user full user object before delete
3654 * @return boolean always true
3656 function delete_user($user) {
3658 require_once($CFG->libdir.'/grouplib.php');
3659 require_once($CFG->libdir.'/gradelib.php');
3660 require_once($CFG->dirroot.'/message/lib.php');
3661 require_once($CFG->dirroot.'/tag/lib.php');
3663 // delete all grades - backup is kept in grade_grades_history table
3664 grade_user_delete($user->id);
3666 //move unread messages from this user to read
3667 message_move_userfrom_unread2read($user->id);
3669 // TODO: remove from cohorts using standard API here
3672 tag_set('user', $user->id, array());
3674 // unconditionally unenrol from all courses
3675 enrol_user_delete($user);
3677 // unenrol from all roles in all contexts
3678 role_unassign_all(array('userid'=>$user->id)); // this might be slow but it is really needed - modules might do some extra cleanup!
3680 //now do a brute force cleanup
3682 // remove from all cohorts
3683 $DB->delete_records('cohort_members',&nbs