3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * moodlelib.php - Moodle main library
21 * Main library file of miscellaneous general-purpose Moodle functions.
22 * Other main libraries:
23 * - weblib.php - functions that produce web output
24 * - datalib.php - functions that access the database
28 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32 defined('MOODLE_INTERNAL') || die();
34 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
36 /// Date and time constants ///
38 * Time constant - the number of seconds in a year
40 define('YEARSECS', 31536000);
43 * Time constant - the number of seconds in a week
45 define('WEEKSECS', 604800);
48 * Time constant - the number of seconds in a day
50 define('DAYSECS', 86400);
53 * Time constant - the number of seconds in an hour
55 define('HOURSECS', 3600);
58 * Time constant - the number of seconds in a minute
60 define('MINSECS', 60);
63 * Time constant - the number of minutes in a day
65 define('DAYMINS', 1440);
68 * Time constant - the number of minutes in an hour
70 define('HOURMINS', 60);
72 /// Parameter constants - every call to optional_param(), required_param() ///
73 /// or clean_param() should have a specified type of parameter. //////////////
78 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
80 define('PARAM_ALPHA', 'alpha');
83 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
84 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
86 define('PARAM_ALPHAEXT', 'alphaext');
89 * PARAM_ALPHANUM - expected numbers and letters only.
91 define('PARAM_ALPHANUM', 'alphanum');
94 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
96 define('PARAM_ALPHANUMEXT', 'alphanumext');
99 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
101 define('PARAM_AUTH', 'auth');
104 * PARAM_BASE64 - Base 64 encoded format
106 define('PARAM_BASE64', 'base64');
109 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
111 define('PARAM_BOOL', 'bool');
114 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
115 * checked against the list of capabilities in the database.
117 define('PARAM_CAPABILITY', 'capability');
120 * PARAM_CLEANHTML - cleans submitted HTML code. use only for text in HTML format. This cleaning may fix xhtml strictness too.
122 define('PARAM_CLEANHTML', 'cleanhtml');
125 * PARAM_EMAIL - an email address following the RFC
127 define('PARAM_EMAIL', 'email');
130 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
132 define('PARAM_FILE', 'file');
135 * PARAM_FLOAT - a real/floating point number.
137 define('PARAM_FLOAT', 'float');
140 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
142 define('PARAM_HOST', 'host');
145 * PARAM_INT - integers only, use when expecting only numbers.
147 define('PARAM_INT', 'int');
150 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
152 define('PARAM_LANG', 'lang');
155 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
157 define('PARAM_LOCALURL', 'localurl');
160 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
162 define('PARAM_NOTAGS', 'notags');
165 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
166 * note: the leading slash is not removed, window drive letter is not allowed
168 define('PARAM_PATH', 'path');
171 * PARAM_PEM - Privacy Enhanced Mail format
173 define('PARAM_PEM', 'pem');
176 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
178 define('PARAM_PERMISSION', 'permission');
181 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
183 define('PARAM_RAW', 'raw');
186 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
188 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
191 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
193 define('PARAM_SAFEDIR', 'safedir');
196 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
198 define('PARAM_SAFEPATH', 'safepath');
201 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
203 define('PARAM_SEQUENCE', 'sequence');
206 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
208 define('PARAM_TAG', 'tag');
211 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
213 define('PARAM_TAGLIST', 'taglist');
216 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
218 define('PARAM_TEXT', 'text');
221 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
223 define('PARAM_THEME', 'theme');
226 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
228 define('PARAM_URL', 'url');
231 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user accounts, do NOT use when syncing with external systems!!
233 define('PARAM_USERNAME', 'username');
236 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
238 define('PARAM_STRINGID', 'stringid');
240 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
242 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
243 * It was one of the first types, that is why it is abused so much ;-)
244 * @deprecated since 2.0
246 define('PARAM_CLEAN', 'clean');
249 * PARAM_INTEGER - deprecated alias for PARAM_INT
251 define('PARAM_INTEGER', 'int');
254 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
256 define('PARAM_NUMBER', 'float');
259 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
260 * NOTE: originally alias for PARAM_APLHA
262 define('PARAM_ACTION', 'alphanumext');
265 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
266 * NOTE: originally alias for PARAM_APLHA
268 define('PARAM_FORMAT', 'alphanumext');
271 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
273 define('PARAM_MULTILANG', 'text');
276 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
277 * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
278 * America/Port-au-Prince)
280 define('PARAM_TIMEZONE', 'timezone');
283 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
285 define('PARAM_CLEANFILE', 'file');
288 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
289 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
290 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
291 * NOTE: numbers and underscores are strongly discouraged in plugin names!
293 define('PARAM_COMPONENT', 'component');
296 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
297 * It is usually used together with context id and component.
298 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
300 define('PARAM_AREA', 'area');
303 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
304 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
305 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
307 define('PARAM_PLUGIN', 'plugin');
313 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
315 define('VALUE_REQUIRED', 1);
318 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
320 define('VALUE_OPTIONAL', 2);
323 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
325 define('VALUE_DEFAULT', 0);
328 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
330 define('NULL_NOT_ALLOWED', false);
333 * NULL_ALLOWED - the parameter can be set to null in the database
335 define('NULL_ALLOWED', true);
339 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
341 define('PAGE_COURSE_VIEW', 'course-view');
343 /** Get remote addr constant */
344 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
345 /** Get remote addr constant */
346 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
348 /// Blog access level constant declaration ///
349 define ('BLOG_USER_LEVEL', 1);
350 define ('BLOG_GROUP_LEVEL', 2);
351 define ('BLOG_COURSE_LEVEL', 3);
352 define ('BLOG_SITE_LEVEL', 4);
353 define ('BLOG_GLOBAL_LEVEL', 5);
358 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
359 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
360 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
362 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
364 define('TAG_MAX_LENGTH', 50);
366 /// Password policy constants ///
367 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
368 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
369 define ('PASSWORD_DIGITS', '0123456789');
370 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
372 /// Feature constants ///
373 // Used for plugin_supports() to report features that are, or are not, supported by a module.
375 /** True if module can provide a grade */
376 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
377 /** True if module supports outcomes */
378 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
379 /** True if module supports advanced grading methods */
380 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
382 /** True if module has code to track whether somebody viewed it */
383 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
384 /** True if module has custom completion rules */
385 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
387 /** True if module has no 'view' page (like label) */
388 define('FEATURE_NO_VIEW_LINK', 'viewlink');
389 /** True if module supports outcomes */
390 define('FEATURE_IDNUMBER', 'idnumber');
391 /** True if module supports groups */
392 define('FEATURE_GROUPS', 'groups');
393 /** True if module supports groupings */
394 define('FEATURE_GROUPINGS', 'groupings');
395 /** True if module supports groupmembersonly */
396 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
398 /** Type of module */
399 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
400 /** True if module supports intro editor */
401 define('FEATURE_MOD_INTRO', 'mod_intro');
402 /** True if module has default completion */
403 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
405 define('FEATURE_COMMENT', 'comment');
407 define('FEATURE_RATE', 'rate');
408 /** True if module supports backup/restore of moodle2 format */
409 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
411 /** True if module can show description on course main page */
412 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
414 /** Unspecified module archetype */
415 define('MOD_ARCHETYPE_OTHER', 0);
416 /** Resource-like type module */
417 define('MOD_ARCHETYPE_RESOURCE', 1);
418 /** Assignment module archetype */
419 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
422 * Security token used for allowing access
423 * from external application such as web services.
424 * Scripts do not use any session, performance is relatively
425 * low because we need to load access info in each request.
426 * Scripts are executed in parallel.
428 define('EXTERNAL_TOKEN_PERMANENT', 0);
431 * Security token used for allowing access
432 * of embedded applications, the code is executed in the
433 * active user session. Token is invalidated after user logs out.
434 * Scripts are executed serially - normal session locking is used.
436 define('EXTERNAL_TOKEN_EMBEDDED', 1);
439 * The home page should be the site home
441 define('HOMEPAGE_SITE', 0);
443 * The home page should be the users my page
445 define('HOMEPAGE_MY', 1);
447 * The home page can be chosen by the user
449 define('HOMEPAGE_USER', 2);
452 * Hub directory url (should be moodle.org)
454 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
458 * Moodle.org url (should be moodle.org)
460 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
463 * Moodle mobile app service name
465 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
467 /// PARAMETER HANDLING ////////////////////////////////////////////////////
470 * Returns a particular value for the named variable, taken from
471 * POST or GET. If the parameter doesn't exist then an error is
472 * thrown because we require this variable.
474 * This function should be used to initialise all required values
475 * in a script that are based on parameters. Usually it will be
477 * $id = required_param('id', PARAM_INT);
479 * Please note the $type parameter is now required and the value can not be array.
481 * @param string $parname the name of the page parameter we want
482 * @param string $type expected type of parameter
485 function required_param($parname, $type) {
486 if (func_num_args() != 2 or empty($parname) or empty($type)) {
487 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
489 if (isset($_POST[$parname])) { // POST has precedence
490 $param = $_POST[$parname];
491 } else if (isset($_GET[$parname])) {
492 $param = $_GET[$parname];
494 print_error('missingparam', '', '', $parname);
497 if (is_array($param)) {
498 debugging('Invalid array parameter detected in required_param(): '.$parname);
499 // TODO: switch to fatal error in Moodle 2.3
500 //print_error('missingparam', '', '', $parname);
501 return required_param_array($parname, $type);
504 return clean_param($param, $type);
508 * Returns a particular array value for the named variable, taken from
509 * POST or GET. If the parameter doesn't exist then an error is
510 * thrown because we require this variable.
512 * This function should be used to initialise all required values
513 * in a script that are based on parameters. Usually it will be
515 * $ids = required_param_array('ids', PARAM_INT);
517 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
519 * @param string $parname the name of the page parameter we want
520 * @param string $type expected type of parameter
523 function required_param_array($parname, $type) {
524 if (func_num_args() != 2 or empty($parname) or empty($type)) {
525 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
527 if (isset($_POST[$parname])) { // POST has precedence
528 $param = $_POST[$parname];
529 } else if (isset($_GET[$parname])) {
530 $param = $_GET[$parname];
532 print_error('missingparam', '', '', $parname);
534 if (!is_array($param)) {
535 print_error('missingparam', '', '', $parname);
539 foreach($param as $key=>$value) {
540 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
541 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
544 $result[$key] = clean_param($value, $type);
551 * Returns a particular value for the named variable, taken from
552 * POST or GET, otherwise returning a given default.
554 * This function should be used to initialise all optional values
555 * in a script that are based on parameters. Usually it will be
557 * $name = optional_param('name', 'Fred', PARAM_TEXT);
559 * Please note the $type parameter is now required and the value can not be array.
561 * @param string $parname the name of the page parameter we want
562 * @param mixed $default the default value to return if nothing is found
563 * @param string $type expected type of parameter
566 function optional_param($parname, $default, $type) {
567 if (func_num_args() != 3 or empty($parname) or empty($type)) {
568 throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
570 if (!isset($default)) {
574 if (isset($_POST[$parname])) { // POST has precedence
575 $param = $_POST[$parname];
576 } else if (isset($_GET[$parname])) {
577 $param = $_GET[$parname];
582 if (is_array($param)) {
583 debugging('Invalid array parameter detected in required_param(): '.$parname);
584 // TODO: switch to $default in Moodle 2.3
586 return optional_param_array($parname, $default, $type);
589 return clean_param($param, $type);
593 * Returns a particular array value for the named variable, taken from
594 * POST or GET, otherwise returning a given default.
596 * This function should be used to initialise all optional values
597 * in a script that are based on parameters. Usually it will be
599 * $ids = optional_param('id', array(), PARAM_INT);
601 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
603 * @param string $parname the name of the page parameter we want
604 * @param mixed $default the default value to return if nothing is found
605 * @param string $type expected type of parameter
608 function optional_param_array($parname, $default, $type) {
609 if (func_num_args() != 3 or empty($parname) or empty($type)) {
610 throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
613 if (isset($_POST[$parname])) { // POST has precedence
614 $param = $_POST[$parname];
615 } else if (isset($_GET[$parname])) {
616 $param = $_GET[$parname];
620 if (!is_array($param)) {
621 debugging('optional_param_array() expects array parameters only: '.$parname);
626 foreach($param as $key=>$value) {
627 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
628 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
631 $result[$key] = clean_param($value, $type);
638 * Strict validation of parameter values, the values are only converted
639 * to requested PHP type. Internally it is using clean_param, the values
640 * before and after cleaning must be equal - otherwise
641 * an invalid_parameter_exception is thrown.
642 * Objects and classes are not accepted.
644 * @param mixed $param
645 * @param string $type PARAM_ constant
646 * @param bool $allownull are nulls valid value?
647 * @param string $debuginfo optional debug information
648 * @return mixed the $param value converted to PHP type or invalid_parameter_exception
650 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
651 if (is_null($param)) {
652 if ($allownull == NULL_ALLOWED) {
655 throw new invalid_parameter_exception($debuginfo);
658 if (is_array($param) or is_object($param)) {
659 throw new invalid_parameter_exception($debuginfo);
662 $cleaned = clean_param($param, $type);
663 if ((string)$param !== (string)$cleaned) {
664 // conversion to string is usually lossless
665 throw new invalid_parameter_exception($debuginfo);
672 * Makes sure array contains only the allowed types,
673 * this function does not validate array key names!
675 * $options = clean_param($options, PARAM_INT);
678 * @param array $param the variable array we are cleaning
679 * @param string $type expected format of param after cleaning.
680 * @param bool $recursive clean recursive arrays
683 function clean_param_array(array $param = null, $type, $recursive = false) {
684 $param = (array)$param; // convert null to empty array
685 foreach ($param as $key => $value) {
686 if (is_array($value)) {
688 $param[$key] = clean_param_array($value, $type, true);
690 throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
693 $param[$key] = clean_param($value, $type);
700 * Used by {@link optional_param()} and {@link required_param()} to
701 * clean the variables and/or cast to specific types, based on
704 * $course->format = clean_param($course->format, PARAM_ALPHA);
705 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
708 * @param mixed $param the variable we are cleaning
709 * @param string $type expected format of param after cleaning.
712 function clean_param($param, $type) {
716 if (is_array($param)) {
717 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
718 } else if (is_object($param)) {
719 if (method_exists($param, '__toString')) {
720 $param = $param->__toString();
722 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
727 case PARAM_RAW: // no cleaning at all
728 $param = fix_utf8($param);
731 case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
732 $param = fix_utf8($param);
735 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
736 // this is deprecated!, please use more specific type instead
737 if (is_numeric($param)) {
740 $param = fix_utf8($param);
741 return clean_text($param); // Sweep for scripts, etc
743 case PARAM_CLEANHTML: // clean html fragment
744 $param = fix_utf8($param);
745 $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
749 return (int)$param; // Convert to integer
753 return (float)$param; // Convert to float
755 case PARAM_ALPHA: // Remove everything not a-z
756 return preg_replace('/[^a-zA-Z]/i', '', $param);
758 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
759 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
761 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
762 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
764 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
765 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
767 case PARAM_SEQUENCE: // Remove everything not 0-9,
768 return preg_replace('/[^0-9,]/i', '', $param);
770 case PARAM_BOOL: // Convert to 1 or 0
771 $tempstr = strtolower($param);
772 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
774 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
777 $param = empty($param) ? 0 : 1;
781 case PARAM_NOTAGS: // Strip all tags
782 $param = fix_utf8($param);
783 return strip_tags($param);
785 case PARAM_TEXT: // leave only tags needed for multilang
786 $param = fix_utf8($param);
787 // if the multilang syntax is not correct we strip all tags
788 // because it would break xhtml strict which is required for accessibility standards
789 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
791 if (strpos($param, '</lang>') !== false) {
792 // old and future mutilang syntax
793 $param = strip_tags($param, '<lang>');
794 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
798 foreach ($matches[0] as $match) {
799 if ($match === '</lang>') {
807 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
818 } else if (strpos($param, '</span>') !== false) {
819 // current problematic multilang syntax
820 $param = strip_tags($param, '<span>');
821 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
825 foreach ($matches[0] as $match) {
826 if ($match === '</span>') {
834 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
846 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
847 return strip_tags($param);
849 case PARAM_COMPONENT:
850 // we do not want any guessing here, either the name is correct or not
851 // please note only normalised component names are accepted
852 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
855 if (strpos($param, '__') !== false) {
858 if (strpos($param, 'mod_') === 0) {
859 // module names must not contain underscores because we need to differentiate them from invalid plugin types
860 if (substr_count($param, '_') != 1) {
868 // we do not want any guessing here, either the name is correct or not
869 if (!preg_match('/^[a-z][a-z0-9_]*[a-z0-9]$/', $param)) {
872 if (strpos($param, '__') !== false) {
877 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
878 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
880 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
881 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
883 case PARAM_FILE: // Strip all suspicious characters from filename
884 $param = fix_utf8($param);
885 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
886 $param = preg_replace('~\.\.+~', '', $param);
887 if ($param === '.') {
892 case PARAM_PATH: // Strip all suspicious characters from file path
893 $param = fix_utf8($param);
894 $param = str_replace('\\', '/', $param);
895 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
896 $param = preg_replace('~\.\.+~', '', $param);
897 $param = preg_replace('~//+~', '/', $param);
898 return preg_replace('~/(\./)+~', '/', $param);
900 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
901 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
902 // match ipv4 dotted quad
903 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
904 // confirm values are ok
908 || $match[4] > 255 ) {
909 // hmmm, what kind of dotted quad is this?
912 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
913 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
914 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
916 // all is ok - $param is respected
923 case PARAM_URL: // allow safe ftp, http, mailto urls
924 $param = fix_utf8($param);
925 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
926 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
927 // all is ok, param is respected
929 $param =''; // not really ok
933 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
934 $param = clean_param($param, PARAM_URL);
935 if (!empty($param)) {
936 if (preg_match(':^/:', $param)) {
937 // root-relative, ok!
938 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
939 // absolute, and matches our wwwroot
941 // relative - let's make sure there are no tricks
942 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
952 $param = trim($param);
953 // PEM formatted strings may contain letters/numbers and the symbols
957 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
958 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
959 list($wholething, $body) = $matches;
960 unset($wholething, $matches);
961 $b64 = clean_param($body, PARAM_BASE64);
963 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
971 if (!empty($param)) {
972 // PEM formatted strings may contain letters/numbers and the symbols
976 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
979 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
980 // Each line of base64 encoded data must be 64 characters in
981 // length, except for the last line which may be less than (or
982 // equal to) 64 characters long.
983 for ($i=0, $j=count($lines); $i < $j; $i++) {
985 if (64 < strlen($lines[$i])) {
991 if (64 != strlen($lines[$i])) {
995 return implode("\n",$lines);
1001 $param = fix_utf8($param);
1002 // Please note it is not safe to use the tag name directly anywhere,
1003 // it must be processed with s(), urlencode() before embedding anywhere.
1004 // remove some nasties
1005 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1006 //convert many whitespace chars into one
1007 $param = preg_replace('/\s+/', ' ', $param);
1008 $textlib = textlib_get_instance();
1009 $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
1013 $param = fix_utf8($param);
1014 $tags = explode(',', $param);
1016 foreach ($tags as $tag) {
1017 $res = clean_param($tag, PARAM_TAG);
1023 return implode(',', $result);
1028 case PARAM_CAPABILITY:
1029 if (get_capability_info($param)) {
1035 case PARAM_PERMISSION:
1036 $param = (int)$param;
1037 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1044 $param = clean_param($param, PARAM_PLUGIN);
1045 if (empty($param)) {
1047 } else if (exists_auth_plugin($param)) {
1054 $param = clean_param($param, PARAM_SAFEDIR);
1055 if (get_string_manager()->translation_exists($param)) {
1058 return ''; // Specified language is not installed or param malformed
1062 $param = clean_param($param, PARAM_PLUGIN);
1063 if (empty($param)) {
1065 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1067 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1070 return ''; // Specified theme is not installed
1073 case PARAM_USERNAME:
1074 $param = fix_utf8($param);
1075 $param = str_replace(" " , "", $param);
1076 $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
1077 if (empty($CFG->extendedusernamechars)) {
1078 // regular expression, eliminate all chars EXCEPT:
1079 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1080 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1085 $param = fix_utf8($param);
1086 if (validate_email($param)) {
1092 case PARAM_STRINGID:
1093 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1099 case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1100 $param = fix_utf8($param);
1101 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1102 if (preg_match($timezonepattern, $param)) {
1108 default: // throw error, switched parameters in optional_param or another serious problem
1109 print_error("unknownparamtype", '', '', $type);
1114 * Makes sure the data is using valid utf8, invalid characters are discarded.
1116 * Note: this function is not intended for full objects with methods and private properties.
1118 * @param mixed $value
1119 * @return mixed with proper utf-8 encoding
1121 function fix_utf8($value) {
1122 if (is_null($value) or $value === '') {
1125 } else if (is_string($value)) {
1126 if ((string)(int)$value === $value) {
1130 return iconv('UTF-8', 'UTF-8//IGNORE', $value);
1132 } else if (is_array($value)) {
1133 foreach ($value as $k=>$v) {
1134 $value[$k] = fix_utf8($v);
1138 } else if (is_object($value)) {
1139 $value = clone($value); // do not modify original
1140 foreach ($value as $k=>$v) {
1141 $value->$k = fix_utf8($v);
1146 // this is some other type, no utf-8 here
1152 * Return true if given value is integer or string with integer value
1154 * @param mixed $value String or Int
1155 * @return bool true if number, false if not
1157 function is_number($value) {
1158 if (is_int($value)) {
1160 } else if (is_string($value)) {
1161 return ((string)(int)$value) === $value;
1168 * Returns host part from url
1169 * @param string $url full url
1170 * @return string host, null if not found
1172 function get_host_from_url($url) {
1173 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1181 * Tests whether anything was returned by text editor
1183 * This function is useful for testing whether something you got back from
1184 * the HTML editor actually contains anything. Sometimes the HTML editor
1185 * appear to be empty, but actually you get back a <br> tag or something.
1187 * @param string $string a string containing HTML.
1188 * @return boolean does the string contain any actual content - that is text,
1189 * images, objects, etc.
1191 function html_is_blank($string) {
1192 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1196 * Set a key in global configuration
1198 * Set a key/value pair in both this session's {@link $CFG} global variable
1199 * and in the 'config' database table for future sessions.
1201 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1202 * In that case it doesn't affect $CFG.
1204 * A NULL value will delete the entry.
1208 * @param string $name the key to set
1209 * @param string $value the value to set (without magic quotes)
1210 * @param string $plugin (optional) the plugin scope, default NULL
1211 * @return bool true or exception
1213 function set_config($name, $value, $plugin=NULL) {
1216 if (empty($plugin)) {
1217 if (!array_key_exists($name, $CFG->config_php_settings)) {
1218 // So it's defined for this invocation at least
1219 if (is_null($value)) {
1222 $CFG->$name = (string)$value; // settings from db are always strings
1226 if ($DB->get_field('config', 'name', array('name'=>$name))) {
1227 if ($value === null) {
1228 $DB->delete_records('config', array('name'=>$name));
1230 $DB->set_field('config', 'value', $value, array('name'=>$name));
1233 if ($value !== null) {
1234 $config = new stdClass();
1235 $config->name = $name;
1236 $config->value = $value;
1237 $DB->insert_record('config', $config, false);
1241 } else { // plugin scope
1242 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1243 if ($value===null) {
1244 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1246 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1249 if ($value !== null) {
1250 $config = new stdClass();
1251 $config->plugin = $plugin;
1252 $config->name = $name;
1253 $config->value = $value;
1254 $DB->insert_record('config_plugins', $config, false);
1263 * Get configuration values from the global config table
1264 * or the config_plugins table.
1266 * If called with one parameter, it will load all the config
1267 * variables for one plugin, and return them as an object.
1269 * If called with 2 parameters it will return a string single
1270 * value or false if the value is not found.
1272 * @param string $plugin full component name
1273 * @param string $name default NULL
1274 * @return mixed hash-like object or single value, return false no config found
1276 function get_config($plugin, $name = NULL) {
1279 // normalise component name
1280 if ($plugin === 'moodle' or $plugin === 'core') {
1284 if (!empty($name)) { // the user is asking for a specific value
1285 if (!empty($plugin)) {
1286 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1287 // setting forced in config file
1288 return $CFG->forced_plugin_settings[$plugin][$name];
1290 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1293 if (array_key_exists($name, $CFG->config_php_settings)) {
1294 // setting force in config file
1295 return $CFG->config_php_settings[$name];
1297 return $DB->get_field('config', 'value', array('name'=>$name));
1302 // the user is after a recordset
1304 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1305 if (isset($CFG->forced_plugin_settings[$plugin])) {
1306 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1307 if (is_null($v) or is_array($v) or is_object($v)) {
1308 // we do not want any extra mess here, just real settings that could be saved in db
1309 unset($localcfg[$n]);
1311 //convert to string as if it went through the DB
1312 $localcfg[$n] = (string)$v;
1317 return (object)$localcfg;
1323 // this part is not really used any more, but anyway...
1324 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1325 foreach($CFG->config_php_settings as $n=>$v) {
1326 if (is_null($v) or is_array($v) or is_object($v)) {
1327 // we do not want any extra mess here, just real settings that could be saved in db
1328 unset($localcfg[$n]);
1330 //convert to string as if it went through the DB
1331 $localcfg[$n] = (string)$v;
1334 return (object)$localcfg;
1339 * Removes a key from global configuration
1341 * @param string $name the key to set
1342 * @param string $plugin (optional) the plugin scope
1344 * @return boolean whether the operation succeeded.
1346 function unset_config($name, $plugin=NULL) {
1349 if (empty($plugin)) {
1351 $DB->delete_records('config', array('name'=>$name));
1353 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1360 * Remove all the config variables for a given plugin.
1362 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1363 * @return boolean whether the operation succeeded.
1365 function unset_all_config_for_plugin($plugin) {
1367 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1368 $like = $DB->sql_like('name', '?', true, true, false, '|');
1369 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1370 $DB->delete_records_select('config', $like, $params);
1375 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1377 * All users are verified if they still have the necessary capability.
1379 * @param string $value the value of the config setting.
1380 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1381 * @param bool $include admins, include administrators
1382 * @return array of user objects.
1384 function get_users_from_config($value, $capability, $includeadmins = true) {
1387 if (empty($value) or $value === '$@NONE@$') {
1391 // we have to make sure that users still have the necessary capability,
1392 // it should be faster to fetch them all first and then test if they are present
1393 // instead of validating them one-by-one
1394 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1395 if ($includeadmins) {
1396 $admins = get_admins();
1397 foreach ($admins as $admin) {
1398 $users[$admin->id] = $admin;
1402 if ($value === '$@ALL@$') {
1406 $result = array(); // result in correct order
1407 $allowed = explode(',', $value);
1408 foreach ($allowed as $uid) {
1409 if (isset($users[$uid])) {
1410 $user = $users[$uid];
1411 $result[$user->id] = $user;
1420 * Invalidates browser caches and cached data in temp
1423 function purge_all_caches() {
1426 reset_text_filters_cache();
1427 js_reset_all_caches();
1428 theme_reset_all_caches();
1429 get_string_manager()->reset_caches();
1431 // purge all other caches: rss, simplepie, etc.
1432 remove_dir($CFG->cachedir.'', true);
1434 // make sure cache dir is writable, throws exception if not
1435 make_cache_directory('');
1437 // hack: this script may get called after the purifier was initialised,
1438 // but we do not want to verify repeatedly this exists in each call
1439 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;
1655 if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1656 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1659 if (is_null($user)) {
1661 } else if (isset($user->id)) {
1662 // $user is valid object
1663 } else if (is_numeric($user)) {
1664 $user = (object)array('id'=>(int)$user);
1666 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1669 check_user_preferences_loaded($user);
1671 if (empty($user->id) or isguestuser($user->id)) {
1672 // no permanent storage for not-logged-in users and guest
1673 $user->preference[$name] = $value;
1677 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1678 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1679 // preference already set to this value
1682 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1685 $preference = new stdClass();
1686 $preference->userid = $user->id;
1687 $preference->name = $name;
1688 $preference->value = $value;
1689 $DB->insert_record('user_preferences', $preference);
1692 // update value in cache
1693 $user->preference[$name] = $value;
1695 // set reload flag for other sessions
1696 mark_user_preferences_changed($user->id);
1702 * Sets a whole array of preferences for the current user
1704 * If user object submitted, 'preference' property contains the preferences cache.
1706 * @param array $prefarray An array of key/value pairs to be set
1707 * @param stdClass|int $user A moodle user object or id, null means current user
1708 * @return bool always true or exception
1710 function set_user_preferences(array $prefarray, $user = null) {
1711 foreach ($prefarray as $name => $value) {
1712 set_user_preference($name, $value, $user);
1718 * Unsets a preference completely by deleting it from the database
1720 * If user object submitted, 'preference' property contains the preferences cache.
1722 * @param string $name The key to unset as preference for the specified user
1723 * @param stdClass|int $user A moodle user object or id, null means current user
1724 * @return bool always true or exception
1726 function unset_user_preference($name, $user = null) {
1729 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1730 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1733 if (is_null($user)) {
1735 } else if (isset($user->id)) {
1736 // $user is valid object
1737 } else if (is_numeric($user)) {
1738 $user = (object)array('id'=>(int)$user);
1740 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1743 check_user_preferences_loaded($user);
1745 if (empty($user->id) or isguestuser($user->id)) {
1746 // no permanent storage for not-logged-in user and guest
1747 unset($user->preference[$name]);
1752 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1754 // delete the preference from cache
1755 unset($user->preference[$name]);
1757 // set reload flag for other sessions
1758 mark_user_preferences_changed($user->id);
1764 * Used to fetch user preference(s)
1766 * If no arguments are supplied this function will return
1767 * all of the current user preferences as an array.
1769 * If a name is specified then this function
1770 * attempts to return that particular preference value. If
1771 * none is found, then the optional value $default is returned,
1774 * If user object submitted, 'preference' property contains the preferences cache.
1776 * @param string $name Name of the key to use in finding a preference value
1777 * @param mixed $default Value to be returned if the $name key is not set in the user preferences
1778 * @param stdClass|int $user A moodle user object or id, null means current user
1779 * @return mixed string value or default
1781 function get_user_preferences($name = null, $default = null, $user = null) {
1784 if (is_null($name)) {
1786 } else if (is_numeric($name) or $name === '_lastloaded') {
1787 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1790 if (is_null($user)) {
1792 } else if (isset($user->id)) {
1793 // $user is valid object
1794 } else if (is_numeric($user)) {
1795 $user = (object)array('id'=>(int)$user);
1797 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1800 check_user_preferences_loaded($user);
1803 return $user->preference; // All values
1804 } else if (isset($user->preference[$name])) {
1805 return $user->preference[$name]; // The single string value
1807 return $default; // Default value (null if not specified)
1811 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1814 * Given date parts in user time produce a GMT timestamp.
1816 * @todo Finish documenting this function
1817 * @param int $year The year part to create timestamp of
1818 * @param int $month The month part to create timestamp of
1819 * @param int $day The day part to create timestamp of
1820 * @param int $hour The hour part to create timestamp of
1821 * @param int $minute The minute part to create timestamp of
1822 * @param int $second The second part to create timestamp of
1823 * @param mixed $timezone Timezone modifier, if 99 then use default user's timezone
1824 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1825 * applied only if timezone is 99 or string.
1826 * @return int timestamp
1828 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1830 //save input timezone, required for dst offset check.
1831 $passedtimezone = $timezone;
1833 $timezone = get_user_timezone_offset($timezone);
1835 if (abs($timezone) > 13) { //server time
1836 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1838 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1839 $time = usertime($time, $timezone);
1841 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1842 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1843 $time -= dst_offset_on($time, $passedtimezone);
1852 * Format a date/time (seconds) as weeks, days, hours etc as needed
1854 * Given an amount of time in seconds, returns string
1855 * formatted nicely as weeks, days, hours etc as needed
1861 * @param int $totalsecs Time in seconds
1862 * @param object $str Should be a time object
1863 * @return string A nicely formatted date/time string
1865 function format_time($totalsecs, $str=NULL) {
1867 $totalsecs = abs($totalsecs);
1869 if (!$str) { // Create the str structure the slow way
1870 $str->day = get_string('day');
1871 $str->days = get_string('days');
1872 $str->hour = get_string('hour');
1873 $str->hours = get_string('hours');
1874 $str->min = get_string('min');
1875 $str->mins = get_string('mins');
1876 $str->sec = get_string('sec');
1877 $str->secs = get_string('secs');
1878 $str->year = get_string('year');
1879 $str->years = get_string('years');
1883 $years = floor($totalsecs/YEARSECS);
1884 $remainder = $totalsecs - ($years*YEARSECS);
1885 $days = floor($remainder/DAYSECS);
1886 $remainder = $totalsecs - ($days*DAYSECS);
1887 $hours = floor($remainder/HOURSECS);
1888 $remainder = $remainder - ($hours*HOURSECS);
1889 $mins = floor($remainder/MINSECS);
1890 $secs = $remainder - ($mins*MINSECS);
1892 $ss = ($secs == 1) ? $str->sec : $str->secs;
1893 $sm = ($mins == 1) ? $str->min : $str->mins;
1894 $sh = ($hours == 1) ? $str->hour : $str->hours;
1895 $sd = ($days == 1) ? $str->day : $str->days;
1896 $sy = ($years == 1) ? $str->year : $str->years;
1904 if ($years) $oyears = $years .' '. $sy;
1905 if ($days) $odays = $days .' '. $sd;
1906 if ($hours) $ohours = $hours .' '. $sh;
1907 if ($mins) $omins = $mins .' '. $sm;
1908 if ($secs) $osecs = $secs .' '. $ss;
1910 if ($years) return trim($oyears .' '. $odays);
1911 if ($days) return trim($odays .' '. $ohours);
1912 if ($hours) return trim($ohours .' '. $omins);
1913 if ($mins) return trim($omins .' '. $osecs);
1914 if ($secs) return $osecs;
1915 return get_string('now');
1919 * Returns a formatted string that represents a date in user time
1921 * Returns a formatted string that represents a date in user time
1922 * <b>WARNING: note that the format is for strftime(), not date().</b>
1923 * Because of a bug in most Windows time libraries, we can't use
1924 * the nicer %e, so we have to use %d which has leading zeroes.
1925 * A lot of the fuss in the function is just getting rid of these leading
1926 * zeroes as efficiently as possible.
1928 * If parameter fixday = true (default), then take off leading
1929 * zero from %d, else maintain it.
1931 * @param int $date the timestamp in UTC, as obtained from the database.
1932 * @param string $format strftime format. You should probably get this using
1933 * get_string('strftime...', 'langconfig');
1934 * @param mixed $timezone by default, uses the user's time zone. if numeric and
1935 * not 99 then daylight saving will not be added.
1936 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1937 * If false then the leading zero is maintained.
1938 * @return string the formatted date/time.
1940 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1944 if (empty($format)) {
1945 $format = get_string('strftimedaydatetime', 'langconfig');
1948 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1950 } else if ($fixday) {
1951 $formatnoday = str_replace('%d', 'DD', $format);
1952 $fixday = ($formatnoday != $format);
1955 //add daylight saving offset for string timezones only, as we can't get dst for
1956 //float values. if timezone is 99 (user default timezone), then try update dst.
1957 if ((99 == $timezone) || !is_numeric($timezone)) {
1958 $date += dst_offset_on($date, $timezone);
1961 $timezone = get_user_timezone_offset($timezone);
1963 if (abs($timezone) > 13) { /// Server time
1965 $datestring = strftime($formatnoday, $date);
1966 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
1967 $datestring = str_replace('DD', $daystring, $datestring);
1969 $datestring = strftime($format, $date);
1972 $date += (int)($timezone * 3600);
1974 $datestring = gmstrftime($formatnoday, $date);
1975 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
1976 $datestring = str_replace('DD', $daystring, $datestring);
1978 $datestring = gmstrftime($format, $date);
1982 /// If we are running under Windows convert from windows encoding to UTF-8
1983 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1985 if ($CFG->ostype == 'WINDOWS') {
1986 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
1987 $textlib = textlib_get_instance();
1988 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1996 * Given a $time timestamp in GMT (seconds since epoch),
1997 * returns an array that represents the date in user time
1999 * @todo Finish documenting this function
2001 * @param int $time Timestamp in GMT
2002 * @param mixed $timezone offset time with timezone, if float and not 99, then no
2003 * dst offset is applyed
2004 * @return array An array that represents the date in user time
2006 function usergetdate($time, $timezone=99) {
2008 //save input timezone, required for dst offset check.
2009 $passedtimezone = $timezone;
2011 $timezone = get_user_timezone_offset($timezone);
2013 if (abs($timezone) > 13) { // Server time
2014 return getdate($time);
2017 //add daylight saving offset for string timezones only, as we can't get dst for
2018 //float values. if timezone is 99 (user default timezone), then try update dst.
2019 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2020 $time += dst_offset_on($time, $passedtimezone);
2023 $time += intval((float)$timezone * HOURSECS);
2025 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2027 //be careful to ensure the returned array matches that produced by getdate() above
2030 $getdate['weekday'],
2037 $getdate['minutes'],
2039 ) = explode('_', $datestring);
2045 * Given a GMT timestamp (seconds since epoch), offsets it by
2046 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2049 * @param int $date Timestamp in GMT
2050 * @param float $timezone
2053 function usertime($date, $timezone=99) {
2055 $timezone = get_user_timezone_offset($timezone);
2057 if (abs($timezone) > 13) {
2060 return $date - (int)($timezone * HOURSECS);
2064 * Given a time, return the GMT timestamp of the most recent midnight
2065 * for the current user.
2067 * @param int $date Timestamp in GMT
2068 * @param float $timezone Defaults to user's timezone
2069 * @return int Returns a GMT timestamp
2071 function usergetmidnight($date, $timezone=99) {
2073 $userdate = usergetdate($date, $timezone);
2075 // Time of midnight of this user's day, in GMT
2076 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2081 * Returns a string that prints the user's timezone
2083 * @param float $timezone The user's timezone
2086 function usertimezone($timezone=99) {
2088 $tz = get_user_timezone($timezone);
2090 if (!is_float($tz)) {
2094 if(abs($tz) > 13) { // Server time
2095 return get_string('serverlocaltime');
2098 if($tz == intval($tz)) {
2099 // Don't show .0 for whole hours
2116 * Returns a float which represents the user's timezone difference from GMT in hours
2117 * Checks various settings and picks the most dominant of those which have a value
2121 * @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
2124 function get_user_timezone_offset($tz = 99) {
2128 $tz = get_user_timezone($tz);
2130 if (is_float($tz)) {
2133 $tzrecord = get_timezone_record($tz);
2134 if (empty($tzrecord)) {
2137 return (float)$tzrecord->gmtoff / HOURMINS;
2142 * Returns an int which represents the systems's timezone difference from GMT in seconds
2145 * @param mixed $tz timezone
2146 * @return int if found, false is timezone 99 or error
2148 function get_timezone_offset($tz) {
2155 if (is_numeric($tz)) {
2156 return intval($tz * 60*60);
2159 if (!$tzrecord = get_timezone_record($tz)) {
2162 return intval($tzrecord->gmtoff * 60);
2166 * Returns a float or a string which denotes the user's timezone
2167 * 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)
2168 * means that for this timezone there are also DST rules to be taken into account
2169 * Checks various settings and picks the most dominant of those which have a value
2173 * @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
2176 function get_user_timezone($tz = 99) {
2181 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2182 isset($USER->timezone) ? $USER->timezone : 99,
2183 isset($CFG->timezone) ? $CFG->timezone : 99,
2188 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
2189 $tz = $next['value'];
2192 return is_numeric($tz) ? (float) $tz : $tz;
2196 * Returns cached timezone record for given $timezonename
2200 * @param string $timezonename
2201 * @return mixed timezonerecord object or false
2203 function get_timezone_record($timezonename) {
2205 static $cache = NULL;
2207 if ($cache === NULL) {
2211 if (isset($cache[$timezonename])) {
2212 return $cache[$timezonename];
2215 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2216 WHERE name = ? ORDER BY year DESC', array($timezonename), true);
2220 * Build and store the users Daylight Saving Time (DST) table
2225 * @param mixed $from_year Start year for the table, defaults to 1971
2226 * @param mixed $to_year End year for the table, defaults to 2035
2227 * @param mixed $strtimezone, if null or 99 then user's default timezone is used
2230 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2231 global $CFG, $SESSION, $DB;
2233 $usertz = get_user_timezone($strtimezone);
2235 if (is_float($usertz)) {
2236 // Trivial timezone, no DST
2240 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2241 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2242 unset($SESSION->dst_offsets);
2243 unset($SESSION->dst_range);
2246 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2247 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2248 // This will be the return path most of the time, pretty light computationally
2252 // Reaching here means we either need to extend our table or create it from scratch
2254 // Remember which TZ we calculated these changes for
2255 $SESSION->dst_offsettz = $usertz;
2257 if(empty($SESSION->dst_offsets)) {
2258 // If we 're creating from scratch, put the two guard elements in there
2259 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2261 if(empty($SESSION->dst_range)) {
2262 // If creating from scratch
2263 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2264 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2266 // Fill in the array with the extra years we need to process
2267 $yearstoprocess = array();
2268 for($i = $from; $i <= $to; ++$i) {
2269 $yearstoprocess[] = $i;
2272 // Take note of which years we have processed for future calls
2273 $SESSION->dst_range = array($from, $to);
2276 // If needing to extend the table, do the same
2277 $yearstoprocess = array();
2279 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2280 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2282 if($from < $SESSION->dst_range[0]) {
2283 // Take note of which years we need to process and then note that we have processed them for future calls
2284 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2285 $yearstoprocess[] = $i;
2287 $SESSION->dst_range[0] = $from;
2289 if($to > $SESSION->dst_range[1]) {
2290 // Take note of which years we need to process and then note that we have processed them for future calls
2291 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2292 $yearstoprocess[] = $i;
2294 $SESSION->dst_range[1] = $to;
2298 if(empty($yearstoprocess)) {
2299 // This means that there was a call requesting a SMALLER range than we have already calculated
2303 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2304 // Also, the array is sorted in descending timestamp order!
2308 static $presets_cache = array();
2309 if (!isset($presets_cache[$usertz])) {
2310 $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');
2312 if(empty($presets_cache[$usertz])) {
2316 // Remove ending guard (first element of the array)
2317 reset($SESSION->dst_offsets);
2318 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2320 // Add all required change timestamps
2321 foreach($yearstoprocess as $y) {
2322 // Find the record which is in effect for the year $y
2323 foreach($presets_cache[$usertz] as $year => $preset) {
2329 $changes = dst_changes_for_year($y, $preset);
2331 if($changes === NULL) {
2334 if($changes['dst'] != 0) {
2335 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2337 if($changes['std'] != 0) {
2338 $SESSION->dst_offsets[$changes['std']] = 0;
2342 // Put in a guard element at the top
2343 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2344 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2347 krsort($SESSION->dst_offsets);
2353 * Calculates the required DST change and returns a Timestamp Array
2357 * @param mixed $year Int or String Year to focus on
2358 * @param object $timezone Instatiated Timezone object
2359 * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
2361 function dst_changes_for_year($year, $timezone) {
2363 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2367 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2368 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2370 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2371 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2373 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2374 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2376 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2377 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2378 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2380 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2381 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2383 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2387 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2388 * - Note: Daylight saving only works for string timezones and not for float.
2391 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2392 * @param mixed $strtimezone timezone for which offset is expected, if 99 or null
2393 * then user's default timezone is used.
2396 function dst_offset_on($time, $strtimezone = NULL) {
2399 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2403 reset($SESSION->dst_offsets);
2404 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2405 if($from <= $time) {
2410 // This is the normal return path
2411 if($offset !== NULL) {
2415 // Reaching this point means we haven't calculated far enough, do it now:
2416 // Calculate extra DST changes if needed and recurse. The recursion always
2417 // moves toward the stopping condition, so will always end.
2420 // We need a year smaller than $SESSION->dst_range[0]
2421 if($SESSION->dst_range[0] == 1971) {
2424 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2425 return dst_offset_on($time, $strtimezone);
2428 // We need a year larger than $SESSION->dst_range[1]
2429 if($SESSION->dst_range[1] == 2035) {
2432 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2433 return dst_offset_on($time, $strtimezone);
2440 * @todo Document what this function does
2441 * @param int $startday
2442 * @param int $weekday
2447 function find_day_in_month($startday, $weekday, $month, $year) {
2449 $daysinmonth = days_in_month($month, $year);
2451 if($weekday == -1) {
2452 // Don't care about weekday, so return:
2453 // abs($startday) if $startday != -1
2454 // $daysinmonth otherwise
2455 return ($startday == -1) ? $daysinmonth : abs($startday);
2458 // From now on we 're looking for a specific weekday
2460 // Give "end of month" its actual value, since we know it
2461 if($startday == -1) {
2462 $startday = -1 * $daysinmonth;
2465 // Starting from day $startday, the sign is the direction
2469 $startday = abs($startday);
2470 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2472 // This is the last such weekday of the month
2473 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2474 if($lastinmonth > $daysinmonth) {
2478 // Find the first such weekday <= $startday
2479 while($lastinmonth > $startday) {
2483 return $lastinmonth;
2488 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2490 $diff = $weekday - $indexweekday;
2495 // This is the first such weekday of the month equal to or after $startday
2496 $firstfromindex = $startday + $diff;
2498 return $firstfromindex;
2504 * Calculate the number of days in a given month
2506 * @param int $month The month whose day count is sought
2507 * @param int $year The year of the month whose day count is sought
2510 function days_in_month($month, $year) {
2511 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2515 * Calculate the position in the week of a specific calendar day
2517 * @param int $day The day of the date whose position in the week is sought
2518 * @param int $month The month of the date whose position in the week is sought
2519 * @param int $year The year of the date whose position in the week is sought
2522 function dayofweek($day, $month, $year) {
2523 // I wonder if this is any different from
2524 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2525 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2528 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2531 * Returns full login url.
2533 * @return string login url
2535 function get_login_url() {
2538 $url = "$CFG->wwwroot/login/index.php";
2540 if (!empty($CFG->loginhttps)) {
2541 $url = str_replace('http:', 'https:', $url);
2548 * This function checks that the current user is logged in and has the
2549 * required privileges
2551 * This function checks that the current user is logged in, and optionally
2552 * whether they are allowed to be in a particular course and view a particular
2554 * If they are not logged in, then it redirects them to the site login unless
2555 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2556 * case they are automatically logged in as guests.
2557 * If $courseid is given and the user is not enrolled in that course then the
2558 * user is redirected to the course enrolment page.
2559 * If $cm is given and the course module is hidden and the user is not a teacher
2560 * in the course then the user is redirected to the course home page.
2562 * When $cm parameter specified, this function sets page layout to 'module'.
2563 * You need to change it manually later if some other layout needed.
2565 * @param mixed $courseorid id of the course or course object
2566 * @param bool $autologinguest default true
2567 * @param object $cm course module object
2568 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2569 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2570 * in order to keep redirects working properly. MDL-14495
2571 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2572 * @return mixed Void, exit, and die depending on path
2574 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2575 global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2577 // setup global $COURSE, themes, language and locale
2578 if (!empty($courseorid)) {
2579 if (is_object($courseorid)) {
2580 $course = $courseorid;
2581 } else if ($courseorid == SITEID) {
2582 $course = clone($SITE);
2584 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2587 if ($cm->course != $course->id) {
2588 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2590 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2591 if (!($cm instanceof cm_info)) {
2592 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2593 // db queries so this is not really a performance concern, however it is obviously
2594 // better if you use get_fast_modinfo to get the cm before calling this.
2595 $modinfo = get_fast_modinfo($course);
2596 $cm = $modinfo->get_cm($cm->id);
2598 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2599 $PAGE->set_pagelayout('incourse');
2601 $PAGE->set_course($course); // set's up global $COURSE
2604 // do not touch global $COURSE via $PAGE->set_course(),
2605 // the reasons is we need to be able to call require_login() at any time!!
2608 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2612 // If the user is not even logged in yet then make sure they are
2613 if (!isloggedin()) {
2614 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2615 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2616 // misconfigured site guest, just redirect to login page
2617 redirect(get_login_url());
2618 exit; // never reached
2620 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2621 complete_user_login($guest);
2622 $USER->autologinguest = true;
2623 $SESSION->lang = $lang;
2625 //NOTE: $USER->site check was obsoleted by session test cookie,
2626 // $USER->confirmed test is in login/index.php
2627 if ($preventredirect) {
2628 throw new require_login_exception('You are not logged in');
2631 if ($setwantsurltome) {
2632 // TODO: switch to PAGE->url
2633 $SESSION->wantsurl = $FULLME;
2635 if (!empty($_SERVER['HTTP_REFERER'])) {
2636 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2638 redirect(get_login_url());
2639 exit; // never reached
2643 // loginas as redirection if needed
2644 if ($course->id != SITEID and session_is_loggedinas()) {
2645 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2646 if ($USER->loginascontext->instanceid != $course->id) {
2647 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2652 // check whether the user should be changing password (but only if it is REALLY them)
2653 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2654 $userauth = get_auth_plugin($USER->auth);
2655 if ($userauth->can_change_password() and !$preventredirect) {
2656 $SESSION->wantsurl = $FULLME;
2657 if ($changeurl = $userauth->change_password_url()) {
2658 //use plugin custom url
2659 redirect($changeurl);
2661 //use moodle internal method
2662 if (empty($CFG->loginhttps)) {
2663 redirect($CFG->wwwroot .'/login/change_password.php');
2665 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2666 redirect($wwwroot .'/login/change_password.php');
2670 print_error('nopasswordchangeforced', 'auth');
2674 // Check that the user account is properly set up
2675 if (user_not_fully_set_up($USER)) {
2676 if ($preventredirect) {
2677 throw new require_login_exception('User not fully set-up');
2679 $SESSION->wantsurl = $FULLME;
2680 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2683 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2686 // Do not bother admins with any formalities
2687 if (is_siteadmin()) {
2688 //set accesstime or the user will appear offline which messes up messaging
2689 user_accesstime_log($course->id);
2693 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2694 if (!$USER->policyagreed and !is_siteadmin()) {
2695 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2696 if ($preventredirect) {
2697 throw new require_login_exception('Policy not agreed');
2699 $SESSION->wantsurl = $FULLME;
2700 redirect($CFG->wwwroot .'/user/policy.php');
2701 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2702 if ($preventredirect) {
2703 throw new require_login_exception('Policy not agreed');
2705 $SESSION->wantsurl = $FULLME;
2706 redirect($CFG->wwwroot .'/user/policy.php');
2710 // Fetch the system context, the course context, and prefetch its child contexts
2711 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2712 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2714 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2719 // If the site is currently under maintenance, then print a message
2720 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2721 if ($preventredirect) {
2722 throw new require_login_exception('Maintenance in progress');
2725 print_maintenance_message();
2728 // make sure the course itself is not hidden
2729 if ($course->id == SITEID) {
2730 // frontpage can not be hidden
2732 if (is_role_switched($course->id)) {
2733 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2735 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2736 // originally there was also test of parent category visibility,
2737 // BUT is was very slow in complex queries involving "my courses"
2738 // now it is also possible to simply hide all courses user is not enrolled in :-)
2739 if ($preventredirect) {
2740 throw new require_login_exception('Course is hidden');
2742 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2747 // is the user enrolled?
2748 if ($course->id == SITEID) {
2749 // everybody is enrolled on the frontpage
2752 if (session_is_loggedinas()) {
2753 // Make sure the REAL person can access this course first
2754 $realuser = session_get_realuser();
2755 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2756 if ($preventredirect) {
2757 throw new require_login_exception('Invalid course login-as access');
2759 echo $OUTPUT->header();
2760 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2766 if (is_role_switched($course->id)) {
2767 // ok, user had to be inside this course before the switch
2770 } else 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] > time()) {
2778 if (isset($USER->enrol['tempguest'][$course->id])) {
2779 unset($USER->enrol['tempguest'][$course->id]);
2780 remove_temp_course_roles($coursecontext);
2784 unset($USER->enrol['enrolled'][$course->id]);
2787 if (isset($USER->enrol['tempguest'][$course->id])) {
2788 if ($USER->enrol['tempguest'][$course->id] == 0) {
2790 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2794 unset($USER->enrol['tempguest'][$course->id]);
2795 remove_temp_course_roles($coursecontext);
2802 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2803 if ($until !== false) {
2804 // active participants may always access, a timestamp in the future, 0 (always) or false.
2806 $until = ENROL_MAX_TIMESTAMP;
2808 $USER->enrol['enrolled'][$course->id] = $until;
2812 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2813 $enrols = enrol_get_plugins(true);
2814 // first ask all enabled enrol instances in course if they want to auto enrol user
2815 foreach($instances as $instance) {
2816 if (!isset($enrols[$instance->enrol])) {
2819 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2820 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2821 if ($until !== false) {
2823 $until = ENROL_MAX_TIMESTAMP;
2825 $USER->enrol['enrolled'][$course->id] = $until;
2830 // if not enrolled yet try to gain temporary guest access
2832 foreach($instances as $instance) {
2833 if (!isset($enrols[$instance->enrol])) {
2836 // Get a duration for the guest access, a timestamp in the future or false.
2837 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2838 if ($until !== false and $until > time()) {
2839 $USER->enrol['tempguest'][$course->id] = $until;
2850 if ($preventredirect) {
2851 throw new require_login_exception('Not enrolled');
2853 $SESSION->wantsurl = $FULLME;
2854 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2858 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
2859 // conditional availability, etc
2860 if ($cm && !$cm->uservisible) {
2861 if ($preventredirect) {
2862 throw new require_login_exception('Activity is hidden');
2864 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2867 // Finally access granted, update lastaccess times
2868 user_accesstime_log($course->id);
2873 * This function just makes sure a user is logged out.
2877 function require_logout() {
2883 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2885 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2886 foreach($authsequence as $authname) {
2887 $authplugin = get_auth_plugin($authname);
2888 $authplugin->prelogout_hook();
2892 events_trigger('user_logout', $params);
2893 session_get_instance()->terminate_current();
2898 * Weaker version of require_login()
2900 * This is a weaker version of {@link require_login()} which only requires login
2901 * when called from within a course rather than the site page, unless
2902 * the forcelogin option is turned on.
2903 * @see require_login()
2906 * @param mixed $courseorid The course object or id in question
2907 * @param bool $autologinguest Allow autologin guests if that is wanted
2908 * @param object $cm Course activity module if known
2909 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2910 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2911 * in order to keep redirects working properly. MDL-14495
2912 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2915 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2916 global $CFG, $PAGE, $SITE;
2917 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
2918 or (!is_object($courseorid) and $courseorid == SITEID);
2919 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2920 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2921 // db queries so this is not really a performance concern, however it is obviously
2922 // better if you use get_fast_modinfo to get the cm before calling this.
2923 if (is_object($courseorid)) {
2924 $course = $courseorid;
2926 $course = clone($SITE);
2928 $modinfo = get_fast_modinfo($course);
2929 $cm = $modinfo->get_cm($cm->id);
2931 if (!empty($CFG->forcelogin)) {
2932 // login required for both SITE and courses
2933 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2935 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2936 // always login for hidden activities
2937 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2939 } else if ($issite) {
2940 //login for SITE not required
2941 if ($cm and empty($cm->visible)) {
2942 // hidden activities are not accessible without login
2943 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2944 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
2945 // not-logged-in users do not have any group membership
2946 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2948 // We still need to instatiate PAGE vars properly so that things
2949 // that rely on it like navigation function correctly.
2950 if (!empty($courseorid)) {
2951 if (is_object($courseorid)) {
2952 $course = $courseorid;
2954 $course = clone($SITE);
2957 if ($cm->course != $course->id) {
2958 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2960 $PAGE->set_cm($cm, $course);
2961 $PAGE->set_pagelayout('incourse');
2963 $PAGE->set_course($course);
2966 // If $PAGE->course, and hence $PAGE->context, have not already been set
2967 // up properly, set them up now.
2968 $PAGE->set_course($PAGE->course);
2970 //TODO: verify conditional activities here
2971 user_accesstime_log(SITEID);
2976 // course login always required
2977 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2982 * Require key login. Function terminates with error if key not found or incorrect.
2988 * @uses NO_MOODLE_COOKIES
2989 * @uses PARAM_ALPHANUM
2990 * @param string $script unique script identifier
2991 * @param int $instance optional instance id
2992 * @return int Instance ID
2994 function require_user_key_login($script, $instance=null) {
2995 global $USER, $SESSION, $CFG, $DB;
2997 if (!NO_MOODLE_COOKIES) {
2998 print_error('sessioncookiesdisable');
3002 @session_write_close();
3004 $keyvalue = required_param('key', PARAM_ALPHANUM);
3006 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3007 print_error('invalidkey');
3010 if (!empty($key->validuntil) and $key->validuntil < time()) {
3011 print_error('expiredkey');
3014 if ($key->iprestriction) {
3015 $remoteaddr = getremoteaddr(null);
3016 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3017 print_error('ipmismatch');
3021 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
3022 print_error('invaliduserid');
3025 /// emulate normal session
3026 enrol_check_plugins($user);
3027 session_set_user($user);
3029 /// note we are not using normal login
3030 if (!defined('USER_KEY_LOGIN')) {
3031 define('USER_KEY_LOGIN', true);
3034 /// return instance id - it might be empty
3035 return $key->instance;
3039 * Creates a new private user access key.
3042 * @param string $script unique target identifier
3043 * @param int $userid
3044 * @param int $instance optional instance id
3045 * @param string $iprestriction optional ip restricted access
3046 * @param timestamp $validuntil key valid only until given data
3047 * @return string access key value
3049 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3052 $key = new stdClass();
3053 $key->script = $script;
3054 $key->userid = $userid;
3055 $key->instance = $instance;
3056 $key->iprestriction = $iprestriction;
3057 $key->validuntil = $validuntil;
3058 $key->timecreated = time();
3060 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
3061 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3063 $key->value = md5($userid.'_'.time().random_string(40));
3065 $DB->insert_record('user_private_key', $key);
3070 * Delete the user's new private user access keys for a particular script.
3073 * @param string $script unique target identifier
3074 * @param int $userid
3077 function delete_user_key($script,$userid) {
3079 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3083 * Gets a private user access key (and creates one if one doesn't exist).
3086 * @param string $script unique target identifier
3087 * @param int $userid
3088 * @param int $instance optional instance id
3089 * @param string $iprestriction optional ip restricted access
3090 * @param timestamp $validuntil key valid only until given data
3091 * @return string access key value
3093 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3096 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3097 'instance'=>$instance, 'iprestriction'=>$iprestriction,
3098 'validuntil'=>$validuntil))) {
3101 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3107 * Modify the user table by setting the currently logged in user's
3108 * last login to now.
3112 * @return bool Always returns true
3114 function update_user_login_times() {
3117 $user = new stdClass();
3118 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3119 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
3121 $user->id = $USER->id;
3123 $DB->update_record('user', $user);
3128 * Determines if a user has completed setting up their account.
3130 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3133 function user_not_fully_set_up($user) {
3134 if (isguestuser($user)) {
3137 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3141 * Check whether the user has exceeded the bounce threshold
3145 * @param user $user A {@link $USER} object
3146 * @return bool true=>User has exceeded bounce threshold
3148 function over_bounce_threshold($user) {
3151 if (empty($CFG->handlebounces)) {
3155 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3159 // set sensible defaults
3160 if (empty($CFG->minbounces)) {
3161 $CFG->minbounces = 10;
3163 if (empty($CFG->bounceratio)) {
3164 $CFG->bounceratio = .20;
3168 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3169 $bouncecount = $bounce->value;
3171 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3172 $sendcount = $send->value;
3174 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3178 * Used to increment or reset email sent count
3181 * @param user $user object containing an id
3182 * @param bool $reset will reset the count to 0
3185 function set_send_count($user,$reset=false) {
3188 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3192 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3193 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3194 $DB->update_record('user_preferences', $pref);
3196 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3198 $pref = new stdClass();
3199 $pref->name = 'email_send_count';
3201 $pref->userid = $user->id;
3202 $DB->insert_record('user_preferences', $pref, false);
3207 * Increment or reset user's email bounce count
3210 * @param user $user object containing an id
3211 * @param bool $reset will reset the count to 0
3213 function set_bounce_count($user,$reset=false) {
3216 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3217 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3218 $DB->update_record('user_preferences', $pref);
3220 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3222 $pref = new stdClass();
3223 $pref->name = 'email_bounce_count';
3225 $pref->userid = $user->id;
3226 $DB->insert_record('user_preferences', $pref, false);
3231 * Keeps track of login attempts
3235 function update_login_count() {
3240 if (empty($SESSION->logincount)) {
3241 $SESSION->logincount = 1;
3243 $SESSION->logincount++;
3246 if ($SESSION->logincount > $max_logins) {
3247 unset($SESSION->wantsurl);
3248 print_error('errortoomanylogins');
3253 * Resets login attempts
3257 function reset_login_count() {
3260 $SESSION->logincount = 0;
3264 * Determines if the currently logged in user is in editing mode.
3265 * Note: originally this function had $userid parameter - it was not usable anyway
3267 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3268 * @todo Deprecated function remove when ready
3271 * @uses DEBUG_DEVELOPER
3274 function isediting() {
3276 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3277 return $PAGE->user_is_editing();
3281 * Determines if the logged in user is currently moving an activity
3284 * @param int $courseid The id of the course being tested
3287 function ismoving($courseid) {
3290 if (!empty($USER->activitycopy)) {
3291 return ($USER->activitycopycourse == $courseid);
3297 * Returns a persons full name
3299 * Given an object containing firstname and lastname
3300 * values, this function returns a string with the
3301 * full name of the person.
3302 * The result may depend on system settings
3303 * or language. 'override' will force both names
3304 * to be used even if system settings specify one.
3308 * @param object $user A {@link $USER} object to get full name of
3309 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3312 function fullname($user, $override=false) {
3313 global $CFG, $SESSION;
3315 if (!isset($user->firstname) and !isset($user->lastname)) {
3320 if (!empty($CFG->forcefirstname)) {
3321 $user->firstname = $CFG->forcefirstname;
3323 if (!empty($CFG->forcelastname)) {
3324 $user->lastname = $CFG->forcelastname;
3328 if (!empty($SESSION->fullnamedisplay)) {
3329 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3332 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3333 return $user->firstname .' '. $user->lastname;
3335 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3336 return $user->lastname .' '. $user->firstname;
3338 } else if ($CFG->fullnamedisplay == 'firstname') {
3340 return get_string('fullnamedisplay', '', $user);
3342 return $user->firstname;
3346 return get_string('fullnamedisplay', '', $user);
3350 * Checks if current user is shown any extra fields when listing users.
3351 * @param object $context Context
3352 * @param array $already Array of fields that we're going to show anyway
3353 * so don't bother listing them
3354 * @return array Array of field names from user table, not including anything
3355 * listed in $already
3357 function get_extra_user_fields($context, $already = array()) {
3360 // Only users with permission get the extra fields
3361 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3365 // Split showuseridentity on comma
3366 if ($CFG->showuseridentity === '') {
3367 // Explode gives wrong result with empty string
3370 $extra = explode(',', $CFG->showuseridentity);
3373 foreach ($extra as $key => $field) {
3374 if (in_array($field, $already)) {
3375 unset($extra[$key]);
3380 // For consistency, if entries are removed from array, renumber it
3381 // so they are numbered as you would expect
3382 $extra = array_merge($extra);
3388 * If the current user is to be shown extra user fields when listing or
3389 * selecting users, returns a string suitable for including in an SQL select
3390 * clause to retrieve those fields.
3391 * @param object $context Context
3392 * @param string $alias Alias of user table, e.g. 'u' (default none)
3393 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3394 * @param array $already Array of fields that we're going to include anyway
3395 * so don't list them (default none)
3396 * @return string Partial SQL select clause, beginning with comma, for example
3397 * ',u.idnumber,u.department' unless it is blank
3399 function get_extra_user_fields_sql($context, $alias='', $prefix='',
3400 $already = array()) {
3401 $fields = get_extra_user_fields($context, $already);
3403 // Add punctuation for alias
3404 if ($alias !== '') {
3407 foreach ($fields as $field) {
3408 $result .= ', ' . $alias . $field;
3410 $result .= ' AS ' . $prefix . $field;
3417 * Returns the display name of a field in the user table. Works for most fields
3418 * that are commonly displayed to users.
3419 * @param string $field Field name, e.g. 'phone1'
3420 * @return string Text description taken from language file, e.g. 'Phone number'
3422 function get_user_field_name($field) {
3423 // Some fields have language strings which are not the same as field name
3425 case 'phone1' : return get_string('phone');
3427 // Otherwise just use the same lang string
3428 return get_string($field);
3432 * Returns whether a given authentication plugin exists.
3435 * @param string $auth Form of authentication to check for. Defaults to the
3436 * global setting in {@link $CFG}.
3437 * @return boolean Whether the plugin is available.
3439 function exists_auth_plugin($auth) {
3442 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3443 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3449 * Checks if a given plugin is in the list of enabled authentication plugins.
3451 * @param string $auth Authentication plugin.
3452 * @return boolean Whether the plugin is enabled.
3454 function is_enabled_auth($auth) {
3459 $enabled = get_enabled_auth_plugins();
3461 return in_array($auth, $enabled);
3465 * Returns an authentication plugin instance.
3468 * @param string $auth name of authentication plugin
3469 * @return auth_plugin_base An instance of the required authentication plugin.
3471 function get_auth_plugin($auth) {
3474 // check the plugin exists first
3475 if (! exists_auth_plugin($auth)) {
3476 print_error('authpluginnotfound', 'debug', '', $auth);
3479 // return auth plugin instance
3480 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3481 $class = "auth_plugin_$auth";
3486 * Returns array of active auth plugins.
3488 * @param bool $fix fix $CFG->auth if needed
3491 function get_enabled_auth_plugins($fix=false) {
3494 $default = array('manual', 'nologin');
3496 if (empty($CFG->auth)) {
3499 $auths = explode(',', $CFG->auth);
3503 $auths = array_unique($auths);
3504 foreach($auths as $k=>$authname) {
3505 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3509 $newconfig = implode(',', $auths);
3510 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3511 set_config('auth', $newconfig);
3515 return (array_merge($default, $auths));
3519 * Returns true if an internal authentication method is being used.
3520 * if method not specified then, global default is assumed
3522 * @param string $auth Form of authentication required
3525 function is_internal_auth($auth) {
3526 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3527 return $authplugin->is_internal();
3531 * Returns true if the user is a 'restored' one
3533 * Used in the login process to inform the user
3534 * and allow him/her to reset the password
3538 * @param string $username username to be checked
3541 function is_restored_user($username) {
3544 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3548 * Returns an array of user fields
3550 * @return array User field/column names
3552 function get_user_fieldnames() {
3555 $fieldarray = $DB->get_columns('user');
3556 unset($fieldarray['id']);
3557 $fieldarray = array_keys($fieldarray);
3563 * Creates a bare-bones user record
3565 * @todo Outline auth types and provide code example
3567 * @param string $username New user's username to add to record
3568 * @param string $password New user's password to add to record
3569 * @param string $auth Form of authentication required
3570 * @return stdClass A complete user object
3572 function create_user_record($username, $password, $auth = 'manual') {
3575 //just in case check text case
3576 $username = trim(moodle_strtolower($username));
3578 $authplugin = get_auth_plugin($auth);
3580 $newuser = new stdClass();
3582 if ($newinfo = $authplugin->get_userinfo($username)) {
3583 $newinfo = truncate_userinfo($newinfo);
3584 foreach ($newinfo as $key => $value){
3585 $newuser->$key = $value;
3589 if (!empty($newuser->email)) {
3590 if (email_is_not_allowed($newuser->email)) {
3591 unset($newuser->email);
3595 if (!isset($newuser->city)) {
3596 $newuser->city = '';
3599 $newuser->auth = $auth;
3600 $newuser->username = $username;
3603 // user CFG lang for user if $newuser->lang is empty
3604 // or $user->lang is not an installed language
3605 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3606 $newuser->lang = $CFG->lang;
3608 $newuser->confirmed = 1;
3609 $newuser->lastip = getremoteaddr();
3610 $newuser->timemodified = time();
3611 $newuser->mnethostid = $CFG->mnet_localhost_id;
3613 $newuser->id = $DB->insert_record('user', $newuser);
3614 $user = get_complete_user_data('id', $newuser->id);
3615 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3616 set_user_preference('auth_forcepasswordchange', 1, $user);
3618 update_internal_user_password($user, $password);
3620 // fetch full user record for the event, the complete user data contains too much info
3621 // and we want to be consistent with other places that trigger this event
3622 events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
3628 * Will update a local user record from an external source.
3629 * (MNET users can not be updated using this method!)
3631 * @param string $username user's username to update the record
3632 * @return stdClass A complete user object
3634 function update_user_record($username) {
3637 $username = trim(moodle_strtolower($username)); /// just in case check text case
3639 $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
3641 $userauth = get_auth_plugin($oldinfo->auth);
3643 if ($newinfo = $userauth->get_userinfo($username)) {
3644 $newinfo = truncate_userinfo($newinfo);
3645 foreach ($newinfo as $key => $value){
3646 $key = strtolower($key);
3647 if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id'
3648 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3649 // unknown or must not be changed
3652 $confval = $userauth->config->{'field_updatelocal_' . $key};
3653 $lockval = $userauth->config->{'field_lock_' . $key};
3654 if (empty($confval) || empty($lockval)) {
3657 if ($confval === 'onlogin') {
3658 // MDL-4207 Don't overwrite modified user profile values with
3659 // empty LDAP values when 'unlocked if empty' is set. The purpose
3660 // of the setting 'unlocked if empty' is to allow the user to fill
3661 // in a value for the selected field _if LDAP is giving
3662 // nothing_ for this field. Thus it makes sense to let this value
3663 // stand in until LDAP is giving a value for this field.
3664 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3665 if ((string)$oldinfo->$key !== (string)$value) {
3666 $newuser[$key] = (string)$value;
3672 $newuser['id'] = $oldinfo->id;
3673 $DB->update_record('user', $newuser);
3674 // fetch full user record for the event, the complete user data contains too much info
3675 // and we want to be consistent with other places that trigger this event
3676 events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id)));
3680 return get_complete_user_data('id', $oldinfo->id);
3684 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3685 * which may have large fields
3687 * @todo Add vartype handling to ensure $info is an array
3689 * @param array $info Array of user properties to truncate if needed
3690 * @return array The now truncated information that was passed in