Merge branch 'wip-mdl-52020-m29' of https://github.com/rajeshtaneja/moodle into MOODL...
[moodle.git] / lib / moodlelib.php
blobf639e94bf0393cf8461771a794757bbad0a6cfd7
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
25 * @package core
26 * @subpackage lib
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
36 /**
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
41 /**
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
46 /**
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
51 /**
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
56 /**
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
61 /**
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
66 /**
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
74 /**
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
79 /**
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
83 define('PARAM_ALPHAEXT', 'alphaext');
85 /**
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
90 /**
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
95 /**
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
98 define('PARAM_AUTH', 'auth');
101 * PARAM_BASE64 - Base 64 encoded format
103 define('PARAM_BASE64', 'base64');
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
108 define('PARAM_BOOL', 'bool');
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
114 define('PARAM_CAPABILITY', 'capability');
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119 * the input (required/optional_param or formslib) and then sanitse the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
123 define('PARAM_CLEANHTML', 'cleanhtml');
126 * PARAM_EMAIL - an email address following the RFC
128 define('PARAM_EMAIL', 'email');
131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
133 define('PARAM_FILE', 'file');
136 * PARAM_FLOAT - a real/floating point number.
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
146 define('PARAM_FLOAT', 'float');
149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
151 define('PARAM_HOST', 'host');
154 * PARAM_INT - integers only, use when expecting only numbers.
156 define('PARAM_INT', 'int');
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
161 define('PARAM_LANG', 'lang');
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
167 define('PARAM_LOCALURL', 'localurl');
170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
172 define('PARAM_NOTAGS', 'notags');
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
178 define('PARAM_PATH', 'path');
181 * PARAM_PEM - Privacy Enhanced Mail format
183 define('PARAM_PEM', 'pem');
186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
188 define('PARAM_PERMISSION', 'permission');
191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
193 define('PARAM_RAW', 'raw');
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
203 define('PARAM_SAFEDIR', 'safedir');
206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
208 define('PARAM_SAFEPATH', 'safepath');
211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
213 define('PARAM_SEQUENCE', 'sequence');
216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
218 define('PARAM_TAG', 'tag');
221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
223 define('PARAM_TAGLIST', 'taglist');
226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
228 define('PARAM_TEXT', 'text');
231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
233 define('PARAM_THEME', 'theme');
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
245 define('PARAM_USERNAME', 'username');
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
250 define('PARAM_STRINGID', 'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
256 * @deprecated since 2.0
258 define('PARAM_CLEAN', 'clean');
261 * PARAM_INTEGER - deprecated alias for PARAM_INT
262 * @deprecated since 2.0
264 define('PARAM_INTEGER', 'int');
267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268 * @deprecated since 2.0
270 define('PARAM_NUMBER', 'float');
273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274 * NOTE: originally alias for PARAM_APLHA
275 * @deprecated since 2.0
277 define('PARAM_ACTION', 'alphanumext');
280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
282 * @deprecated since 2.0
284 define('PARAM_FORMAT', 'alphanumext');
287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288 * @deprecated since 2.0
290 define('PARAM_MULTILANG', 'text');
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295 * America/Port-au-Prince)
297 define('PARAM_TIMEZONE', 'timezone');
300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
302 define('PARAM_CLEANFILE', 'file');
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
310 define('PARAM_COMPONENT', 'component');
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
317 define('PARAM_AREA', 'area');
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
324 define('PARAM_PLUGIN', 'plugin');
327 // Web Services.
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
332 define('VALUE_REQUIRED', 1);
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
337 define('VALUE_OPTIONAL', 2);
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
342 define('VALUE_DEFAULT', 0);
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
347 define('NULL_NOT_ALLOWED', false);
350 * NULL_ALLOWED - the parameter can be set to null in the database
352 define('NULL_ALLOWED', true);
354 // Page types.
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
374 // Tag constants.
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
442 /** Unspecified module archetype */
443 define('MOD_ARCHETYPE_OTHER', 0);
444 /** Resource-like type module */
445 define('MOD_ARCHETYPE_RESOURCE', 1);
446 /** Assignment module archetype */
447 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448 /** System (not user-addable) module archetype */
449 define('MOD_ARCHETYPE_SYSTEM', 3);
451 /** Return this from modname_get_types callback to use default display in activity chooser */
452 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
455 * Security token used for allowing access
456 * from external application such as web services.
457 * Scripts do not use any session, performance is relatively
458 * low because we need to load access info in each request.
459 * Scripts are executed in parallel.
461 define('EXTERNAL_TOKEN_PERMANENT', 0);
464 * Security token used for allowing access
465 * of embedded applications, the code is executed in the
466 * active user session. Token is invalidated after user logs out.
467 * Scripts are executed serially - normal session locking is used.
469 define('EXTERNAL_TOKEN_EMBEDDED', 1);
472 * The home page should be the site home
474 define('HOMEPAGE_SITE', 0);
476 * The home page should be the users my page
478 define('HOMEPAGE_MY', 1);
480 * The home page can be chosen by the user
482 define('HOMEPAGE_USER', 2);
485 * Hub directory url (should be moodle.org)
487 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
491 * Moodle.org url (should be moodle.org)
493 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
496 * Moodle mobile app service name
498 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
501 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
503 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
506 * Course display settings: display all sections on one page.
508 define('COURSE_DISPLAY_SINGLEPAGE', 0);
510 * Course display settings: split pages into a page per section.
512 define('COURSE_DISPLAY_MULTIPAGE', 1);
515 * Authentication constant: String used in password field when password is not stored.
517 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
519 // PARAMETER HANDLING.
522 * Returns a particular value for the named variable, taken from
523 * POST or GET. If the parameter doesn't exist then an error is
524 * thrown because we require this variable.
526 * This function should be used to initialise all required values
527 * in a script that are based on parameters. Usually it will be
528 * used like this:
529 * $id = required_param('id', PARAM_INT);
531 * Please note the $type parameter is now required and the value can not be array.
533 * @param string $parname the name of the page parameter we want
534 * @param string $type expected type of parameter
535 * @return mixed
536 * @throws coding_exception
538 function required_param($parname, $type) {
539 if (func_num_args() != 2 or empty($parname) or empty($type)) {
540 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
542 // POST has precedence.
543 if (isset($_POST[$parname])) {
544 $param = $_POST[$parname];
545 } else if (isset($_GET[$parname])) {
546 $param = $_GET[$parname];
547 } else {
548 print_error('missingparam', '', '', $parname);
551 if (is_array($param)) {
552 debugging('Invalid array parameter detected in required_param(): '.$parname);
553 // TODO: switch to fatal error in Moodle 2.3.
554 return required_param_array($parname, $type);
557 return clean_param($param, $type);
561 * Returns a particular array value for the named variable, taken from
562 * POST or GET. If the parameter doesn't exist then an error is
563 * thrown because we require this variable.
565 * This function should be used to initialise all required values
566 * in a script that are based on parameters. Usually it will be
567 * used like this:
568 * $ids = required_param_array('ids', PARAM_INT);
570 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
572 * @param string $parname the name of the page parameter we want
573 * @param string $type expected type of parameter
574 * @return array
575 * @throws coding_exception
577 function required_param_array($parname, $type) {
578 if (func_num_args() != 2 or empty($parname) or empty($type)) {
579 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
581 // POST has precedence.
582 if (isset($_POST[$parname])) {
583 $param = $_POST[$parname];
584 } else if (isset($_GET[$parname])) {
585 $param = $_GET[$parname];
586 } else {
587 print_error('missingparam', '', '', $parname);
589 if (!is_array($param)) {
590 print_error('missingparam', '', '', $parname);
593 $result = array();
594 foreach ($param as $key => $value) {
595 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
596 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
597 continue;
599 $result[$key] = clean_param($value, $type);
602 return $result;
606 * Returns a particular value for the named variable, taken from
607 * POST or GET, otherwise returning a given default.
609 * This function should be used to initialise all optional values
610 * in a script that are based on parameters. Usually it will be
611 * used like this:
612 * $name = optional_param('name', 'Fred', PARAM_TEXT);
614 * Please note the $type parameter is now required and the value can not be array.
616 * @param string $parname the name of the page parameter we want
617 * @param mixed $default the default value to return if nothing is found
618 * @param string $type expected type of parameter
619 * @return mixed
620 * @throws coding_exception
622 function optional_param($parname, $default, $type) {
623 if (func_num_args() != 3 or empty($parname) or empty($type)) {
624 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
626 if (!isset($default)) {
627 $default = null;
630 // POST has precedence.
631 if (isset($_POST[$parname])) {
632 $param = $_POST[$parname];
633 } else if (isset($_GET[$parname])) {
634 $param = $_GET[$parname];
635 } else {
636 return $default;
639 if (is_array($param)) {
640 debugging('Invalid array parameter detected in required_param(): '.$parname);
641 // TODO: switch to $default in Moodle 2.3.
642 return optional_param_array($parname, $default, $type);
645 return clean_param($param, $type);
649 * Returns a particular array value for the named variable, taken from
650 * POST or GET, otherwise returning a given default.
652 * This function should be used to initialise all optional values
653 * in a script that are based on parameters. Usually it will be
654 * used like this:
655 * $ids = optional_param('id', array(), PARAM_INT);
657 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
659 * @param string $parname the name of the page parameter we want
660 * @param mixed $default the default value to return if nothing is found
661 * @param string $type expected type of parameter
662 * @return array
663 * @throws coding_exception
665 function optional_param_array($parname, $default, $type) {
666 if (func_num_args() != 3 or empty($parname) or empty($type)) {
667 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
670 // POST has precedence.
671 if (isset($_POST[$parname])) {
672 $param = $_POST[$parname];
673 } else if (isset($_GET[$parname])) {
674 $param = $_GET[$parname];
675 } else {
676 return $default;
678 if (!is_array($param)) {
679 debugging('optional_param_array() expects array parameters only: '.$parname);
680 return $default;
683 $result = array();
684 foreach ($param as $key => $value) {
685 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
686 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
687 continue;
689 $result[$key] = clean_param($value, $type);
692 return $result;
696 * Strict validation of parameter values, the values are only converted
697 * to requested PHP type. Internally it is using clean_param, the values
698 * before and after cleaning must be equal - otherwise
699 * an invalid_parameter_exception is thrown.
700 * Objects and classes are not accepted.
702 * @param mixed $param
703 * @param string $type PARAM_ constant
704 * @param bool $allownull are nulls valid value?
705 * @param string $debuginfo optional debug information
706 * @return mixed the $param value converted to PHP type
707 * @throws invalid_parameter_exception if $param is not of given type
709 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
710 if (is_null($param)) {
711 if ($allownull == NULL_ALLOWED) {
712 return null;
713 } else {
714 throw new invalid_parameter_exception($debuginfo);
717 if (is_array($param) or is_object($param)) {
718 throw new invalid_parameter_exception($debuginfo);
721 $cleaned = clean_param($param, $type);
723 if ($type == PARAM_FLOAT) {
724 // Do not detect precision loss here.
725 if (is_float($param) or is_int($param)) {
726 // These always fit.
727 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
728 throw new invalid_parameter_exception($debuginfo);
730 } else if ((string)$param !== (string)$cleaned) {
731 // Conversion to string is usually lossless.
732 throw new invalid_parameter_exception($debuginfo);
735 return $cleaned;
739 * Makes sure array contains only the allowed types, this function does not validate array key names!
741 * <code>
742 * $options = clean_param($options, PARAM_INT);
743 * </code>
745 * @param array $param the variable array we are cleaning
746 * @param string $type expected format of param after cleaning.
747 * @param bool $recursive clean recursive arrays
748 * @return array
749 * @throws coding_exception
751 function clean_param_array(array $param = null, $type, $recursive = false) {
752 // Convert null to empty array.
753 $param = (array)$param;
754 foreach ($param as $key => $value) {
755 if (is_array($value)) {
756 if ($recursive) {
757 $param[$key] = clean_param_array($value, $type, true);
758 } else {
759 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
761 } else {
762 $param[$key] = clean_param($value, $type);
765 return $param;
769 * Used by {@link optional_param()} and {@link required_param()} to
770 * clean the variables and/or cast to specific types, based on
771 * an options field.
772 * <code>
773 * $course->format = clean_param($course->format, PARAM_ALPHA);
774 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
775 * </code>
777 * @param mixed $param the variable we are cleaning
778 * @param string $type expected format of param after cleaning.
779 * @return mixed
780 * @throws coding_exception
782 function clean_param($param, $type) {
783 global $CFG;
785 if (is_array($param)) {
786 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
787 } else if (is_object($param)) {
788 if (method_exists($param, '__toString')) {
789 $param = $param->__toString();
790 } else {
791 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
795 switch ($type) {
796 case PARAM_RAW:
797 // No cleaning at all.
798 $param = fix_utf8($param);
799 return $param;
801 case PARAM_RAW_TRIMMED:
802 // No cleaning, but strip leading and trailing whitespace.
803 $param = fix_utf8($param);
804 return trim($param);
806 case PARAM_CLEAN:
807 // General HTML cleaning, try to use more specific type if possible this is deprecated!
808 // Please use more specific type instead.
809 if (is_numeric($param)) {
810 return $param;
812 $param = fix_utf8($param);
813 // Sweep for scripts, etc.
814 return clean_text($param);
816 case PARAM_CLEANHTML:
817 // Clean html fragment.
818 $param = fix_utf8($param);
819 // Sweep for scripts, etc.
820 $param = clean_text($param, FORMAT_HTML);
821 return trim($param);
823 case PARAM_INT:
824 // Convert to integer.
825 return (int)$param;
827 case PARAM_FLOAT:
828 // Convert to float.
829 return (float)$param;
831 case PARAM_ALPHA:
832 // Remove everything not `a-z`.
833 return preg_replace('/[^a-zA-Z]/i', '', $param);
835 case PARAM_ALPHAEXT:
836 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
837 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
839 case PARAM_ALPHANUM:
840 // Remove everything not `a-zA-Z0-9`.
841 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
843 case PARAM_ALPHANUMEXT:
844 // Remove everything not `a-zA-Z0-9_-`.
845 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
847 case PARAM_SEQUENCE:
848 // Remove everything not `0-9,`.
849 return preg_replace('/[^0-9,]/i', '', $param);
851 case PARAM_BOOL:
852 // Convert to 1 or 0.
853 $tempstr = strtolower($param);
854 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
855 $param = 1;
856 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
857 $param = 0;
858 } else {
859 $param = empty($param) ? 0 : 1;
861 return $param;
863 case PARAM_NOTAGS:
864 // Strip all tags.
865 $param = fix_utf8($param);
866 return strip_tags($param);
868 case PARAM_TEXT:
869 // Leave only tags needed for multilang.
870 $param = fix_utf8($param);
871 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
872 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
873 do {
874 if (strpos($param, '</lang>') !== false) {
875 // Old and future mutilang syntax.
876 $param = strip_tags($param, '<lang>');
877 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
878 break;
880 $open = false;
881 foreach ($matches[0] as $match) {
882 if ($match === '</lang>') {
883 if ($open) {
884 $open = false;
885 continue;
886 } else {
887 break 2;
890 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
891 break 2;
892 } else {
893 $open = true;
896 if ($open) {
897 break;
899 return $param;
901 } else if (strpos($param, '</span>') !== false) {
902 // Current problematic multilang syntax.
903 $param = strip_tags($param, '<span>');
904 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
905 break;
907 $open = false;
908 foreach ($matches[0] as $match) {
909 if ($match === '</span>') {
910 if ($open) {
911 $open = false;
912 continue;
913 } else {
914 break 2;
917 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
918 break 2;
919 } else {
920 $open = true;
923 if ($open) {
924 break;
926 return $param;
928 } while (false);
929 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
930 return strip_tags($param);
932 case PARAM_COMPONENT:
933 // We do not want any guessing here, either the name is correct or not
934 // please note only normalised component names are accepted.
935 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
936 return '';
938 if (strpos($param, '__') !== false) {
939 return '';
941 if (strpos($param, 'mod_') === 0) {
942 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
943 if (substr_count($param, '_') != 1) {
944 return '';
947 return $param;
949 case PARAM_PLUGIN:
950 case PARAM_AREA:
951 // We do not want any guessing here, either the name is correct or not.
952 if (!is_valid_plugin_name($param)) {
953 return '';
955 return $param;
957 case PARAM_SAFEDIR:
958 // Remove everything not a-zA-Z0-9_- .
959 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
961 case PARAM_SAFEPATH:
962 // Remove everything not a-zA-Z0-9/_- .
963 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
965 case PARAM_FILE:
966 // Strip all suspicious characters from filename.
967 $param = fix_utf8($param);
968 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
969 if ($param === '.' || $param === '..') {
970 $param = '';
972 return $param;
974 case PARAM_PATH:
975 // Strip all suspicious characters from file path.
976 $param = fix_utf8($param);
977 $param = str_replace('\\', '/', $param);
979 // Explode the path and clean each element using the PARAM_FILE rules.
980 $breadcrumb = explode('/', $param);
981 foreach ($breadcrumb as $key => $crumb) {
982 if ($crumb === '.' && $key === 0) {
983 // Special condition to allow for relative current path such as ./currentdirfile.txt.
984 } else {
985 $crumb = clean_param($crumb, PARAM_FILE);
987 $breadcrumb[$key] = $crumb;
989 $param = implode('/', $breadcrumb);
991 // Remove multiple current path (./././) and multiple slashes (///).
992 $param = preg_replace('~//+~', '/', $param);
993 $param = preg_replace('~/(\./)+~', '/', $param);
994 return $param;
996 case PARAM_HOST:
997 // Allow FQDN or IPv4 dotted quad.
998 $param = preg_replace('/[^\.\d\w-]/', '', $param );
999 // Match ipv4 dotted quad.
1000 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1001 // Confirm values are ok.
1002 if ( $match[0] > 255
1003 || $match[1] > 255
1004 || $match[3] > 255
1005 || $match[4] > 255 ) {
1006 // Hmmm, what kind of dotted quad is this?
1007 $param = '';
1009 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1010 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1011 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1013 // All is ok - $param is respected.
1014 } else {
1015 // All is not ok...
1016 $param='';
1018 return $param;
1020 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1021 $param = fix_utf8($param);
1022 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1023 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1024 // All is ok, param is respected.
1025 } else {
1026 // Not really ok.
1027 $param ='';
1029 return $param;
1031 case PARAM_LOCALURL:
1032 // Allow http absolute, root relative and relative URLs within wwwroot.
1033 $param = clean_param($param, PARAM_URL);
1034 if (!empty($param)) {
1036 // Simulate the HTTPS version of the site.
1037 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1039 if ($param === $CFG->wwwroot) {
1040 // Exact match;
1041 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1042 // Exact match;
1043 } else if (preg_match(':^/:', $param)) {
1044 // Root-relative, ok!
1045 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1046 // Absolute, and matches our wwwroot.
1047 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1048 // Absolute, and matches our httpswwwroot.
1049 } else {
1050 // Relative - let's make sure there are no tricks.
1051 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1052 // Looks ok.
1053 } else {
1054 $param = '';
1058 return $param;
1060 case PARAM_PEM:
1061 $param = trim($param);
1062 // PEM formatted strings may contain letters/numbers and the symbols:
1063 // forward slash: /
1064 // plus sign: +
1065 // equal sign: =
1066 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1067 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1068 list($wholething, $body) = $matches;
1069 unset($wholething, $matches);
1070 $b64 = clean_param($body, PARAM_BASE64);
1071 if (!empty($b64)) {
1072 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1073 } else {
1074 return '';
1077 return '';
1079 case PARAM_BASE64:
1080 if (!empty($param)) {
1081 // PEM formatted strings may contain letters/numbers and the symbols
1082 // forward slash: /
1083 // plus sign: +
1084 // equal sign: =.
1085 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1086 return '';
1088 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1089 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1090 // than (or equal to) 64 characters long.
1091 for ($i=0, $j=count($lines); $i < $j; $i++) {
1092 if ($i + 1 == $j) {
1093 if (64 < strlen($lines[$i])) {
1094 return '';
1096 continue;
1099 if (64 != strlen($lines[$i])) {
1100 return '';
1103 return implode("\n", $lines);
1104 } else {
1105 return '';
1108 case PARAM_TAG:
1109 $param = fix_utf8($param);
1110 // Please note it is not safe to use the tag name directly anywhere,
1111 // it must be processed with s(), urlencode() before embedding anywhere.
1112 // Remove some nasties.
1113 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1114 // Convert many whitespace chars into one.
1115 $param = preg_replace('/\s+/u', ' ', $param);
1116 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1117 return $param;
1119 case PARAM_TAGLIST:
1120 $param = fix_utf8($param);
1121 $tags = explode(',', $param);
1122 $result = array();
1123 foreach ($tags as $tag) {
1124 $res = clean_param($tag, PARAM_TAG);
1125 if ($res !== '') {
1126 $result[] = $res;
1129 if ($result) {
1130 return implode(',', $result);
1131 } else {
1132 return '';
1135 case PARAM_CAPABILITY:
1136 if (get_capability_info($param)) {
1137 return $param;
1138 } else {
1139 return '';
1142 case PARAM_PERMISSION:
1143 $param = (int)$param;
1144 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1145 return $param;
1146 } else {
1147 return CAP_INHERIT;
1150 case PARAM_AUTH:
1151 $param = clean_param($param, PARAM_PLUGIN);
1152 if (empty($param)) {
1153 return '';
1154 } else if (exists_auth_plugin($param)) {
1155 return $param;
1156 } else {
1157 return '';
1160 case PARAM_LANG:
1161 $param = clean_param($param, PARAM_SAFEDIR);
1162 if (get_string_manager()->translation_exists($param)) {
1163 return $param;
1164 } else {
1165 // Specified language is not installed or param malformed.
1166 return '';
1169 case PARAM_THEME:
1170 $param = clean_param($param, PARAM_PLUGIN);
1171 if (empty($param)) {
1172 return '';
1173 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1174 return $param;
1175 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1176 return $param;
1177 } else {
1178 // Specified theme is not installed.
1179 return '';
1182 case PARAM_USERNAME:
1183 $param = fix_utf8($param);
1184 $param = trim($param);
1185 // Convert uppercase to lowercase MDL-16919.
1186 $param = core_text::strtolower($param);
1187 if (empty($CFG->extendedusernamechars)) {
1188 $param = str_replace(" " , "", $param);
1189 // Regular expression, eliminate all chars EXCEPT:
1190 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1191 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1193 return $param;
1195 case PARAM_EMAIL:
1196 $param = fix_utf8($param);
1197 if (validate_email($param)) {
1198 return $param;
1199 } else {
1200 return '';
1203 case PARAM_STRINGID:
1204 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1205 return $param;
1206 } else {
1207 return '';
1210 case PARAM_TIMEZONE:
1211 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1212 $param = fix_utf8($param);
1213 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1214 if (preg_match($timezonepattern, $param)) {
1215 return $param;
1216 } else {
1217 return '';
1220 default:
1221 // Doh! throw error, switched parameters in optional_param or another serious problem.
1222 print_error("unknownparamtype", '', '', $type);
1227 * Makes sure the data is using valid utf8, invalid characters are discarded.
1229 * Note: this function is not intended for full objects with methods and private properties.
1231 * @param mixed $value
1232 * @return mixed with proper utf-8 encoding
1234 function fix_utf8($value) {
1235 if (is_null($value) or $value === '') {
1236 return $value;
1238 } else if (is_string($value)) {
1239 if ((string)(int)$value === $value) {
1240 // Shortcut.
1241 return $value;
1243 // No null bytes expected in our data, so let's remove it.
1244 $value = str_replace("\0", '', $value);
1246 // Note: this duplicates min_fix_utf8() intentionally.
1247 static $buggyiconv = null;
1248 if ($buggyiconv === null) {
1249 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1252 if ($buggyiconv) {
1253 if (function_exists('mb_convert_encoding')) {
1254 $subst = mb_substitute_character();
1255 mb_substitute_character('');
1256 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1257 mb_substitute_character($subst);
1259 } else {
1260 // Warn admins on admin/index.php page.
1261 $result = $value;
1264 } else {
1265 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1268 return $result;
1270 } else if (is_array($value)) {
1271 foreach ($value as $k => $v) {
1272 $value[$k] = fix_utf8($v);
1274 return $value;
1276 } else if (is_object($value)) {
1277 // Do not modify original.
1278 $value = clone($value);
1279 foreach ($value as $k => $v) {
1280 $value->$k = fix_utf8($v);
1282 return $value;
1284 } else {
1285 // This is some other type, no utf-8 here.
1286 return $value;
1291 * Return true if given value is integer or string with integer value
1293 * @param mixed $value String or Int
1294 * @return bool true if number, false if not
1296 function is_number($value) {
1297 if (is_int($value)) {
1298 return true;
1299 } else if (is_string($value)) {
1300 return ((string)(int)$value) === $value;
1301 } else {
1302 return false;
1307 * Returns host part from url.
1309 * @param string $url full url
1310 * @return string host, null if not found
1312 function get_host_from_url($url) {
1313 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1314 if ($matches) {
1315 return $matches[1];
1317 return null;
1321 * Tests whether anything was returned by text editor
1323 * This function is useful for testing whether something you got back from
1324 * the HTML editor actually contains anything. Sometimes the HTML editor
1325 * appear to be empty, but actually you get back a <br> tag or something.
1327 * @param string $string a string containing HTML.
1328 * @return boolean does the string contain any actual content - that is text,
1329 * images, objects, etc.
1331 function html_is_blank($string) {
1332 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1336 * Set a key in global configuration
1338 * Set a key/value pair in both this session's {@link $CFG} global variable
1339 * and in the 'config' database table for future sessions.
1341 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1342 * In that case it doesn't affect $CFG.
1344 * A NULL value will delete the entry.
1346 * NOTE: this function is called from lib/db/upgrade.php
1348 * @param string $name the key to set
1349 * @param string $value the value to set (without magic quotes)
1350 * @param string $plugin (optional) the plugin scope, default null
1351 * @return bool true or exception
1353 function set_config($name, $value, $plugin=null) {
1354 global $CFG, $DB;
1356 if (empty($plugin)) {
1357 if (!array_key_exists($name, $CFG->config_php_settings)) {
1358 // So it's defined for this invocation at least.
1359 if (is_null($value)) {
1360 unset($CFG->$name);
1361 } else {
1362 // Settings from db are always strings.
1363 $CFG->$name = (string)$value;
1367 if ($DB->get_field('config', 'name', array('name' => $name))) {
1368 if ($value === null) {
1369 $DB->delete_records('config', array('name' => $name));
1370 } else {
1371 $DB->set_field('config', 'value', $value, array('name' => $name));
1373 } else {
1374 if ($value !== null) {
1375 $config = new stdClass();
1376 $config->name = $name;
1377 $config->value = $value;
1378 $DB->insert_record('config', $config, false);
1381 if ($name === 'siteidentifier') {
1382 cache_helper::update_site_identifier($value);
1384 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1385 } else {
1386 // Plugin scope.
1387 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1388 if ($value===null) {
1389 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1390 } else {
1391 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1393 } else {
1394 if ($value !== null) {
1395 $config = new stdClass();
1396 $config->plugin = $plugin;
1397 $config->name = $name;
1398 $config->value = $value;
1399 $DB->insert_record('config_plugins', $config, false);
1402 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1405 return true;
1409 * Get configuration values from the global config table
1410 * or the config_plugins table.
1412 * If called with one parameter, it will load all the config
1413 * variables for one plugin, and return them as an object.
1415 * If called with 2 parameters it will return a string single
1416 * value or false if the value is not found.
1418 * NOTE: this function is called from lib/db/upgrade.php
1420 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1421 * that we need only fetch it once per request.
1422 * @param string $plugin full component name
1423 * @param string $name default null
1424 * @return mixed hash-like object or single value, return false no config found
1425 * @throws dml_exception
1427 function get_config($plugin, $name = null) {
1428 global $CFG, $DB;
1430 static $siteidentifier = null;
1432 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1433 $forced =& $CFG->config_php_settings;
1434 $iscore = true;
1435 $plugin = 'core';
1436 } else {
1437 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1438 $forced =& $CFG->forced_plugin_settings[$plugin];
1439 } else {
1440 $forced = array();
1442 $iscore = false;
1445 if ($siteidentifier === null) {
1446 try {
1447 // This may fail during installation.
1448 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1449 // install the database.
1450 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1451 } catch (dml_exception $ex) {
1452 // Set siteidentifier to false. We don't want to trip this continually.
1453 $siteidentifier = false;
1454 throw $ex;
1458 if (!empty($name)) {
1459 if (array_key_exists($name, $forced)) {
1460 return (string)$forced[$name];
1461 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1462 return $siteidentifier;
1466 $cache = cache::make('core', 'config');
1467 $result = $cache->get($plugin);
1468 if ($result === false) {
1469 // The user is after a recordset.
1470 if (!$iscore) {
1471 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1472 } else {
1473 // This part is not really used any more, but anyway...
1474 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1476 $cache->set($plugin, $result);
1479 if (!empty($name)) {
1480 if (array_key_exists($name, $result)) {
1481 return $result[$name];
1483 return false;
1486 if ($plugin === 'core') {
1487 $result['siteidentifier'] = $siteidentifier;
1490 foreach ($forced as $key => $value) {
1491 if (is_null($value) or is_array($value) or is_object($value)) {
1492 // We do not want any extra mess here, just real settings that could be saved in db.
1493 unset($result[$key]);
1494 } else {
1495 // Convert to string as if it went through the DB.
1496 $result[$key] = (string)$value;
1500 return (object)$result;
1504 * Removes a key from global configuration.
1506 * NOTE: this function is called from lib/db/upgrade.php
1508 * @param string $name the key to set
1509 * @param string $plugin (optional) the plugin scope
1510 * @return boolean whether the operation succeeded.
1512 function unset_config($name, $plugin=null) {
1513 global $CFG, $DB;
1515 if (empty($plugin)) {
1516 unset($CFG->$name);
1517 $DB->delete_records('config', array('name' => $name));
1518 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1519 } else {
1520 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1521 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1524 return true;
1528 * Remove all the config variables for a given plugin.
1530 * NOTE: this function is called from lib/db/upgrade.php
1532 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1533 * @return boolean whether the operation succeeded.
1535 function unset_all_config_for_plugin($plugin) {
1536 global $DB;
1537 // Delete from the obvious config_plugins first.
1538 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1539 // Next delete any suspect settings from config.
1540 $like = $DB->sql_like('name', '?', true, true, false, '|');
1541 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1542 $DB->delete_records_select('config', $like, $params);
1543 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1544 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1546 return true;
1550 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1552 * All users are verified if they still have the necessary capability.
1554 * @param string $value the value of the config setting.
1555 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1556 * @param bool $includeadmins include administrators.
1557 * @return array of user objects.
1559 function get_users_from_config($value, $capability, $includeadmins = true) {
1560 if (empty($value) or $value === '$@NONE@$') {
1561 return array();
1564 // We have to make sure that users still have the necessary capability,
1565 // it should be faster to fetch them all first and then test if they are present
1566 // instead of validating them one-by-one.
1567 $users = get_users_by_capability(context_system::instance(), $capability);
1568 if ($includeadmins) {
1569 $admins = get_admins();
1570 foreach ($admins as $admin) {
1571 $users[$admin->id] = $admin;
1575 if ($value === '$@ALL@$') {
1576 return $users;
1579 $result = array(); // Result in correct order.
1580 $allowed = explode(',', $value);
1581 foreach ($allowed as $uid) {
1582 if (isset($users[$uid])) {
1583 $user = $users[$uid];
1584 $result[$user->id] = $user;
1588 return $result;
1593 * Invalidates browser caches and cached data in temp.
1595 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1596 * {@link phpunit_util::reset_dataroot()}
1598 * @return void
1600 function purge_all_caches() {
1601 global $CFG, $DB;
1603 reset_text_filters_cache();
1604 js_reset_all_caches();
1605 theme_reset_all_caches();
1606 get_string_manager()->reset_caches();
1607 core_text::reset_caches();
1608 if (class_exists('core_plugin_manager')) {
1609 core_plugin_manager::reset_caches();
1612 // Bump up cacherev field for all courses.
1613 try {
1614 increment_revision_number('course', 'cacherev', '');
1615 } catch (moodle_exception $e) {
1616 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1619 $DB->reset_caches();
1620 cache_helper::purge_all();
1622 // Purge all other caches: rss, simplepie, etc.
1623 remove_dir($CFG->cachedir.'', true);
1625 // Make sure cache dir is writable, throws exception if not.
1626 make_cache_directory('');
1628 // This is the only place where we purge local caches, we are only adding files there.
1629 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1630 remove_dir($CFG->localcachedir, true);
1631 set_config('localcachedirpurged', time());
1632 make_localcache_directory('', true);
1633 \core\task\manager::clear_static_caches();
1637 * Get volatile flags
1639 * @param string $type
1640 * @param int $changedsince default null
1641 * @return array records array
1643 function get_cache_flags($type, $changedsince = null) {
1644 global $DB;
1646 $params = array('type' => $type, 'expiry' => time());
1647 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1648 if ($changedsince !== null) {
1649 $params['changedsince'] = $changedsince;
1650 $sqlwhere .= " AND timemodified > :changedsince";
1652 $cf = array();
1653 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1654 foreach ($flags as $flag) {
1655 $cf[$flag->name] = $flag->value;
1658 return $cf;
1662 * Get volatile flags
1664 * @param string $type
1665 * @param string $name
1666 * @param int $changedsince default null
1667 * @return string|false The cache flag value or false
1669 function get_cache_flag($type, $name, $changedsince=null) {
1670 global $DB;
1672 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1674 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1675 if ($changedsince !== null) {
1676 $params['changedsince'] = $changedsince;
1677 $sqlwhere .= " AND timemodified > :changedsince";
1680 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1684 * Set a volatile flag
1686 * @param string $type the "type" namespace for the key
1687 * @param string $name the key to set
1688 * @param string $value the value to set (without magic quotes) - null will remove the flag
1689 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1690 * @return bool Always returns true
1692 function set_cache_flag($type, $name, $value, $expiry = null) {
1693 global $DB;
1695 $timemodified = time();
1696 if ($expiry === null || $expiry < $timemodified) {
1697 $expiry = $timemodified + 24 * 60 * 60;
1698 } else {
1699 $expiry = (int)$expiry;
1702 if ($value === null) {
1703 unset_cache_flag($type, $name);
1704 return true;
1707 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1708 // This is a potential problem in DEBUG_DEVELOPER.
1709 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1710 return true; // No need to update.
1712 $f->value = $value;
1713 $f->expiry = $expiry;
1714 $f->timemodified = $timemodified;
1715 $DB->update_record('cache_flags', $f);
1716 } else {
1717 $f = new stdClass();
1718 $f->flagtype = $type;
1719 $f->name = $name;
1720 $f->value = $value;
1721 $f->expiry = $expiry;
1722 $f->timemodified = $timemodified;
1723 $DB->insert_record('cache_flags', $f);
1725 return true;
1729 * Removes a single volatile flag
1731 * @param string $type the "type" namespace for the key
1732 * @param string $name the key to set
1733 * @return bool
1735 function unset_cache_flag($type, $name) {
1736 global $DB;
1737 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1738 return true;
1742 * Garbage-collect volatile flags
1744 * @return bool Always returns true
1746 function gc_cache_flags() {
1747 global $DB;
1748 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1749 return true;
1752 // USER PREFERENCE API.
1755 * Refresh user preference cache. This is used most often for $USER
1756 * object that is stored in session, but it also helps with performance in cron script.
1758 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1760 * @package core
1761 * @category preference
1762 * @access public
1763 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1764 * @param int $cachelifetime Cache life time on the current page (in seconds)
1765 * @throws coding_exception
1766 * @return null
1768 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1769 global $DB;
1770 // Static cache, we need to check on each page load, not only every 2 minutes.
1771 static $loadedusers = array();
1773 if (!isset($user->id)) {
1774 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1777 if (empty($user->id) or isguestuser($user->id)) {
1778 // No permanent storage for not-logged-in users and guest.
1779 if (!isset($user->preference)) {
1780 $user->preference = array();
1782 return;
1785 $timenow = time();
1787 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1788 // Already loaded at least once on this page. Are we up to date?
1789 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1790 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1791 return;
1793 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1794 // No change since the lastcheck on this page.
1795 $user->preference['_lastloaded'] = $timenow;
1796 return;
1800 // OK, so we have to reload all preferences.
1801 $loadedusers[$user->id] = true;
1802 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1803 $user->preference['_lastloaded'] = $timenow;
1807 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1809 * NOTE: internal function, do not call from other code.
1811 * @package core
1812 * @access private
1813 * @param integer $userid the user whose prefs were changed.
1815 function mark_user_preferences_changed($userid) {
1816 global $CFG;
1818 if (empty($userid) or isguestuser($userid)) {
1819 // No cache flags for guest and not-logged-in users.
1820 return;
1823 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1827 * Sets a preference for the specified user.
1829 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1831 * @package core
1832 * @category preference
1833 * @access public
1834 * @param string $name The key to set as preference for the specified user
1835 * @param string $value The value to set for the $name key in the specified user's
1836 * record, null means delete current value.
1837 * @param stdClass|int|null $user A moodle user object or id, null means current user
1838 * @throws coding_exception
1839 * @return bool Always true or exception
1841 function set_user_preference($name, $value, $user = null) {
1842 global $USER, $DB;
1844 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1845 throw new coding_exception('Invalid preference name in set_user_preference() call');
1848 if (is_null($value)) {
1849 // Null means delete current.
1850 return unset_user_preference($name, $user);
1851 } else if (is_object($value)) {
1852 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1853 } else if (is_array($value)) {
1854 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1856 // Value column maximum length is 1333 characters.
1857 $value = (string)$value;
1858 if (core_text::strlen($value) > 1333) {
1859 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1862 if (is_null($user)) {
1863 $user = $USER;
1864 } else if (isset($user->id)) {
1865 // It is a valid object.
1866 } else if (is_numeric($user)) {
1867 $user = (object)array('id' => (int)$user);
1868 } else {
1869 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1872 check_user_preferences_loaded($user);
1874 if (empty($user->id) or isguestuser($user->id)) {
1875 // No permanent storage for not-logged-in users and guest.
1876 $user->preference[$name] = $value;
1877 return true;
1880 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1881 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1882 // Preference already set to this value.
1883 return true;
1885 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1887 } else {
1888 $preference = new stdClass();
1889 $preference->userid = $user->id;
1890 $preference->name = $name;
1891 $preference->value = $value;
1892 $DB->insert_record('user_preferences', $preference);
1895 // Update value in cache.
1896 $user->preference[$name] = $value;
1898 // Set reload flag for other sessions.
1899 mark_user_preferences_changed($user->id);
1901 return true;
1905 * Sets a whole array of preferences for the current user
1907 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1909 * @package core
1910 * @category preference
1911 * @access public
1912 * @param array $prefarray An array of key/value pairs to be set
1913 * @param stdClass|int|null $user A moodle user object or id, null means current user
1914 * @return bool Always true or exception
1916 function set_user_preferences(array $prefarray, $user = null) {
1917 foreach ($prefarray as $name => $value) {
1918 set_user_preference($name, $value, $user);
1920 return true;
1924 * Unsets a preference completely by deleting it from the database
1926 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1928 * @package core
1929 * @category preference
1930 * @access public
1931 * @param string $name The key to unset as preference for the specified user
1932 * @param stdClass|int|null $user A moodle user object or id, null means current user
1933 * @throws coding_exception
1934 * @return bool Always true or exception
1936 function unset_user_preference($name, $user = null) {
1937 global $USER, $DB;
1939 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1940 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1943 if (is_null($user)) {
1944 $user = $USER;
1945 } else if (isset($user->id)) {
1946 // It is a valid object.
1947 } else if (is_numeric($user)) {
1948 $user = (object)array('id' => (int)$user);
1949 } else {
1950 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1953 check_user_preferences_loaded($user);
1955 if (empty($user->id) or isguestuser($user->id)) {
1956 // No permanent storage for not-logged-in user and guest.
1957 unset($user->preference[$name]);
1958 return true;
1961 // Delete from DB.
1962 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1964 // Delete the preference from cache.
1965 unset($user->preference[$name]);
1967 // Set reload flag for other sessions.
1968 mark_user_preferences_changed($user->id);
1970 return true;
1974 * Used to fetch user preference(s)
1976 * If no arguments are supplied this function will return
1977 * all of the current user preferences as an array.
1979 * If a name is specified then this function
1980 * attempts to return that particular preference value. If
1981 * none is found, then the optional value $default is returned,
1982 * otherwise null.
1984 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1986 * @package core
1987 * @category preference
1988 * @access public
1989 * @param string $name Name of the key to use in finding a preference value
1990 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1991 * @param stdClass|int|null $user A moodle user object or id, null means current user
1992 * @throws coding_exception
1993 * @return string|mixed|null A string containing the value of a single preference. An
1994 * array with all of the preferences or null
1996 function get_user_preferences($name = null, $default = null, $user = null) {
1997 global $USER;
1999 if (is_null($name)) {
2000 // All prefs.
2001 } else if (is_numeric($name) or $name === '_lastloaded') {
2002 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2005 if (is_null($user)) {
2006 $user = $USER;
2007 } else if (isset($user->id)) {
2008 // Is a valid object.
2009 } else if (is_numeric($user)) {
2010 $user = (object)array('id' => (int)$user);
2011 } else {
2012 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2015 check_user_preferences_loaded($user);
2017 if (empty($name)) {
2018 // All values.
2019 return $user->preference;
2020 } else if (isset($user->preference[$name])) {
2021 // The single string value.
2022 return $user->preference[$name];
2023 } else {
2024 // Default value (null if not specified).
2025 return $default;
2029 // FUNCTIONS FOR HANDLING TIME.
2032 * Given date parts in user time produce a GMT timestamp.
2034 * @package core
2035 * @category time
2036 * @param int $year The year part to create timestamp of
2037 * @param int $month The month part to create timestamp of
2038 * @param int $day The day part to create timestamp of
2039 * @param int $hour The hour part to create timestamp of
2040 * @param int $minute The minute part to create timestamp of
2041 * @param int $second The second part to create timestamp of
2042 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2043 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2044 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2045 * applied only if timezone is 99 or string.
2046 * @return int GMT timestamp
2048 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2049 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2050 $date->setDate((int)$year, (int)$month, (int)$day);
2051 $date->setTime((int)$hour, (int)$minute, (int)$second);
2053 $time = $date->getTimestamp();
2055 // Moodle BC DST stuff.
2056 if (!$applydst) {
2057 $time += dst_offset_on($time, $timezone);
2060 return $time;
2065 * Format a date/time (seconds) as weeks, days, hours etc as needed
2067 * Given an amount of time in seconds, returns string
2068 * formatted nicely as weeks, days, hours etc as needed
2070 * @package core
2071 * @category time
2072 * @uses MINSECS
2073 * @uses HOURSECS
2074 * @uses DAYSECS
2075 * @uses YEARSECS
2076 * @param int $totalsecs Time in seconds
2077 * @param stdClass $str Should be a time object
2078 * @return string A nicely formatted date/time string
2080 function format_time($totalsecs, $str = null) {
2082 $totalsecs = abs($totalsecs);
2084 if (!$str) {
2085 // Create the str structure the slow way.
2086 $str = new stdClass();
2087 $str->day = get_string('day');
2088 $str->days = get_string('days');
2089 $str->hour = get_string('hour');
2090 $str->hours = get_string('hours');
2091 $str->min = get_string('min');
2092 $str->mins = get_string('mins');
2093 $str->sec = get_string('sec');
2094 $str->secs = get_string('secs');
2095 $str->year = get_string('year');
2096 $str->years = get_string('years');
2099 $years = floor($totalsecs/YEARSECS);
2100 $remainder = $totalsecs - ($years*YEARSECS);
2101 $days = floor($remainder/DAYSECS);
2102 $remainder = $totalsecs - ($days*DAYSECS);
2103 $hours = floor($remainder/HOURSECS);
2104 $remainder = $remainder - ($hours*HOURSECS);
2105 $mins = floor($remainder/MINSECS);
2106 $secs = $remainder - ($mins*MINSECS);
2108 $ss = ($secs == 1) ? $str->sec : $str->secs;
2109 $sm = ($mins == 1) ? $str->min : $str->mins;
2110 $sh = ($hours == 1) ? $str->hour : $str->hours;
2111 $sd = ($days == 1) ? $str->day : $str->days;
2112 $sy = ($years == 1) ? $str->year : $str->years;
2114 $oyears = '';
2115 $odays = '';
2116 $ohours = '';
2117 $omins = '';
2118 $osecs = '';
2120 if ($years) {
2121 $oyears = $years .' '. $sy;
2123 if ($days) {
2124 $odays = $days .' '. $sd;
2126 if ($hours) {
2127 $ohours = $hours .' '. $sh;
2129 if ($mins) {
2130 $omins = $mins .' '. $sm;
2132 if ($secs) {
2133 $osecs = $secs .' '. $ss;
2136 if ($years) {
2137 return trim($oyears .' '. $odays);
2139 if ($days) {
2140 return trim($odays .' '. $ohours);
2142 if ($hours) {
2143 return trim($ohours .' '. $omins);
2145 if ($mins) {
2146 return trim($omins .' '. $osecs);
2148 if ($secs) {
2149 return $osecs;
2151 return get_string('now');
2155 * Returns a formatted string that represents a date in user time.
2157 * @package core
2158 * @category time
2159 * @param int $date the timestamp in UTC, as obtained from the database.
2160 * @param string $format strftime format. You should probably get this using
2161 * get_string('strftime...', 'langconfig');
2162 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2163 * not 99 then daylight saving will not be added.
2164 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2165 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2166 * If false then the leading zero is maintained.
2167 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2168 * @return string the formatted date/time.
2170 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2171 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2172 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2176 * Returns a formatted date ensuring it is UTF-8.
2178 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2179 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2181 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2182 * @param string $format strftime format.
2183 * @param int|float|string $tz the user timezone
2184 * @return string the formatted date/time.
2185 * @since Moodle 2.3.3
2187 function date_format_string($date, $format, $tz = 99) {
2188 global $CFG;
2190 $localewincharset = null;
2191 // Get the calendar type user is using.
2192 if ($CFG->ostype == 'WINDOWS') {
2193 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2194 $localewincharset = $calendartype->locale_win_charset();
2197 if ($localewincharset) {
2198 $format = core_text::convert($format, 'utf-8', $localewincharset);
2201 date_default_timezone_set(core_date::get_user_timezone($tz));
2202 $datestring = strftime($format, $date);
2203 core_date::set_default_server_timezone();
2205 if ($localewincharset) {
2206 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2209 return $datestring;
2213 * Given a $time timestamp in GMT (seconds since epoch),
2214 * returns an array that represents the date in user time
2216 * @package core
2217 * @category time
2218 * @param int $time Timestamp in GMT
2219 * @param float|int|string $timezone user timezone
2220 * @return array An array that represents the date in user time
2222 function usergetdate($time, $timezone=99) {
2223 date_default_timezone_set(core_date::get_user_timezone($timezone));
2224 $result = getdate($time);
2225 core_date::set_default_server_timezone();
2227 return $result;
2231 * Given a GMT timestamp (seconds since epoch), offsets it by
2232 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2234 * NOTE: this function does not include DST properly,
2235 * you should use the PHP date stuff instead!
2237 * @package core
2238 * @category time
2239 * @param int $date Timestamp in GMT
2240 * @param float|int|string $timezone user timezone
2241 * @return int
2243 function usertime($date, $timezone=99) {
2244 $userdate = new DateTime('@' . $date);
2245 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2246 $dst = dst_offset_on($date, $timezone);
2248 return $date - $userdate->getOffset() + $dst;
2252 * Given a time, return the GMT timestamp of the most recent midnight
2253 * for the current user.
2255 * @package core
2256 * @category time
2257 * @param int $date Timestamp in GMT
2258 * @param float|int|string $timezone user timezone
2259 * @return int Returns a GMT timestamp
2261 function usergetmidnight($date, $timezone=99) {
2263 $userdate = usergetdate($date, $timezone);
2265 // Time of midnight of this user's day, in GMT.
2266 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2271 * Returns a string that prints the user's timezone
2273 * @package core
2274 * @category time
2275 * @param float|int|string $timezone user timezone
2276 * @return string
2278 function usertimezone($timezone=99) {
2279 $tz = core_date::get_user_timezone($timezone);
2280 return core_date::get_localised_timezone($tz);
2284 * Returns a float or a string which denotes the user's timezone
2285 * 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)
2286 * means that for this timezone there are also DST rules to be taken into account
2287 * Checks various settings and picks the most dominant of those which have a value
2289 * @package core
2290 * @category time
2291 * @param float|int|string $tz timezone to calculate GMT time offset before
2292 * calculating user timezone, 99 is default user timezone
2293 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2294 * @return float|string
2296 function get_user_timezone($tz = 99) {
2297 global $USER, $CFG;
2299 $timezones = array(
2300 $tz,
2301 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2302 isset($USER->timezone) ? $USER->timezone : 99,
2303 isset($CFG->timezone) ? $CFG->timezone : 99,
2306 $tz = 99;
2308 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2309 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2310 $tz = $next['value'];
2312 return is_numeric($tz) ? (float) $tz : $tz;
2316 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2317 * - Note: Daylight saving only works for string timezones and not for float.
2319 * @package core
2320 * @category time
2321 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2322 * @param int|float|string $strtimezone user timezone
2323 * @return int
2325 function dst_offset_on($time, $strtimezone = null) {
2326 $tz = core_date::get_user_timezone($strtimezone);
2327 $date = new DateTime('@' . $time);
2328 $date->setTimezone(new DateTimeZone($tz));
2329 if ($date->format('I') == '1') {
2330 if ($tz === 'Australia/Lord_Howe') {
2331 return 1800;
2333 return 3600;
2335 return 0;
2339 * Calculates when the day appears in specific month
2341 * @package core
2342 * @category time
2343 * @param int $startday starting day of the month
2344 * @param int $weekday The day when week starts (normally taken from user preferences)
2345 * @param int $month The month whose day is sought
2346 * @param int $year The year of the month whose day is sought
2347 * @return int
2349 function find_day_in_month($startday, $weekday, $month, $year) {
2350 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2352 $daysinmonth = days_in_month($month, $year);
2353 $daysinweek = count($calendartype->get_weekdays());
2355 if ($weekday == -1) {
2356 // Don't care about weekday, so return:
2357 // abs($startday) if $startday != -1
2358 // $daysinmonth otherwise.
2359 return ($startday == -1) ? $daysinmonth : abs($startday);
2362 // From now on we 're looking for a specific weekday.
2363 // Give "end of month" its actual value, since we know it.
2364 if ($startday == -1) {
2365 $startday = -1 * $daysinmonth;
2368 // Starting from day $startday, the sign is the direction.
2369 if ($startday < 1) {
2370 $startday = abs($startday);
2371 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2373 // This is the last such weekday of the month.
2374 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2375 if ($lastinmonth > $daysinmonth) {
2376 $lastinmonth -= $daysinweek;
2379 // Find the first such weekday <= $startday.
2380 while ($lastinmonth > $startday) {
2381 $lastinmonth -= $daysinweek;
2384 return $lastinmonth;
2385 } else {
2386 $indexweekday = dayofweek($startday, $month, $year);
2388 $diff = $weekday - $indexweekday;
2389 if ($diff < 0) {
2390 $diff += $daysinweek;
2393 // This is the first such weekday of the month equal to or after $startday.
2394 $firstfromindex = $startday + $diff;
2396 return $firstfromindex;
2401 * Calculate the number of days in a given month
2403 * @package core
2404 * @category time
2405 * @param int $month The month whose day count is sought
2406 * @param int $year The year of the month whose day count is sought
2407 * @return int
2409 function days_in_month($month, $year) {
2410 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2411 return $calendartype->get_num_days_in_month($year, $month);
2415 * Calculate the position in the week of a specific calendar day
2417 * @package core
2418 * @category time
2419 * @param int $day The day of the date whose position in the week is sought
2420 * @param int $month The month of the date whose position in the week is sought
2421 * @param int $year The year of the date whose position in the week is sought
2422 * @return int
2424 function dayofweek($day, $month, $year) {
2425 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2426 return $calendartype->get_weekday($year, $month, $day);
2429 // USER AUTHENTICATION AND LOGIN.
2432 * Returns full login url.
2434 * @return string login url
2436 function get_login_url() {
2437 global $CFG;
2439 $url = "$CFG->wwwroot/login/index.php";
2441 if (!empty($CFG->loginhttps)) {
2442 $url = str_replace('http:', 'https:', $url);
2445 return $url;
2449 * This function checks that the current user is logged in and has the
2450 * required privileges
2452 * This function checks that the current user is logged in, and optionally
2453 * whether they are allowed to be in a particular course and view a particular
2454 * course module.
2455 * If they are not logged in, then it redirects them to the site login unless
2456 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2457 * case they are automatically logged in as guests.
2458 * If $courseid is given and the user is not enrolled in that course then the
2459 * user is redirected to the course enrolment page.
2460 * If $cm is given and the course module is hidden and the user is not a teacher
2461 * in the course then the user is redirected to the course home page.
2463 * When $cm parameter specified, this function sets page layout to 'module'.
2464 * You need to change it manually later if some other layout needed.
2466 * @package core_access
2467 * @category access
2469 * @param mixed $courseorid id of the course or course object
2470 * @param bool $autologinguest default true
2471 * @param object $cm course module object
2472 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2473 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2474 * in order to keep redirects working properly. MDL-14495
2475 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2476 * @return mixed Void, exit, and die depending on path
2477 * @throws coding_exception
2478 * @throws require_login_exception
2480 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2481 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2483 // Must not redirect when byteserving already started.
2484 if (!empty($_SERVER['HTTP_RANGE'])) {
2485 $preventredirect = true;
2488 if (AJAX_SCRIPT) {
2489 // We cannot redirect for AJAX scripts either.
2490 $preventredirect = true;
2493 // Setup global $COURSE, themes, language and locale.
2494 if (!empty($courseorid)) {
2495 if (is_object($courseorid)) {
2496 $course = $courseorid;
2497 } else if ($courseorid == SITEID) {
2498 $course = clone($SITE);
2499 } else {
2500 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2502 if ($cm) {
2503 if ($cm->course != $course->id) {
2504 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2506 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2507 if (!($cm instanceof cm_info)) {
2508 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2509 // db queries so this is not really a performance concern, however it is obviously
2510 // better if you use get_fast_modinfo to get the cm before calling this.
2511 $modinfo = get_fast_modinfo($course);
2512 $cm = $modinfo->get_cm($cm->id);
2515 } else {
2516 // Do not touch global $COURSE via $PAGE->set_course(),
2517 // the reasons is we need to be able to call require_login() at any time!!
2518 $course = $SITE;
2519 if ($cm) {
2520 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2524 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2525 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2526 // risk leading the user back to the AJAX request URL.
2527 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2528 $setwantsurltome = false;
2531 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2532 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2533 if ($preventredirect) {
2534 throw new require_login_session_timeout_exception();
2535 } else {
2536 if ($setwantsurltome) {
2537 $SESSION->wantsurl = qualified_me();
2539 redirect(get_login_url());
2543 // If the user is not even logged in yet then make sure they are.
2544 if (!isloggedin()) {
2545 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2546 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2547 // Misconfigured site guest, just redirect to login page.
2548 redirect(get_login_url());
2549 exit; // Never reached.
2551 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2552 complete_user_login($guest);
2553 $USER->autologinguest = true;
2554 $SESSION->lang = $lang;
2555 } else {
2556 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2557 if ($preventredirect) {
2558 throw new require_login_exception('You are not logged in');
2561 if ($setwantsurltome) {
2562 $SESSION->wantsurl = qualified_me();
2565 $referer = get_local_referer(false);
2566 if (!empty($referer)) {
2567 $SESSION->fromurl = $referer;
2570 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2571 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2572 foreach($authsequence as $authname) {
2573 $authplugin = get_auth_plugin($authname);
2574 $authplugin->pre_loginpage_hook();
2575 if (isloggedin()) {
2576 break;
2580 // If we're still not logged in then go to the login page
2581 if (!isloggedin()) {
2582 redirect(get_login_url());
2583 exit; // Never reached.
2588 // Loginas as redirection if needed.
2589 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2590 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2591 if ($USER->loginascontext->instanceid != $course->id) {
2592 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2597 // Check whether the user should be changing password (but only if it is REALLY them).
2598 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2599 $userauth = get_auth_plugin($USER->auth);
2600 if ($userauth->can_change_password() and !$preventredirect) {
2601 if ($setwantsurltome) {
2602 $SESSION->wantsurl = qualified_me();
2604 if ($changeurl = $userauth->change_password_url()) {
2605 // Use plugin custom url.
2606 redirect($changeurl);
2607 } else {
2608 // Use moodle internal method.
2609 if (empty($CFG->loginhttps)) {
2610 redirect($CFG->wwwroot .'/login/change_password.php');
2611 } else {
2612 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2613 redirect($wwwroot .'/login/change_password.php');
2616 } else {
2617 print_error('nopasswordchangeforced', 'auth');
2621 // Check that the user account is properly set up.
2622 if (user_not_fully_set_up($USER)) {
2623 if ($preventredirect) {
2624 throw new require_login_exception('User not fully set-up');
2626 if ($setwantsurltome) {
2627 $SESSION->wantsurl = qualified_me();
2629 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2632 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2633 sesskey();
2635 // Do not bother admins with any formalities.
2636 if (is_siteadmin()) {
2637 // Set the global $COURSE.
2638 if ($cm) {
2639 $PAGE->set_cm($cm, $course);
2640 $PAGE->set_pagelayout('incourse');
2641 } else if (!empty($courseorid)) {
2642 $PAGE->set_course($course);
2644 // Set accesstime or the user will appear offline which messes up messaging.
2645 user_accesstime_log($course->id);
2646 return;
2649 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2650 if (!$USER->policyagreed and !is_siteadmin()) {
2651 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2652 if ($preventredirect) {
2653 throw new require_login_exception('Policy not agreed');
2655 if ($setwantsurltome) {
2656 $SESSION->wantsurl = qualified_me();
2658 redirect($CFG->wwwroot .'/user/policy.php');
2659 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2660 if ($preventredirect) {
2661 throw new require_login_exception('Policy not agreed');
2663 if ($setwantsurltome) {
2664 $SESSION->wantsurl = qualified_me();
2666 redirect($CFG->wwwroot .'/user/policy.php');
2670 // Fetch the system context, the course context, and prefetch its child contexts.
2671 $sysctx = context_system::instance();
2672 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2673 if ($cm) {
2674 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2675 } else {
2676 $cmcontext = null;
2679 // If the site is currently under maintenance, then print a message.
2680 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2681 if ($preventredirect) {
2682 throw new require_login_exception('Maintenance in progress');
2685 print_maintenance_message();
2688 // Make sure the course itself is not hidden.
2689 if ($course->id == SITEID) {
2690 // Frontpage can not be hidden.
2691 } else {
2692 if (is_role_switched($course->id)) {
2693 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2694 } else {
2695 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2696 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2697 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2698 if ($preventredirect) {
2699 throw new require_login_exception('Course is hidden');
2701 $PAGE->set_context(null);
2702 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2703 // the navigation will mess up when trying to find it.
2704 navigation_node::override_active_url(new moodle_url('/'));
2705 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2710 // Is the user enrolled?
2711 if ($course->id == SITEID) {
2712 // Everybody is enrolled on the frontpage.
2713 } else {
2714 if (\core\session\manager::is_loggedinas()) {
2715 // Make sure the REAL person can access this course first.
2716 $realuser = \core\session\manager::get_realuser();
2717 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2718 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2719 if ($preventredirect) {
2720 throw new require_login_exception('Invalid course login-as access');
2722 $PAGE->set_context(null);
2723 echo $OUTPUT->header();
2724 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2728 $access = false;
2730 if (is_role_switched($course->id)) {
2731 // Ok, user had to be inside this course before the switch.
2732 $access = true;
2734 } else if (is_viewing($coursecontext, $USER)) {
2735 // Ok, no need to mess with enrol.
2736 $access = true;
2738 } else {
2739 if (isset($USER->enrol['enrolled'][$course->id])) {
2740 if ($USER->enrol['enrolled'][$course->id] > time()) {
2741 $access = true;
2742 if (isset($USER->enrol['tempguest'][$course->id])) {
2743 unset($USER->enrol['tempguest'][$course->id]);
2744 remove_temp_course_roles($coursecontext);
2746 } else {
2747 // Expired.
2748 unset($USER->enrol['enrolled'][$course->id]);
2751 if (isset($USER->enrol['tempguest'][$course->id])) {
2752 if ($USER->enrol['tempguest'][$course->id] == 0) {
2753 $access = true;
2754 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2755 $access = true;
2756 } else {
2757 // Expired.
2758 unset($USER->enrol['tempguest'][$course->id]);
2759 remove_temp_course_roles($coursecontext);
2763 if (!$access) {
2764 // Cache not ok.
2765 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2766 if ($until !== false) {
2767 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2768 if ($until == 0) {
2769 $until = ENROL_MAX_TIMESTAMP;
2771 $USER->enrol['enrolled'][$course->id] = $until;
2772 $access = true;
2774 } else {
2775 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2776 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2777 $enrols = enrol_get_plugins(true);
2778 // First ask all enabled enrol instances in course if they want to auto enrol user.
2779 foreach ($instances as $instance) {
2780 if (!isset($enrols[$instance->enrol])) {
2781 continue;
2783 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2784 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2785 if ($until !== false) {
2786 if ($until == 0) {
2787 $until = ENROL_MAX_TIMESTAMP;
2789 $USER->enrol['enrolled'][$course->id] = $until;
2790 $access = true;
2791 break;
2794 // If not enrolled yet try to gain temporary guest access.
2795 if (!$access) {
2796 foreach ($instances as $instance) {
2797 if (!isset($enrols[$instance->enrol])) {
2798 continue;
2800 // Get a duration for the guest access, a timestamp in the future or false.
2801 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2802 if ($until !== false and $until > time()) {
2803 $USER->enrol['tempguest'][$course->id] = $until;
2804 $access = true;
2805 break;
2813 if (!$access) {
2814 if ($preventredirect) {
2815 throw new require_login_exception('Not enrolled');
2817 if ($setwantsurltome) {
2818 $SESSION->wantsurl = qualified_me();
2820 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2824 // Set the global $COURSE.
2825 // TODO MDL-49434: setting current course/cm should be after the check $cm->uservisible .
2826 if ($cm) {
2827 $PAGE->set_cm($cm, $course);
2828 $PAGE->set_pagelayout('incourse');
2829 } else if (!empty($courseorid)) {
2830 $PAGE->set_course($course);
2833 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2834 if ($cm && !$cm->uservisible) {
2835 if ($preventredirect) {
2836 throw new require_login_exception('Activity is hidden');
2838 if ($course->id != SITEID) {
2839 $url = new moodle_url('/course/view.php', array('id' => $course->id));
2840 } else {
2841 $url = new moodle_url('/');
2843 redirect($url, get_string('activityiscurrentlyhidden'));
2846 // Finally access granted, update lastaccess times.
2847 user_accesstime_log($course->id);
2852 * This function just makes sure a user is logged out.
2854 * @package core_access
2855 * @category access
2857 function require_logout() {
2858 global $USER, $DB;
2860 if (!isloggedin()) {
2861 // This should not happen often, no need for hooks or events here.
2862 \core\session\manager::terminate_current();
2863 return;
2866 // Execute hooks before action.
2867 $authplugins = array();
2868 $authsequence = get_enabled_auth_plugins();
2869 foreach ($authsequence as $authname) {
2870 $authplugins[$authname] = get_auth_plugin($authname);
2871 $authplugins[$authname]->prelogout_hook();
2874 // Store info that gets removed during logout.
2875 $sid = session_id();
2876 $event = \core\event\user_loggedout::create(
2877 array(
2878 'userid' => $USER->id,
2879 'objectid' => $USER->id,
2880 'other' => array('sessionid' => $sid),
2883 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2884 $event->add_record_snapshot('sessions', $session);
2887 // Clone of $USER object to be used by auth plugins.
2888 $user = fullclone($USER);
2890 // Delete session record and drop $_SESSION content.
2891 \core\session\manager::terminate_current();
2893 // Trigger event AFTER action.
2894 $event->trigger();
2896 // Hook to execute auth plugins redirection after event trigger.
2897 foreach ($authplugins as $authplugin) {
2898 $authplugin->postlogout_hook($user);
2903 * Weaker version of require_login()
2905 * This is a weaker version of {@link require_login()} which only requires login
2906 * when called from within a course rather than the site page, unless
2907 * the forcelogin option is turned on.
2908 * @see require_login()
2910 * @package core_access
2911 * @category access
2913 * @param mixed $courseorid The course object or id in question
2914 * @param bool $autologinguest Allow autologin guests if that is wanted
2915 * @param object $cm Course activity module if known
2916 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2917 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2918 * in order to keep redirects working properly. MDL-14495
2919 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2920 * @return void
2921 * @throws coding_exception
2923 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2924 global $CFG, $PAGE, $SITE;
2925 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2926 or (!is_object($courseorid) and $courseorid == SITEID));
2927 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2928 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2929 // db queries so this is not really a performance concern, however it is obviously
2930 // better if you use get_fast_modinfo to get the cm before calling this.
2931 if (is_object($courseorid)) {
2932 $course = $courseorid;
2933 } else {
2934 $course = clone($SITE);
2936 $modinfo = get_fast_modinfo($course);
2937 $cm = $modinfo->get_cm($cm->id);
2939 if (!empty($CFG->forcelogin)) {
2940 // Login required for both SITE and courses.
2941 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2943 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2944 // Always login for hidden activities.
2945 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2947 } else if ($issite) {
2948 // Login for SITE not required.
2949 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
2950 if (!empty($courseorid)) {
2951 if (is_object($courseorid)) {
2952 $course = $courseorid;
2953 } else {
2954 $course = clone $SITE;
2956 if ($cm) {
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');
2962 } else {
2963 $PAGE->set_course($course);
2965 } else {
2966 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
2967 $PAGE->set_course($PAGE->course);
2969 user_accesstime_log(SITEID);
2970 return;
2972 } else {
2973 // Course login always required.
2974 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2979 * Require key login. Function terminates with error if key not found or incorrect.
2981 * @uses NO_MOODLE_COOKIES
2982 * @uses PARAM_ALPHANUM
2983 * @param string $script unique script identifier
2984 * @param int $instance optional instance id
2985 * @return int Instance ID
2987 function require_user_key_login($script, $instance=null) {
2988 global $DB;
2990 if (!NO_MOODLE_COOKIES) {
2991 print_error('sessioncookiesdisable');
2994 // Extra safety.
2995 \core\session\manager::write_close();
2997 $keyvalue = required_param('key', PARAM_ALPHANUM);
2999 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3000 print_error('invalidkey');
3003 if (!empty($key->validuntil) and $key->validuntil < time()) {
3004 print_error('expiredkey');
3007 if ($key->iprestriction) {
3008 $remoteaddr = getremoteaddr(null);
3009 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3010 print_error('ipmismatch');
3014 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3015 print_error('invaliduserid');
3018 // Emulate normal session.
3019 enrol_check_plugins($user);
3020 \core\session\manager::set_user($user);
3022 // Note we are not using normal login.
3023 if (!defined('USER_KEY_LOGIN')) {
3024 define('USER_KEY_LOGIN', true);
3027 // Return instance id - it might be empty.
3028 return $key->instance;
3032 * Creates a new private user access key.
3034 * @param string $script unique target identifier
3035 * @param int $userid
3036 * @param int $instance optional instance id
3037 * @param string $iprestriction optional ip restricted access
3038 * @param timestamp $validuntil key valid only until given data
3039 * @return string access key value
3041 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3042 global $DB;
3044 $key = new stdClass();
3045 $key->script = $script;
3046 $key->userid = $userid;
3047 $key->instance = $instance;
3048 $key->iprestriction = $iprestriction;
3049 $key->validuntil = $validuntil;
3050 $key->timecreated = time();
3052 // Something long and unique.
3053 $key->value = md5($userid.'_'.time().random_string(40));
3054 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3055 // Must be unique.
3056 $key->value = md5($userid.'_'.time().random_string(40));
3058 $DB->insert_record('user_private_key', $key);
3059 return $key->value;
3063 * Delete the user's new private user access keys for a particular script.
3065 * @param string $script unique target identifier
3066 * @param int $userid
3067 * @return void
3069 function delete_user_key($script, $userid) {
3070 global $DB;
3071 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3075 * Gets a private user access key (and creates one if one doesn't exist).
3077 * @param string $script unique target identifier
3078 * @param int $userid
3079 * @param int $instance optional instance id
3080 * @param string $iprestriction optional ip restricted access
3081 * @param timestamp $validuntil key valid only until given data
3082 * @return string access key value
3084 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3085 global $DB;
3087 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3088 'instance' => $instance, 'iprestriction' => $iprestriction,
3089 'validuntil' => $validuntil))) {
3090 return $key->value;
3091 } else {
3092 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3098 * Modify the user table by setting the currently logged in user's last login to now.
3100 * @return bool Always returns true
3102 function update_user_login_times() {
3103 global $USER, $DB;
3105 if (isguestuser()) {
3106 // Do not update guest access times/ips for performance.
3107 return true;
3110 $now = time();
3112 $user = new stdClass();
3113 $user->id = $USER->id;
3115 // Make sure all users that logged in have some firstaccess.
3116 if ($USER->firstaccess == 0) {
3117 $USER->firstaccess = $user->firstaccess = $now;
3120 // Store the previous current as lastlogin.
3121 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3123 $USER->currentlogin = $user->currentlogin = $now;
3125 // Function user_accesstime_log() may not update immediately, better do it here.
3126 $USER->lastaccess = $user->lastaccess = $now;
3127 $USER->lastip = $user->lastip = getremoteaddr();
3129 // Note: do not call user_update_user() here because this is part of the login process,
3130 // the login event means that these fields were updated.
3131 $DB->update_record('user', $user);
3132 return true;
3136 * Determines if a user has completed setting up their account.
3138 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3139 * @return bool
3141 function user_not_fully_set_up($user) {
3142 if (isguestuser($user)) {
3143 return false;
3145 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3149 * Check whether the user has exceeded the bounce threshold
3151 * @param stdClass $user A {@link $USER} object
3152 * @return bool true => User has exceeded bounce threshold
3154 function over_bounce_threshold($user) {
3155 global $CFG, $DB;
3157 if (empty($CFG->handlebounces)) {
3158 return false;
3161 if (empty($user->id)) {
3162 // No real (DB) user, nothing to do here.
3163 return false;
3166 // Set sensible defaults.
3167 if (empty($CFG->minbounces)) {
3168 $CFG->minbounces = 10;
3170 if (empty($CFG->bounceratio)) {
3171 $CFG->bounceratio = .20;
3173 $bouncecount = 0;
3174 $sendcount = 0;
3175 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3176 $bouncecount = $bounce->value;
3178 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3179 $sendcount = $send->value;
3181 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3185 * Used to increment or reset email sent count
3187 * @param stdClass $user object containing an id
3188 * @param bool $reset will reset the count to 0
3189 * @return void
3191 function set_send_count($user, $reset=false) {
3192 global $DB;
3194 if (empty($user->id)) {
3195 // No real (DB) user, nothing to do here.
3196 return;
3199 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3200 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3201 $DB->update_record('user_preferences', $pref);
3202 } else if (!empty($reset)) {
3203 // If it's not there and we're resetting, don't bother. Make a new one.
3204 $pref = new stdClass();
3205 $pref->name = 'email_send_count';
3206 $pref->value = 1;
3207 $pref->userid = $user->id;
3208 $DB->insert_record('user_preferences', $pref, false);
3213 * Increment or reset user's email bounce count
3215 * @param stdClass $user object containing an id
3216 * @param bool $reset will reset the count to 0
3218 function set_bounce_count($user, $reset=false) {
3219 global $DB;
3221 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3222 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3223 $DB->update_record('user_preferences', $pref);
3224 } else if (!empty($reset)) {
3225 // If it's not there and we're resetting, don't bother. Make a new one.
3226 $pref = new stdClass();
3227 $pref->name = 'email_bounce_count';
3228 $pref->value = 1;
3229 $pref->userid = $user->id;
3230 $DB->insert_record('user_preferences', $pref, false);
3235 * Determines if the logged in user is currently moving an activity
3237 * @param int $courseid The id of the course being tested
3238 * @return bool
3240 function ismoving($courseid) {
3241 global $USER;
3243 if (!empty($USER->activitycopy)) {
3244 return ($USER->activitycopycourse == $courseid);
3246 return false;
3250 * Returns a persons full name
3252 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3253 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3254 * specify one.
3256 * @param stdClass $user A {@link $USER} object to get full name of.
3257 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3258 * @return string
3260 function fullname($user, $override=false) {
3261 global $CFG, $SESSION;
3263 if (!isset($user->firstname) and !isset($user->lastname)) {
3264 return '';
3267 // Get all of the name fields.
3268 $allnames = get_all_user_name_fields();
3269 if ($CFG->debugdeveloper) {
3270 foreach ($allnames as $allname) {
3271 if (!array_key_exists($allname, $user)) {
3272 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3273 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3274 // Message has been sent, no point in sending the message multiple times.
3275 break;
3280 if (!$override) {
3281 if (!empty($CFG->forcefirstname)) {
3282 $user->firstname = $CFG->forcefirstname;
3284 if (!empty($CFG->forcelastname)) {
3285 $user->lastname = $CFG->forcelastname;
3289 if (!empty($SESSION->fullnamedisplay)) {
3290 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3293 $template = null;
3294 // If the fullnamedisplay setting is available, set the template to that.
3295 if (isset($CFG->fullnamedisplay)) {
3296 $template = $CFG->fullnamedisplay;
3298 // If the template is empty, or set to language, return the language string.
3299 if ((empty($template) || $template == 'language') && !$override) {
3300 return get_string('fullnamedisplay', null, $user);
3303 // Check to see if we are displaying according to the alternative full name format.
3304 if ($override) {
3305 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3306 // Default to show just the user names according to the fullnamedisplay string.
3307 return get_string('fullnamedisplay', null, $user);
3308 } else {
3309 // If the override is true, then change the template to use the complete name.
3310 $template = $CFG->alternativefullnameformat;
3314 $requirednames = array();
3315 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3316 foreach ($allnames as $allname) {
3317 if (strpos($template, $allname) !== false) {
3318 $requirednames[] = $allname;
3322 $displayname = $template;
3323 // Switch in the actual data into the template.
3324 foreach ($requirednames as $altname) {
3325 if (isset($user->$altname)) {
3326 // Using empty() on the below if statement causes breakages.
3327 if ((string)$user->$altname == '') {
3328 $displayname = str_replace($altname, 'EMPTY', $displayname);
3329 } else {
3330 $displayname = str_replace($altname, $user->$altname, $displayname);
3332 } else {
3333 $displayname = str_replace($altname, 'EMPTY', $displayname);
3336 // Tidy up any misc. characters (Not perfect, but gets most characters).
3337 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3338 // katakana and parenthesis.
3339 $patterns = array();
3340 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3341 // filled in by a user.
3342 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3343 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3344 // This regular expression is to remove any double spaces in the display name.
3345 $patterns[] = '/\s{2,}/u';
3346 foreach ($patterns as $pattern) {
3347 $displayname = preg_replace($pattern, ' ', $displayname);
3350 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3351 $displayname = trim($displayname);
3352 if (empty($displayname)) {
3353 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3354 // people in general feel is a good setting to fall back on.
3355 $displayname = $user->firstname;
3357 return $displayname;
3361 * A centralised location for the all name fields. Returns an array / sql string snippet.
3363 * @param bool $returnsql True for an sql select field snippet.
3364 * @param string $tableprefix table query prefix to use in front of each field.
3365 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3366 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3367 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3368 * @return array|string All name fields.
3370 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3371 // This array is provided in this order because when called by fullname() (above) if firstname is before
3372 // firstnamephonetic str_replace() will change the wrong placeholder.
3373 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3374 'lastnamephonetic' => 'lastnamephonetic',
3375 'middlename' => 'middlename',
3376 'alternatename' => 'alternatename',
3377 'firstname' => 'firstname',
3378 'lastname' => 'lastname');
3380 // Let's add a prefix to the array of user name fields if provided.
3381 if ($prefix) {
3382 foreach ($alternatenames as $key => $altname) {
3383 $alternatenames[$key] = $prefix . $altname;
3387 // If we want the end result to have firstname and lastname at the front / top of the result.
3388 if ($order) {
3389 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3390 for ($i = 0; $i < 2; $i++) {
3391 // Get the last element.
3392 $lastelement = end($alternatenames);
3393 // Remove it from the array.
3394 unset($alternatenames[$lastelement]);
3395 // Put the element back on the top of the array.
3396 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3400 // Create an sql field snippet if requested.
3401 if ($returnsql) {
3402 if ($tableprefix) {
3403 if ($fieldprefix) {
3404 foreach ($alternatenames as $key => $altname) {
3405 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3407 } else {
3408 foreach ($alternatenames as $key => $altname) {
3409 $alternatenames[$key] = $tableprefix . '.' . $altname;
3413 $alternatenames = implode(',', $alternatenames);
3415 return $alternatenames;
3419 * Reduces lines of duplicated code for getting user name fields.
3421 * See also {@link user_picture::unalias()}
3423 * @param object $addtoobject Object to add user name fields to.
3424 * @param object $secondobject Object that contains user name field information.
3425 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3426 * @param array $additionalfields Additional fields to be matched with data in the second object.
3427 * The key can be set to the user table field name.
3428 * @return object User name fields.
3430 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3431 $fields = get_all_user_name_fields(false, null, $prefix);
3432 if ($additionalfields) {
3433 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3434 // the key is a number and then sets the key to the array value.
3435 foreach ($additionalfields as $key => $value) {
3436 if (is_numeric($key)) {
3437 $additionalfields[$value] = $prefix . $value;
3438 unset($additionalfields[$key]);
3439 } else {
3440 $additionalfields[$key] = $prefix . $value;
3443 $fields = array_merge($fields, $additionalfields);
3445 foreach ($fields as $key => $field) {
3446 // Important that we have all of the user name fields present in the object that we are sending back.
3447 $addtoobject->$key = '';
3448 if (isset($secondobject->$field)) {
3449 $addtoobject->$key = $secondobject->$field;
3452 return $addtoobject;
3456 * Returns an array of values in order of occurance in a provided string.
3457 * The key in the result is the character postion in the string.
3459 * @param array $values Values to be found in the string format
3460 * @param string $stringformat The string which may contain values being searched for.
3461 * @return array An array of values in order according to placement in the string format.
3463 function order_in_string($values, $stringformat) {
3464 $valuearray = array();
3465 foreach ($values as $value) {
3466 $pattern = "/$value\b/";
3467 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3468 if (preg_match($pattern, $stringformat)) {
3469 $replacement = "thing";
3470 // Replace the value with something more unique to ensure we get the right position when using strpos().
3471 $newformat = preg_replace($pattern, $replacement, $stringformat);
3472 $position = strpos($newformat, $replacement);
3473 $valuearray[$position] = $value;
3476 ksort($valuearray);
3477 return $valuearray;
3481 * Checks if current user is shown any extra fields when listing users.
3483 * @param object $context Context
3484 * @param array $already Array of fields that we're going to show anyway
3485 * so don't bother listing them
3486 * @return array Array of field names from user table, not including anything
3487 * listed in $already
3489 function get_extra_user_fields($context, $already = array()) {
3490 global $CFG;
3492 // Only users with permission get the extra fields.
3493 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3494 return array();
3497 // Split showuseridentity on comma.
3498 if (empty($CFG->showuseridentity)) {
3499 // Explode gives wrong result with empty string.
3500 $extra = array();
3501 } else {
3502 $extra = explode(',', $CFG->showuseridentity);
3504 $renumber = false;
3505 foreach ($extra as $key => $field) {
3506 if (in_array($field, $already)) {
3507 unset($extra[$key]);
3508 $renumber = true;
3511 if ($renumber) {
3512 // For consistency, if entries are removed from array, renumber it
3513 // so they are numbered as you would expect.
3514 $extra = array_merge($extra);
3516 return $extra;
3520 * If the current user is to be shown extra user fields when listing or
3521 * selecting users, returns a string suitable for including in an SQL select
3522 * clause to retrieve those fields.
3524 * @param context $context Context
3525 * @param string $alias Alias of user table, e.g. 'u' (default none)
3526 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3527 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3528 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3530 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3531 $fields = get_extra_user_fields($context, $already);
3532 $result = '';
3533 // Add punctuation for alias.
3534 if ($alias !== '') {
3535 $alias .= '.';
3537 foreach ($fields as $field) {
3538 $result .= ', ' . $alias . $field;
3539 if ($prefix) {
3540 $result .= ' AS ' . $prefix . $field;
3543 return $result;
3547 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3548 * @param string $field Field name, e.g. 'phone1'
3549 * @return string Text description taken from language file, e.g. 'Phone number'
3551 function get_user_field_name($field) {
3552 // Some fields have language strings which are not the same as field name.
3553 switch ($field) {
3554 case 'phone1' : {
3555 return get_string('phone');
3557 case 'url' : {
3558 return get_string('webpage');
3560 case 'icq' : {
3561 return get_string('icqnumber');
3563 case 'skype' : {
3564 return get_string('skypeid');
3566 case 'aim' : {
3567 return get_string('aimid');
3569 case 'yahoo' : {
3570 return get_string('yahooid');
3572 case 'msn' : {
3573 return get_string('msnid');
3576 // Otherwise just use the same lang string.
3577 return get_string($field);
3581 * Returns whether a given authentication plugin exists.
3583 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3584 * @return boolean Whether the plugin is available.
3586 function exists_auth_plugin($auth) {
3587 global $CFG;
3589 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3590 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3592 return false;
3596 * Checks if a given plugin is in the list of enabled authentication plugins.
3598 * @param string $auth Authentication plugin.
3599 * @return boolean Whether the plugin is enabled.
3601 function is_enabled_auth($auth) {
3602 if (empty($auth)) {
3603 return false;
3606 $enabled = get_enabled_auth_plugins();
3608 return in_array($auth, $enabled);
3612 * Returns an authentication plugin instance.
3614 * @param string $auth name of authentication plugin
3615 * @return auth_plugin_base An instance of the required authentication plugin.
3617 function get_auth_plugin($auth) {
3618 global $CFG;
3620 // Check the plugin exists first.
3621 if (! exists_auth_plugin($auth)) {
3622 print_error('authpluginnotfound', 'debug', '', $auth);
3625 // Return auth plugin instance.
3626 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3627 $class = "auth_plugin_$auth";
3628 return new $class;
3632 * Returns array of active auth plugins.
3634 * @param bool $fix fix $CFG->auth if needed
3635 * @return array
3637 function get_enabled_auth_plugins($fix=false) {
3638 global $CFG;
3640 $default = array('manual', 'nologin');
3642 if (empty($CFG->auth)) {
3643 $auths = array();
3644 } else {
3645 $auths = explode(',', $CFG->auth);
3648 if ($fix) {
3649 $auths = array_unique($auths);
3650 foreach ($auths as $k => $authname) {
3651 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3652 unset($auths[$k]);
3655 $newconfig = implode(',', $auths);
3656 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3657 set_config('auth', $newconfig);
3661 return (array_merge($default, $auths));
3665 * Returns true if an internal authentication method is being used.
3666 * if method not specified then, global default is assumed
3668 * @param string $auth Form of authentication required
3669 * @return bool
3671 function is_internal_auth($auth) {
3672 // Throws error if bad $auth.
3673 $authplugin = get_auth_plugin($auth);
3674 return $authplugin->is_internal();
3678 * Returns true if the user is a 'restored' one.
3680 * Used in the login process to inform the user and allow him/her to reset the password
3682 * @param string $username username to be checked
3683 * @return bool
3685 function is_restored_user($username) {
3686 global $CFG, $DB;
3688 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3692 * Returns an array of user fields
3694 * @return array User field/column names
3696 function get_user_fieldnames() {
3697 global $DB;
3699 $fieldarray = $DB->get_columns('user');
3700 unset($fieldarray['id']);
3701 $fieldarray = array_keys($fieldarray);
3703 return $fieldarray;
3707 * Creates a bare-bones user record
3709 * @todo Outline auth types and provide code example
3711 * @param string $username New user's username to add to record
3712 * @param string $password New user's password to add to record
3713 * @param string $auth Form of authentication required
3714 * @return stdClass A complete user object
3716 function create_user_record($username, $password, $auth = 'manual') {
3717 global $CFG, $DB;
3718 require_once($CFG->dirroot.'/user/profile/lib.php');
3719 require_once($CFG->dirroot.'/user/lib.php');
3721 // Just in case check text case.
3722 $username = trim(core_text::strtolower($username));
3724 $authplugin = get_auth_plugin($auth);
3725 $customfields = $authplugin->get_custom_user_profile_fields();
3726 $newuser = new stdClass();
3727 if ($newinfo = $authplugin->get_userinfo($username)) {
3728 $newinfo = truncate_userinfo($newinfo);
3729 foreach ($newinfo as $key => $value) {
3730 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3731 $newuser->$key = $value;
3736 if (!empty($newuser->email)) {
3737 if (email_is_not_allowed($newuser->email)) {
3738 unset($newuser->email);
3742 if (!isset($newuser->city)) {
3743 $newuser->city = '';
3746 $newuser->auth = $auth;
3747 $newuser->username = $username;
3749 // Fix for MDL-8480
3750 // user CFG lang for user if $newuser->lang is empty
3751 // or $user->lang is not an installed language.
3752 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3753 $newuser->lang = $CFG->lang;
3755 $newuser->confirmed = 1;
3756 $newuser->lastip = getremoteaddr();
3757 $newuser->timecreated = time();
3758 $newuser->timemodified = $newuser->timecreated;
3759 $newuser->mnethostid = $CFG->mnet_localhost_id;
3761 $newuser->id = user_create_user($newuser, false, false);
3763 // Save user profile data.
3764 profile_save_data($newuser);
3766 $user = get_complete_user_data('id', $newuser->id);
3767 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3768 set_user_preference('auth_forcepasswordchange', 1, $user);
3770 // Set the password.
3771 update_internal_user_password($user, $password);
3773 // Trigger event.
3774 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3776 return $user;
3780 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3782 * @param string $username user's username to update the record
3783 * @return stdClass A complete user object
3785 function update_user_record($username) {
3786 global $DB, $CFG;
3787 // Just in case check text case.
3788 $username = trim(core_text::strtolower($username));
3790 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3791 return update_user_record_by_id($oldinfo->id);
3795 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3797 * @param int $id user id
3798 * @return stdClass A complete user object
3800 function update_user_record_by_id($id) {
3801 global $DB, $CFG;
3802 require_once($CFG->dirroot."/user/profile/lib.php");
3803 require_once($CFG->dirroot.'/user/lib.php');
3805 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3806 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3808 $newuser = array();
3809 $userauth = get_auth_plugin($oldinfo->auth);
3811 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3812 $newinfo = truncate_userinfo($newinfo);
3813 $customfields = $userauth->get_custom_user_profile_fields();
3815 foreach ($newinfo as $key => $value) {
3816 $iscustom = in_array($key, $customfields);
3817 if (!$iscustom) {
3818 $key = strtolower($key);
3820 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3821 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3822 // Unknown or must not be changed.
3823 continue;
3825 $confval = $userauth->config->{'field_updatelocal_' . $key};
3826 $lockval = $userauth->config->{'field_lock_' . $key};
3827 if (empty($confval) || empty($lockval)) {
3828 continue;
3830 if ($confval === 'onlogin') {
3831 // MDL-4207 Don't overwrite modified user profile values with
3832 // empty LDAP values when 'unlocked if empty' is set. The purpose
3833 // of the setting 'unlocked if empty' is to allow the user to fill
3834 // in a value for the selected field _if LDAP is giving
3835 // nothing_ for this field. Thus it makes sense to let this value
3836 // stand in until LDAP is giving a value for this field.
3837 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3838 if ($iscustom || (in_array($key, $userauth->userfields) &&
3839 ((string)$oldinfo->$key !== (string)$value))) {
3840 $newuser[$key] = (string)$value;
3845 if ($newuser) {
3846 $newuser['id'] = $oldinfo->id;
3847 $newuser['timemodified'] = time();
3848 user_update_user((object) $newuser, false, false);
3850 // Save user profile data.
3851 profile_save_data((object) $newuser);
3853 // Trigger event.
3854 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
3858 return get_complete_user_data('id', $oldinfo->id);
3862 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
3864 * @param array $info Array of user properties to truncate if needed
3865 * @return array The now truncated information that was passed in
3867 function truncate_userinfo(array $info) {
3868 // Define the limits.
3869 $limit = array(
3870 'username' => 100,
3871 'idnumber' => 255,
3872 'firstname' => 100,
3873 'lastname' => 100,
3874 'email' => 100,
3875 'icq' => 15,
3876 'phone1' => 20,
3877 'phone2' => 20,
3878 'institution' => 255,
3879 'department' => 255,
3880 'address' => 255,
3881 'city' => 120,
3882 'country' => 2,
3883 'url' => 255,
3886 // Apply where needed.
3887 foreach (array_keys($info) as $key) {
3888 if (!empty($limit[$key])) {
3889 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
3893 return $info;
3897 * Marks user deleted in internal user database and notifies the auth plugin.
3898 * Also unenrols user from all roles and does other cleanup.
3900 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3902 * @param stdClass $user full user object before delete
3903 * @return boolean success
3904 * @throws coding_exception if invalid $user parameter detected
3906 function delete_user(stdClass $user) {
3907 global $CFG, $DB;
3908 require_once($CFG->libdir.'/grouplib.php');
3909 require_once($CFG->libdir.'/gradelib.php');
3910 require_once($CFG->dirroot.'/message/lib.php');
3911 require_once($CFG->dirroot.'/tag/lib.php');
3912 require_once($CFG->dirroot.'/user/lib.php');
3914 // Make sure nobody sends bogus record type as parameter.
3915 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
3916 throw new coding_exception('Invalid $user parameter in delete_user() detected');
3919 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
3920 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
3921 debugging('Attempt to delete unknown user account.');
3922 return false;
3925 // There must be always exactly one guest record, originally the guest account was identified by username only,
3926 // now we use $CFG->siteguest for performance reasons.
3927 if ($user->username === 'guest' or isguestuser($user)) {
3928 debugging('Guest user account can not be deleted.');
3929 return false;
3932 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
3933 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
3934 if ($user->auth === 'manual' and is_siteadmin($user)) {
3935 debugging('Local administrator accounts can not be deleted.');
3936 return false;
3939 // Keep user record before updating it, as we have to pass this to user_deleted event.
3940 $olduser = clone $user;
3942 // Keep a copy of user context, we need it for event.
3943 $usercontext = context_user::instance($user->id);
3945 // Delete all grades - backup is kept in grade_grades_history table.
3946 grade_user_delete($user->id);
3948 // Move unread messages from this user to read.
3949 message_move_userfrom_unread2read($user->id);
3951 // TODO: remove from cohorts using standard API here.
3953 // Remove user tags.
3954 tag_set('user', $user->id, array(), 'core', $usercontext->id);
3956 // Unconditionally unenrol from all courses.
3957 enrol_user_delete($user);
3959 // Unenrol from all roles in all contexts.
3960 // This might be slow but it is really needed - modules might do some extra cleanup!
3961 role_unassign_all(array('userid' => $user->id));
3963 // Now do a brute force cleanup.
3965 // Remove from all cohorts.
3966 $DB->delete_records('cohort_members', array('userid' => $user->id));
3968 // Remove from all groups.
3969 $DB->delete_records('groups_members', array('userid' => $user->id));
3971 // Brute force unenrol from all courses.
3972 $DB->delete_records('user_enrolments', array('userid' => $user->id));
3974 // Purge user preferences.
3975 $DB->delete_records('user_preferences', array('userid' => $user->id));
3977 // Purge user extra profile info.
3978 $DB->delete_records('user_info_data', array('userid' => $user->id));
3980 // Purge log of previous password hashes.
3981 $DB->delete_records('user_password_history', array('userid' => $user->id));
3983 // Last course access not necessary either.
3984 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
3985 // Remove all user tokens.
3986 $DB->delete_records('external_tokens', array('userid' => $user->id));
3988 // Unauthorise the user for all services.
3989 $DB->delete_records('external_services_users', array('userid' => $user->id));
3991 // Remove users private keys.
3992 $DB->delete_records('user_private_key', array('userid' => $user->id));
3994 // Remove users customised pages.
3995 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
3997 // Force logout - may fail if file based sessions used, sorry.
3998 \core\session\manager::kill_user_sessions($user->id);
4000 // Generate username from email address, or a fake email.
4001 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4002 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4004 // Workaround for bulk deletes of users with the same email address.
4005 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4006 $delname++;
4009 // Mark internal user record as "deleted".
4010 $updateuser = new stdClass();
4011 $updateuser->id = $user->id;
4012 $updateuser->deleted = 1;
4013 $updateuser->username = $delname; // Remember it just in case.
4014 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4015 $updateuser->idnumber = ''; // Clear this field to free it up.
4016 $updateuser->picture = 0;
4017 $updateuser->timemodified = time();
4019 // Don't trigger update event, as user is being deleted.
4020 user_update_user($updateuser, false, false);
4022 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4023 context_helper::delete_instance(CONTEXT_USER, $user->id);
4025 // Any plugin that needs to cleanup should register this event.
4026 // Trigger event.
4027 $event = \core\event\user_deleted::create(
4028 array(
4029 'objectid' => $user->id,
4030 'relateduserid' => $user->id,
4031 'context' => $usercontext,
4032 'other' => array(
4033 'username' => $user->username,
4034 'email' => $user->email,
4035 'idnumber' => $user->idnumber,
4036 'picture' => $user->picture,
4037 'mnethostid' => $user->mnethostid
4041 $event->add_record_snapshot('user', $olduser);
4042 $event->trigger();
4044 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4045 // should know about this updated property persisted to the user's table.
4046 $user->timemodified = $updateuser->timemodified;
4048 // Notify auth plugin - do not block the delete even when plugin fails.
4049 $authplugin = get_auth_plugin($user->auth);
4050 $authplugin->user_delete($user);
4052 return true;
4056 * Retrieve the guest user object.
4058 * @return stdClass A {@link $USER} object
4060 function guest_user() {
4061 global $CFG, $DB;
4063 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4064 $newuser->confirmed = 1;
4065 $newuser->lang = $CFG->lang;
4066 $newuser->lastip = getremoteaddr();
4069 return $newuser;
4073 * Authenticates a user against the chosen authentication mechanism
4075 * Given a username and password, this function looks them
4076 * up using the currently selected authentication mechanism,
4077 * and if the authentication is successful, it returns a
4078 * valid $user object from the 'user' table.
4080 * Uses auth_ functions from the currently active auth module
4082 * After authenticate_user_login() returns success, you will need to
4083 * log that the user has logged in, and call complete_user_login() to set
4084 * the session up.
4086 * Note: this function works only with non-mnet accounts!
4088 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4089 * @param string $password User's password
4090 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4091 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4092 * @return stdClass|false A {@link $USER} object or false if error
4094 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4095 global $CFG, $DB;
4096 require_once("$CFG->libdir/authlib.php");
4098 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4099 // we have found the user
4101 } else if (!empty($CFG->authloginviaemail)) {
4102 if ($email = clean_param($username, PARAM_EMAIL)) {
4103 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4104 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4105 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4106 if (count($users) === 1) {
4107 // Use email for login only if unique.
4108 $user = reset($users);
4109 $user = get_complete_user_data('id', $user->id);
4110 $username = $user->username;
4112 unset($users);
4116 $authsenabled = get_enabled_auth_plugins();
4118 if ($user) {
4119 // Use manual if auth not set.
4120 $auth = empty($user->auth) ? 'manual' : $user->auth;
4121 if (!empty($user->suspended)) {
4122 $failurereason = AUTH_LOGIN_SUSPENDED;
4124 // Trigger login failed event.
4125 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4126 'other' => array('username' => $username, 'reason' => $failurereason)));
4127 $event->trigger();
4128 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4129 return false;
4131 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4132 // Legacy way to suspend user.
4133 $failurereason = AUTH_LOGIN_SUSPENDED;
4135 // Trigger login failed event.
4136 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4137 'other' => array('username' => $username, 'reason' => $failurereason)));
4138 $event->trigger();
4139 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4140 return false;
4142 $auths = array($auth);
4144 } else {
4145 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4146 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4147 $failurereason = AUTH_LOGIN_NOUSER;
4149 // Trigger login failed event.
4150 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4151 'reason' => $failurereason)));
4152 $event->trigger();
4153 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4154 return false;
4157 // User does not exist.
4158 $auths = $authsenabled;
4159 $user = new stdClass();
4160 $user->id = 0;
4163 if ($ignorelockout) {
4164 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4165 // or this function is called from a SSO script.
4166 } else if ($user->id) {
4167 // Verify login lockout after other ways that may prevent user login.
4168 if (login_is_lockedout($user)) {
4169 $failurereason = AUTH_LOGIN_LOCKOUT;
4171 // Trigger login failed event.
4172 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4173 'other' => array('username' => $username, 'reason' => $failurereason)));
4174 $event->trigger();
4176 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4177 return false;
4179 } else {
4180 // We can not lockout non-existing accounts.
4183 foreach ($auths as $auth) {
4184 $authplugin = get_auth_plugin($auth);
4186 // On auth fail fall through to the next plugin.
4187 if (!$authplugin->user_login($username, $password)) {
4188 continue;
4191 // Successful authentication.
4192 if ($user->id) {
4193 // User already exists in database.
4194 if (empty($user->auth)) {
4195 // For some reason auth isn't set yet.
4196 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4197 $user->auth = $auth;
4200 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4201 // the current hash algorithm while we have access to the user's password.
4202 update_internal_user_password($user, $password);
4204 if ($authplugin->is_synchronised_with_external()) {
4205 // Update user record from external DB.
4206 $user = update_user_record_by_id($user->id);
4208 } else {
4209 // The user is authenticated but user creation may be disabled.
4210 if (!empty($CFG->authpreventaccountcreation)) {
4211 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4213 // Trigger login failed event.
4214 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4215 'reason' => $failurereason)));
4216 $event->trigger();
4218 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4219 $_SERVER['HTTP_USER_AGENT']);
4220 return false;
4221 } else {
4222 $user = create_user_record($username, $password, $auth);
4226 $authplugin->sync_roles($user);
4228 foreach ($authsenabled as $hau) {
4229 $hauth = get_auth_plugin($hau);
4230 $hauth->user_authenticated_hook($user, $username, $password);
4233 if (empty($user->id)) {
4234 $failurereason = AUTH_LOGIN_NOUSER;
4235 // Trigger login failed event.
4236 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4237 'reason' => $failurereason)));
4238 $event->trigger();
4239 return false;
4242 if (!empty($user->suspended)) {
4243 // Just in case some auth plugin suspended account.
4244 $failurereason = AUTH_LOGIN_SUSPENDED;
4245 // Trigger login failed event.
4246 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4247 'other' => array('username' => $username, 'reason' => $failurereason)));
4248 $event->trigger();
4249 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4250 return false;
4253 login_attempt_valid($user);
4254 $failurereason = AUTH_LOGIN_OK;
4255 return $user;
4258 // Failed if all the plugins have failed.
4259 if (debugging('', DEBUG_ALL)) {
4260 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4263 if ($user->id) {
4264 login_attempt_failed($user);
4265 $failurereason = AUTH_LOGIN_FAILED;
4266 // Trigger login failed event.
4267 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4268 'other' => array('username' => $username, 'reason' => $failurereason)));
4269 $event->trigger();
4270 } else {
4271 $failurereason = AUTH_LOGIN_NOUSER;
4272 // Trigger login failed event.
4273 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4274 'reason' => $failurereason)));
4275 $event->trigger();
4278 return false;
4282 * Call to complete the user login process after authenticate_user_login()
4283 * has succeeded. It will setup the $USER variable and other required bits
4284 * and pieces.
4286 * NOTE:
4287 * - It will NOT log anything -- up to the caller to decide what to log.
4288 * - this function does not set any cookies any more!
4290 * @param stdClass $user
4291 * @return stdClass A {@link $USER} object - BC only, do not use
4293 function complete_user_login($user) {
4294 global $CFG, $USER;
4296 \core\session\manager::login_user($user);
4298 // Reload preferences from DB.
4299 unset($USER->preference);
4300 check_user_preferences_loaded($USER);
4302 // Update login times.
4303 update_user_login_times();
4305 // Extra session prefs init.
4306 set_login_session_preferences();
4308 // Trigger login event.
4309 $event = \core\event\user_loggedin::create(
4310 array(
4311 'userid' => $USER->id,
4312 'objectid' => $USER->id,
4313 'other' => array('username' => $USER->username),
4316 $event->trigger();
4318 if (isguestuser()) {
4319 // No need to continue when user is THE guest.
4320 return $USER;
4323 if (CLI_SCRIPT) {
4324 // We can redirect to password change URL only in browser.
4325 return $USER;
4328 // Select password change url.
4329 $userauth = get_auth_plugin($USER->auth);
4331 // Check whether the user should be changing password.
4332 if (get_user_preferences('auth_forcepasswordchange', false)) {
4333 if ($userauth->can_change_password()) {
4334 if ($changeurl = $userauth->change_password_url()) {
4335 redirect($changeurl);
4336 } else {
4337 redirect($CFG->httpswwwroot.'/login/change_password.php');
4339 } else {
4340 print_error('nopasswordchangeforced', 'auth');
4343 return $USER;
4347 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4349 * @param string $password String to check.
4350 * @return boolean True if the $password matches the format of an md5 sum.
4352 function password_is_legacy_hash($password) {
4353 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4357 * Compare password against hash stored in user object to determine if it is valid.
4359 * If necessary it also updates the stored hash to the current format.
4361 * @param stdClass $user (Password property may be updated).
4362 * @param string $password Plain text password.
4363 * @return bool True if password is valid.
4365 function validate_internal_user_password($user, $password) {
4366 global $CFG;
4367 require_once($CFG->libdir.'/password_compat/lib/password.php');
4369 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4370 // Internal password is not used at all, it can not validate.
4371 return false;
4374 // If hash isn't a legacy (md5) hash, validate using the library function.
4375 if (!password_is_legacy_hash($user->password)) {
4376 return password_verify($password, $user->password);
4379 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4380 // is valid we can then update it to the new algorithm.
4382 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4383 $validated = false;
4385 if ($user->password === md5($password.$sitesalt)
4386 or $user->password === md5($password)
4387 or $user->password === md5(addslashes($password).$sitesalt)
4388 or $user->password === md5(addslashes($password))) {
4389 // Note: we are intentionally using the addslashes() here because we
4390 // need to accept old password hashes of passwords with magic quotes.
4391 $validated = true;
4393 } else {
4394 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4395 $alt = 'passwordsaltalt'.$i;
4396 if (!empty($CFG->$alt)) {
4397 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4398 $validated = true;
4399 break;
4405 if ($validated) {
4406 // If the password matches the existing md5 hash, update to the
4407 // current hash algorithm while we have access to the user's password.
4408 update_internal_user_password($user, $password);
4411 return $validated;
4415 * Calculate hash for a plain text password.
4417 * @param string $password Plain text password to be hashed.
4418 * @param bool $fasthash If true, use a low cost factor when generating the hash
4419 * This is much faster to generate but makes the hash
4420 * less secure. It is used when lots of hashes need to
4421 * be generated quickly.
4422 * @return string The hashed password.
4424 * @throws moodle_exception If a problem occurs while generating the hash.
4426 function hash_internal_user_password($password, $fasthash = false) {
4427 global $CFG;
4428 require_once($CFG->libdir.'/password_compat/lib/password.php');
4430 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4431 $options = ($fasthash) ? array('cost' => 4) : array();
4433 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4435 if ($generatedhash === false || $generatedhash === null) {
4436 throw new moodle_exception('Failed to generate password hash.');
4439 return $generatedhash;
4443 * Update password hash in user object (if necessary).
4445 * The password is updated if:
4446 * 1. The password has changed (the hash of $user->password is different
4447 * to the hash of $password).
4448 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4449 * md5 algorithm).
4451 * Updating the password will modify the $user object and the database
4452 * record to use the current hashing algorithm.
4454 * @param stdClass $user User object (password property may be updated).
4455 * @param string $password Plain text password.
4456 * @param bool $fasthash If true, use a low cost factor when generating the hash
4457 * This is much faster to generate but makes the hash
4458 * less secure. It is used when lots of hashes need to
4459 * be generated quickly.
4460 * @return bool Always returns true.
4462 function update_internal_user_password($user, $password, $fasthash = false) {
4463 global $CFG, $DB;
4464 require_once($CFG->libdir.'/password_compat/lib/password.php');
4466 // Figure out what the hashed password should be.
4467 if (!isset($user->auth)) {
4468 debugging('User record in update_internal_user_password() must include field auth',
4469 DEBUG_DEVELOPER);
4470 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4472 $authplugin = get_auth_plugin($user->auth);
4473 if ($authplugin->prevent_local_passwords()) {
4474 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4475 } else {
4476 $hashedpassword = hash_internal_user_password($password, $fasthash);
4479 $algorithmchanged = false;
4481 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4482 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4483 $passwordchanged = ($user->password !== $hashedpassword);
4485 } else if (isset($user->password)) {
4486 // If verification fails then it means the password has changed.
4487 $passwordchanged = !password_verify($password, $user->password);
4488 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4489 } else {
4490 // While creating new user, password in unset in $user object, to avoid
4491 // saving it with user_create()
4492 $passwordchanged = true;
4495 if ($passwordchanged || $algorithmchanged) {
4496 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4497 $user->password = $hashedpassword;
4499 // Trigger event.
4500 $user = $DB->get_record('user', array('id' => $user->id));
4501 \core\event\user_password_updated::create_from_user($user)->trigger();
4504 return true;
4508 * Get a complete user record, which includes all the info in the user record.
4510 * Intended for setting as $USER session variable
4512 * @param string $field The user field to be checked for a given value.
4513 * @param string $value The value to match for $field.
4514 * @param int $mnethostid
4515 * @return mixed False, or A {@link $USER} object.
4517 function get_complete_user_data($field, $value, $mnethostid = null) {
4518 global $CFG, $DB;
4520 if (!$field || !$value) {
4521 return false;
4524 // Build the WHERE clause for an SQL query.
4525 $params = array('fieldval' => $value);
4526 $constraints = "$field = :fieldval AND deleted <> 1";
4528 // If we are loading user data based on anything other than id,
4529 // we must also restrict our search based on mnet host.
4530 if ($field != 'id') {
4531 if (empty($mnethostid)) {
4532 // If empty, we restrict to local users.
4533 $mnethostid = $CFG->mnet_localhost_id;
4536 if (!empty($mnethostid)) {
4537 $params['mnethostid'] = $mnethostid;
4538 $constraints .= " AND mnethostid = :mnethostid";
4541 // Get all the basic user data.
4542 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4543 return false;
4546 // Get various settings and preferences.
4548 // Preload preference cache.
4549 check_user_preferences_loaded($user);
4551 // Load course enrolment related stuff.
4552 $user->lastcourseaccess = array(); // During last session.
4553 $user->currentcourseaccess = array(); // During current session.
4554 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4555 foreach ($lastaccesses as $lastaccess) {
4556 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4560 $sql = "SELECT g.id, g.courseid
4561 FROM {groups} g, {groups_members} gm
4562 WHERE gm.groupid=g.id AND gm.userid=?";
4564 // This is a special hack to speedup calendar display.
4565 $user->groupmember = array();
4566 if (!isguestuser($user)) {
4567 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4568 foreach ($groups as $group) {
4569 if (!array_key_exists($group->courseid, $user->groupmember)) {
4570 $user->groupmember[$group->courseid] = array();
4572 $user->groupmember[$group->courseid][$group->id] = $group->id;
4577 // Add the custom profile fields to the user record.
4578 $user->profile = array();
4579 if (!isguestuser($user)) {
4580 require_once($CFG->dirroot.'/user/profile/lib.php');
4581 profile_load_custom_fields($user);
4584 // Rewrite some variables if necessary.
4585 if (!empty($user->description)) {
4586 // No need to cart all of it around.
4587 $user->description = true;
4589 if (isguestuser($user)) {
4590 // Guest language always same as site.
4591 $user->lang = $CFG->lang;
4592 // Name always in current language.
4593 $user->firstname = get_string('guestuser');
4594 $user->lastname = ' ';
4597 return $user;
4601 * Validate a password against the configured password policy
4603 * @param string $password the password to be checked against the password policy
4604 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4605 * @return bool true if the password is valid according to the policy. false otherwise.
4607 function check_password_policy($password, &$errmsg) {
4608 global $CFG;
4610 if (empty($CFG->passwordpolicy)) {
4611 return true;
4614 $errmsg = '';
4615 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4616 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4619 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4620 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4623 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4624 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4627 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4628 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4631 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4632 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4634 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4635 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4638 if ($errmsg == '') {
4639 return true;
4640 } else {
4641 return false;
4647 * When logging in, this function is run to set certain preferences for the current SESSION.
4649 function set_login_session_preferences() {
4650 global $SESSION;
4652 $SESSION->justloggedin = true;
4654 unset($SESSION->lang);
4655 unset($SESSION->forcelang);
4656 unset($SESSION->load_navigation_admin);
4661 * Delete a course, including all related data from the database, and any associated files.
4663 * @param mixed $courseorid The id of the course or course object to delete.
4664 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4665 * @return bool true if all the removals succeeded. false if there were any failures. If this
4666 * method returns false, some of the removals will probably have succeeded, and others
4667 * failed, but you have no way of knowing which.
4669 function delete_course($courseorid, $showfeedback = true) {
4670 global $DB;
4672 if (is_object($courseorid)) {
4673 $courseid = $courseorid->id;
4674 $course = $courseorid;
4675 } else {
4676 $courseid = $courseorid;
4677 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4678 return false;
4681 $context = context_course::instance($courseid);
4683 // Frontpage course can not be deleted!!
4684 if ($courseid == SITEID) {
4685 return false;
4688 // Make the course completely empty.
4689 remove_course_contents($courseid, $showfeedback);
4691 // Delete the course and related context instance.
4692 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4694 $DB->delete_records("course", array("id" => $courseid));
4695 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4697 // Reset all course related caches here.
4698 if (class_exists('format_base', false)) {
4699 format_base::reset_course_cache($courseid);
4702 // Trigger a course deleted event.
4703 $event = \core\event\course_deleted::create(array(
4704 'objectid' => $course->id,
4705 'context' => $context,
4706 'other' => array(
4707 'shortname' => $course->shortname,
4708 'fullname' => $course->fullname,
4709 'idnumber' => $course->idnumber
4712 $event->add_record_snapshot('course', $course);
4713 $event->trigger();
4715 return true;
4719 * Clear a course out completely, deleting all content but don't delete the course itself.
4721 * This function does not verify any permissions.
4723 * Please note this function also deletes all user enrolments,
4724 * enrolment instances and role assignments by default.
4726 * $options:
4727 * - 'keep_roles_and_enrolments' - false by default
4728 * - 'keep_groups_and_groupings' - false by default
4730 * @param int $courseid The id of the course that is being deleted
4731 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4732 * @param array $options extra options
4733 * @return bool true if all the removals succeeded. false if there were any failures. If this
4734 * method returns false, some of the removals will probably have succeeded, and others
4735 * failed, but you have no way of knowing which.
4737 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4738 global $CFG, $DB, $OUTPUT;
4740 require_once($CFG->libdir.'/badgeslib.php');
4741 require_once($CFG->libdir.'/completionlib.php');
4742 require_once($CFG->libdir.'/questionlib.php');
4743 require_once($CFG->libdir.'/gradelib.php');
4744 require_once($CFG->dirroot.'/group/lib.php');
4745 require_once($CFG->dirroot.'/tag/coursetagslib.php');
4746 require_once($CFG->dirroot.'/comment/lib.php');
4747 require_once($CFG->dirroot.'/rating/lib.php');
4748 require_once($CFG->dirroot.'/notes/lib.php');
4750 // Handle course badges.
4751 badges_handle_course_deletion($courseid);
4753 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4754 $strdeleted = get_string('deleted').' - ';
4756 // Some crazy wishlist of stuff we should skip during purging of course content.
4757 $options = (array)$options;
4759 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4760 $coursecontext = context_course::instance($courseid);
4761 $fs = get_file_storage();
4763 // Delete course completion information, this has to be done before grades and enrols.
4764 $cc = new completion_info($course);
4765 $cc->clear_criteria();
4766 if ($showfeedback) {
4767 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4770 // Remove all data from gradebook - this needs to be done before course modules
4771 // because while deleting this information, the system may need to reference
4772 // the course modules that own the grades.
4773 remove_course_grades($courseid, $showfeedback);
4774 remove_grade_letters($coursecontext, $showfeedback);
4776 // Delete course blocks in any all child contexts,
4777 // they may depend on modules so delete them first.
4778 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4779 foreach ($childcontexts as $childcontext) {
4780 blocks_delete_all_for_context($childcontext->id);
4782 unset($childcontexts);
4783 blocks_delete_all_for_context($coursecontext->id);
4784 if ($showfeedback) {
4785 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4788 // Delete every instance of every module,
4789 // this has to be done before deleting of course level stuff.
4790 $locations = core_component::get_plugin_list('mod');
4791 foreach ($locations as $modname => $moddir) {
4792 if ($modname === 'NEWMODULE') {
4793 continue;
4795 if ($module = $DB->get_record('modules', array('name' => $modname))) {
4796 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
4797 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
4798 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
4800 if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
4801 foreach ($instances as $instance) {
4802 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
4803 // Delete activity context questions and question categories.
4804 question_delete_activity($cm, $showfeedback);
4806 if (function_exists($moddelete)) {
4807 // This purges all module data in related tables, extra user prefs, settings, etc.
4808 $moddelete($instance->id);
4809 } else {
4810 // NOTE: we should not allow installation of modules with missing delete support!
4811 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4812 $DB->delete_records($modname, array('id' => $instance->id));
4815 if ($cm) {
4816 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4817 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4818 $DB->delete_records('course_modules', array('id' => $cm->id));
4822 if (function_exists($moddeletecourse)) {
4823 // Execute ptional course cleanup callback.
4824 $moddeletecourse($course, $showfeedback);
4826 if ($instances and $showfeedback) {
4827 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4829 } else {
4830 // Ooops, this module is not properly installed, force-delete it in the next block.
4834 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4836 // Remove all data from availability and completion tables that is associated
4837 // with course-modules belonging to this course. Note this is done even if the
4838 // features are not enabled now, in case they were enabled previously.
4839 $DB->delete_records_select('course_modules_completion',
4840 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4841 array($courseid));
4843 // Remove course-module data.
4844 $cms = $DB->get_records('course_modules', array('course' => $course->id));
4845 foreach ($cms as $cm) {
4846 if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
4847 try {
4848 $DB->delete_records($module->name, array('id' => $cm->instance));
4849 } catch (Exception $e) {
4850 // Ignore weird or missing table problems.
4853 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4854 $DB->delete_records('course_modules', array('id' => $cm->id));
4857 if ($showfeedback) {
4858 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
4861 // Cleanup the rest of plugins.
4862 $cleanuplugintypes = array('report', 'coursereport', 'format');
4863 foreach ($cleanuplugintypes as $type) {
4864 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
4865 foreach ($plugins as $plugin => $pluginfunction) {
4866 $pluginfunction($course->id, $showfeedback);
4868 if ($showfeedback) {
4869 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
4873 // Delete questions and question categories.
4874 question_delete_course($course, $showfeedback);
4875 if ($showfeedback) {
4876 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
4879 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
4880 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4881 foreach ($childcontexts as $childcontext) {
4882 $childcontext->delete();
4884 unset($childcontexts);
4886 // Remove all roles and enrolments by default.
4887 if (empty($options['keep_roles_and_enrolments'])) {
4888 // This hack is used in restore when deleting contents of existing course.
4889 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
4890 enrol_course_delete($course);
4891 if ($showfeedback) {
4892 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
4896 // Delete any groups, removing members and grouping/course links first.
4897 if (empty($options['keep_groups_and_groupings'])) {
4898 groups_delete_groupings($course->id, $showfeedback);
4899 groups_delete_groups($course->id, $showfeedback);
4902 // Filters be gone!
4903 filter_delete_all_for_context($coursecontext->id);
4905 // Notes, you shall not pass!
4906 note_delete_all($course->id);
4908 // Die comments!
4909 comment::delete_comments($coursecontext->id);
4911 // Ratings are history too.
4912 $delopt = new stdclass();
4913 $delopt->contextid = $coursecontext->id;
4914 $rm = new rating_manager();
4915 $rm->delete_ratings($delopt);
4917 // Delete course tags.
4918 coursetag_delete_course_tags($course->id, $showfeedback);
4920 // Delete calendar events.
4921 $DB->delete_records('event', array('courseid' => $course->id));
4922 $fs->delete_area_files($coursecontext->id, 'calendar');
4924 // Delete all related records in other core tables that may have a courseid
4925 // This array stores the tables that need to be cleared, as
4926 // table_name => column_name that contains the course id.
4927 $tablestoclear = array(
4928 'backup_courses' => 'courseid', // Scheduled backup stuff.
4929 'user_lastaccess' => 'courseid', // User access info.
4931 foreach ($tablestoclear as $table => $col) {
4932 $DB->delete_records($table, array($col => $course->id));
4935 // Delete all course backup files.
4936 $fs->delete_area_files($coursecontext->id, 'backup');
4938 // Cleanup course record - remove links to deleted stuff.
4939 $oldcourse = new stdClass();
4940 $oldcourse->id = $course->id;
4941 $oldcourse->summary = '';
4942 $oldcourse->cacherev = 0;
4943 $oldcourse->legacyfiles = 0;
4944 $oldcourse->enablecompletion = 0;
4945 if (!empty($options['keep_groups_and_groupings'])) {
4946 $oldcourse->defaultgroupingid = 0;
4948 $DB->update_record('course', $oldcourse);
4950 // Delete course sections.
4951 $DB->delete_records('course_sections', array('course' => $course->id));
4953 // Delete legacy, section and any other course files.
4954 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
4956 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
4957 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
4958 // Easy, do not delete the context itself...
4959 $coursecontext->delete_content();
4960 } else {
4961 // Hack alert!!!!
4962 // We can not drop all context stuff because it would bork enrolments and roles,
4963 // there might be also files used by enrol plugins...
4966 // Delete legacy files - just in case some files are still left there after conversion to new file api,
4967 // also some non-standard unsupported plugins may try to store something there.
4968 fulldelete($CFG->dataroot.'/'.$course->id);
4970 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
4971 $cachemodinfo = cache::make('core', 'coursemodinfo');
4972 $cachemodinfo->delete($courseid);
4974 // Trigger a course content deleted event.
4975 $event = \core\event\course_content_deleted::create(array(
4976 'objectid' => $course->id,
4977 'context' => $coursecontext,
4978 'other' => array('shortname' => $course->shortname,
4979 'fullname' => $course->fullname,
4980 'options' => $options) // Passing this for legacy reasons.
4982 $event->add_record_snapshot('course', $course);
4983 $event->trigger();
4985 return true;
4989 * Change dates in module - used from course reset.
4991 * @param string $modname forum, assignment, etc
4992 * @param array $fields array of date fields from mod table
4993 * @param int $timeshift time difference
4994 * @param int $courseid
4995 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
4996 * @return bool success
4998 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
4999 global $CFG, $DB;
5000 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5002 $return = true;
5003 $params = array($timeshift, $courseid);
5004 foreach ($fields as $field) {
5005 $updatesql = "UPDATE {".$modname."}
5006 SET $field = $field + ?
5007 WHERE course=? AND $field<>0";
5008 if ($modid) {
5009 $updatesql .= ' AND id=?';
5010 $params[] = $modid;
5012 $return = $DB->execute($updatesql, $params) && $return;
5015 $refreshfunction = $modname.'_refresh_events';
5016 if (function_exists($refreshfunction)) {
5017 $refreshfunction($courseid);
5020 return $return;
5024 * This function will empty a course of user data.
5025 * It will retain the activities and the structure of the course.
5027 * @param object $data an object containing all the settings including courseid (without magic quotes)
5028 * @return array status array of array component, item, error
5030 function reset_course_userdata($data) {
5031 global $CFG, $DB;
5032 require_once($CFG->libdir.'/gradelib.php');
5033 require_once($CFG->libdir.'/completionlib.php');
5034 require_once($CFG->dirroot.'/group/lib.php');
5036 $data->courseid = $data->id;
5037 $context = context_course::instance($data->courseid);
5039 $eventparams = array(
5040 'context' => $context,
5041 'courseid' => $data->id,
5042 'other' => array(
5043 'reset_options' => (array) $data
5046 $event = \core\event\course_reset_started::create($eventparams);
5047 $event->trigger();
5049 // Calculate the time shift of dates.
5050 if (!empty($data->reset_start_date)) {
5051 // Time part of course startdate should be zero.
5052 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5053 } else {
5054 $data->timeshift = 0;
5057 // Result array: component, item, error.
5058 $status = array();
5060 // Start the resetting.
5061 $componentstr = get_string('general');
5063 // Move the course start time.
5064 if (!empty($data->reset_start_date) and $data->timeshift) {
5065 // Change course start data.
5066 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5067 // Update all course and group events - do not move activity events.
5068 $updatesql = "UPDATE {event}
5069 SET timestart = timestart + ?
5070 WHERE courseid=? AND instance=0";
5071 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5073 // Update any date activity restrictions.
5074 if ($CFG->enableavailability) {
5075 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5078 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5081 if (!empty($data->reset_events)) {
5082 $DB->delete_records('event', array('courseid' => $data->courseid));
5083 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5086 if (!empty($data->reset_notes)) {
5087 require_once($CFG->dirroot.'/notes/lib.php');
5088 note_delete_all($data->courseid);
5089 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5092 if (!empty($data->delete_blog_associations)) {
5093 require_once($CFG->dirroot.'/blog/lib.php');
5094 blog_remove_associations_for_course($data->courseid);
5095 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5098 if (!empty($data->reset_completion)) {
5099 // Delete course and activity completion information.
5100 $course = $DB->get_record('course', array('id' => $data->courseid));
5101 $cc = new completion_info($course);
5102 $cc->delete_all_completion_data();
5103 $status[] = array('component' => $componentstr,
5104 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5107 $componentstr = get_string('roles');
5109 if (!empty($data->reset_roles_overrides)) {
5110 $children = $context->get_child_contexts();
5111 foreach ($children as $child) {
5112 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5114 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5115 // Force refresh for logged in users.
5116 $context->mark_dirty();
5117 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5120 if (!empty($data->reset_roles_local)) {
5121 $children = $context->get_child_contexts();
5122 foreach ($children as $child) {
5123 role_unassign_all(array('contextid' => $child->id));
5125 // Force refresh for logged in users.
5126 $context->mark_dirty();
5127 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5130 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5131 $data->unenrolled = array();
5132 if (!empty($data->unenrol_users)) {
5133 $plugins = enrol_get_plugins(true);
5134 $instances = enrol_get_instances($data->courseid, true);
5135 foreach ($instances as $key => $instance) {
5136 if (!isset($plugins[$instance->enrol])) {
5137 unset($instances[$key]);
5138 continue;
5142 foreach ($data->unenrol_users as $withroleid) {
5143 if ($withroleid) {
5144 $sql = "SELECT ue.*
5145 FROM {user_enrolments} ue
5146 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5147 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5148 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5149 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5151 } else {
5152 // Without any role assigned at course context.
5153 $sql = "SELECT ue.*
5154 FROM {user_enrolments} ue
5155 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5156 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5157 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5158 WHERE ra.id IS null";
5159 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5162 $rs = $DB->get_recordset_sql($sql, $params);
5163 foreach ($rs as $ue) {
5164 if (!isset($instances[$ue->enrolid])) {
5165 continue;
5167 $instance = $instances[$ue->enrolid];
5168 $plugin = $plugins[$instance->enrol];
5169 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5170 continue;
5173 $plugin->unenrol_user($instance, $ue->userid);
5174 $data->unenrolled[$ue->userid] = $ue->userid;
5176 $rs->close();
5179 if (!empty($data->unenrolled)) {
5180 $status[] = array(
5181 'component' => $componentstr,
5182 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5183 'error' => false
5187 $componentstr = get_string('groups');
5189 // Remove all group members.
5190 if (!empty($data->reset_groups_members)) {
5191 groups_delete_group_members($data->courseid);
5192 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5195 // Remove all groups.
5196 if (!empty($data->reset_groups_remove)) {
5197 groups_delete_groups($data->courseid, false);
5198 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5201 // Remove all grouping members.
5202 if (!empty($data->reset_groupings_members)) {
5203 groups_delete_groupings_groups($data->courseid, false);
5204 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5207 // Remove all groupings.
5208 if (!empty($data->reset_groupings_remove)) {
5209 groups_delete_groupings($data->courseid, false);
5210 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5213 // Look in every instance of every module for data to delete.
5214 $unsupportedmods = array();
5215 if ($allmods = $DB->get_records('modules') ) {
5216 foreach ($allmods as $mod) {
5217 $modname = $mod->name;
5218 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5219 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5220 if (file_exists($modfile)) {
5221 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5222 continue; // Skip mods with no instances.
5224 include_once($modfile);
5225 if (function_exists($moddeleteuserdata)) {
5226 $modstatus = $moddeleteuserdata($data);
5227 if (is_array($modstatus)) {
5228 $status = array_merge($status, $modstatus);
5229 } else {
5230 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5232 } else {
5233 $unsupportedmods[] = $mod;
5235 } else {
5236 debugging('Missing lib.php in '.$modname.' module!');
5241 // Mention unsupported mods.
5242 if (!empty($unsupportedmods)) {
5243 foreach ($unsupportedmods as $mod) {
5244 $status[] = array(
5245 'component' => get_string('modulenameplural', $mod->name),
5246 'item' => '',
5247 'error' => get_string('resetnotimplemented')
5252 $componentstr = get_string('gradebook', 'grades');
5253 // Reset gradebook,.
5254 if (!empty($data->reset_gradebook_items)) {
5255 remove_course_grades($data->courseid, false);
5256 grade_grab_course_grades($data->courseid);
5257 grade_regrade_final_grades($data->courseid);
5258 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5260 } else if (!empty($data->reset_gradebook_grades)) {
5261 grade_course_reset($data->courseid);
5262 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5264 // Reset comments.
5265 if (!empty($data->reset_comments)) {
5266 require_once($CFG->dirroot.'/comment/lib.php');
5267 comment::reset_course_page_comments($context);
5270 $event = \core\event\course_reset_ended::create($eventparams);
5271 $event->trigger();
5273 return $status;
5277 * Generate an email processing address.
5279 * @param int $modid
5280 * @param string $modargs
5281 * @return string Returns email processing address
5283 function generate_email_processing_address($modid, $modargs) {
5284 global $CFG;
5286 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5287 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5293 * @todo Finish documenting this function
5295 * @param string $modargs
5296 * @param string $body Currently unused
5298 function moodle_process_email($modargs, $body) {
5299 global $DB;
5301 // The first char should be an unencoded letter. We'll take this as an action.
5302 switch ($modargs{0}) {
5303 case 'B': { // Bounce.
5304 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5305 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5306 // Check the half md5 of their email.
5307 $md5check = substr(md5($user->email), 0, 16);
5308 if ($md5check == substr($modargs, -16)) {
5309 set_bounce_count($user);
5311 // Else maybe they've already changed it?
5314 break;
5315 // Maybe more later?
5319 // CORRESPONDENCE.
5322 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5324 * @param string $action 'get', 'buffer', 'close' or 'flush'
5325 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5327 function get_mailer($action='get') {
5328 global $CFG;
5330 /** @var moodle_phpmailer $mailer */
5331 static $mailer = null;
5332 static $counter = 0;
5334 if (!isset($CFG->smtpmaxbulk)) {
5335 $CFG->smtpmaxbulk = 1;
5338 if ($action == 'get') {
5339 $prevkeepalive = false;
5341 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5342 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5343 $counter++;
5344 // Reset the mailer.
5345 $mailer->Priority = 3;
5346 $mailer->CharSet = 'UTF-8'; // Our default.
5347 $mailer->ContentType = "text/plain";
5348 $mailer->Encoding = "8bit";
5349 $mailer->From = "root@localhost";
5350 $mailer->FromName = "Root User";
5351 $mailer->Sender = "";
5352 $mailer->Subject = "";
5353 $mailer->Body = "";
5354 $mailer->AltBody = "";
5355 $mailer->ConfirmReadingTo = "";
5357 $mailer->clearAllRecipients();
5358 $mailer->clearReplyTos();
5359 $mailer->clearAttachments();
5360 $mailer->clearCustomHeaders();
5361 return $mailer;
5364 $prevkeepalive = $mailer->SMTPKeepAlive;
5365 get_mailer('flush');
5368 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5369 $mailer = new moodle_phpmailer();
5371 $counter = 1;
5373 if ($CFG->smtphosts == 'qmail') {
5374 // Use Qmail system.
5375 $mailer->isQmail();
5377 } else if (empty($CFG->smtphosts)) {
5378 // Use PHP mail() = sendmail.
5379 $mailer->isMail();
5381 } else {
5382 // Use SMTP directly.
5383 $mailer->isSMTP();
5384 if (!empty($CFG->debugsmtp)) {
5385 $mailer->SMTPDebug = true;
5387 // Specify main and backup servers.
5388 $mailer->Host = $CFG->smtphosts;
5389 // Specify secure connection protocol.
5390 $mailer->SMTPSecure = $CFG->smtpsecure;
5391 // Use previous keepalive.
5392 $mailer->SMTPKeepAlive = $prevkeepalive;
5394 if ($CFG->smtpuser) {
5395 // Use SMTP authentication.
5396 $mailer->SMTPAuth = true;
5397 $mailer->Username = $CFG->smtpuser;
5398 $mailer->Password = $CFG->smtppass;
5402 return $mailer;
5405 $nothing = null;
5407 // Keep smtp session open after sending.
5408 if ($action == 'buffer') {
5409 if (!empty($CFG->smtpmaxbulk)) {
5410 get_mailer('flush');
5411 $m = get_mailer();
5412 if ($m->Mailer == 'smtp') {
5413 $m->SMTPKeepAlive = true;
5416 return $nothing;
5419 // Close smtp session, but continue buffering.
5420 if ($action == 'flush') {
5421 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5422 if (!empty($mailer->SMTPDebug)) {
5423 echo '<pre>'."\n";
5425 $mailer->SmtpClose();
5426 if (!empty($mailer->SMTPDebug)) {
5427 echo '</pre>';
5430 return $nothing;
5433 // Close smtp session, do not buffer anymore.
5434 if ($action == 'close') {
5435 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5436 get_mailer('flush');
5437 $mailer->SMTPKeepAlive = false;
5439 $mailer = null; // Better force new instance.
5440 return $nothing;
5445 * Send an email to a specified user
5447 * @param stdClass $user A {@link $USER} object
5448 * @param stdClass $from A {@link $USER} object
5449 * @param string $subject plain text subject line of the email
5450 * @param string $messagetext plain text version of the message
5451 * @param string $messagehtml complete html version of the message (optional)
5452 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5453 * @param string $attachname the name of the file (extension indicates MIME)
5454 * @param bool $usetrueaddress determines whether $from email address should
5455 * be sent out. Will be overruled by user profile setting for maildisplay
5456 * @param string $replyto Email address to reply to
5457 * @param string $replytoname Name of reply to recipient
5458 * @param int $wordwrapwidth custom word wrap width, default 79
5459 * @return bool Returns true if mail was sent OK and false if there was an error.
5461 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5462 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5464 global $CFG;
5466 if (empty($user) or empty($user->id)) {
5467 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5468 return false;
5471 if (empty($user->email)) {
5472 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5473 return false;
5476 if (!empty($user->deleted)) {
5477 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5478 return false;
5481 if (defined('BEHAT_SITE_RUNNING')) {
5482 // Fake email sending in behat.
5483 return true;
5486 if (!empty($CFG->noemailever)) {
5487 // Hidden setting for development sites, set in config.php if needed.
5488 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5489 return true;
5492 if (!empty($CFG->divertallemailsto)) {
5493 $subject = "[DIVERTED {$user->email}] $subject";
5494 $user = clone($user);
5495 $user->email = $CFG->divertallemailsto;
5498 // Skip mail to suspended users.
5499 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5500 return true;
5503 if (!validate_email($user->email)) {
5504 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5505 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5506 return false;
5509 if (over_bounce_threshold($user)) {
5510 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5511 return false;
5514 // TLD .invalid is specifically reserved for invalid domain names.
5515 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5516 if (substr($user->email, -8) == '.invalid') {
5517 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5518 return true; // This is not an error.
5521 // If the user is a remote mnet user, parse the email text for URL to the
5522 // wwwroot and modify the url to direct the user's browser to login at their
5523 // home site (identity provider - idp) before hitting the link itself.
5524 if (is_mnet_remote_user($user)) {
5525 require_once($CFG->dirroot.'/mnet/lib.php');
5527 $jumpurl = mnet_get_idp_jump_url($user);
5528 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5530 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5531 $callback,
5532 $messagetext);
5533 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5534 $callback,
5535 $messagehtml);
5537 $mail = get_mailer();
5539 if (!empty($mail->SMTPDebug)) {
5540 echo '<pre>' . "\n";
5543 $temprecipients = array();
5544 $tempreplyto = array();
5546 $supportuser = core_user::get_support_user();
5548 // Make up an email address for handling bounces.
5549 if (!empty($CFG->handlebounces)) {
5550 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5551 $mail->Sender = generate_email_processing_address(0, $modargs);
5552 } else {
5553 $mail->Sender = $supportuser->email;
5556 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5557 $usetrueaddress = false;
5558 if (empty($replyto) && $from->maildisplay) {
5559 $replyto = $from->email;
5560 $replytoname = fullname($from);
5564 if (is_string($from)) { // So we can pass whatever we want if there is need.
5565 $mail->From = $CFG->noreplyaddress;
5566 $mail->FromName = $from;
5567 } else if ($usetrueaddress and $from->maildisplay) {
5568 $mail->From = $from->email;
5569 $mail->FromName = fullname($from);
5570 } else {
5571 $mail->From = $CFG->noreplyaddress;
5572 $mail->FromName = fullname($from);
5573 if (empty($replyto)) {
5574 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5578 if (!empty($replyto)) {
5579 $tempreplyto[] = array($replyto, $replytoname);
5582 $mail->Subject = substr($subject, 0, 900);
5584 $temprecipients[] = array($user->email, fullname($user));
5586 // Set word wrap.
5587 $mail->WordWrap = $wordwrapwidth;
5589 if (!empty($from->customheaders)) {
5590 // Add custom headers.
5591 if (is_array($from->customheaders)) {
5592 foreach ($from->customheaders as $customheader) {
5593 $mail->addCustomHeader($customheader);
5595 } else {
5596 $mail->addCustomHeader($from->customheaders);
5600 if (!empty($from->priority)) {
5601 $mail->Priority = $from->priority;
5604 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5605 // Don't ever send HTML to users who don't want it.
5606 $mail->isHTML(true);
5607 $mail->Encoding = 'quoted-printable';
5608 $mail->Body = $messagehtml;
5609 $mail->AltBody = "\n$messagetext\n";
5610 } else {
5611 $mail->IsHTML(false);
5612 $mail->Body = "\n$messagetext\n";
5615 if ($attachment && $attachname) {
5616 if (preg_match( "~\\.\\.~" , $attachment )) {
5617 // Security check for ".." in dir path.
5618 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5619 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5620 } else {
5621 require_once($CFG->libdir.'/filelib.php');
5622 $mimetype = mimeinfo('type', $attachname);
5624 $attachmentpath = $attachment;
5626 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5627 $attachpath = str_replace('\\', '/', $attachmentpath);
5628 // Make sure both variables are normalised before comparing.
5629 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
5631 // If the attachment is a full path to a file in the tempdir, use it as is,
5632 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5633 if (strpos($attachpath, $temppath) !== 0) {
5634 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5637 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5641 // Check if the email should be sent in an other charset then the default UTF-8.
5642 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5644 // Use the defined site mail charset or eventually the one preferred by the recipient.
5645 $charset = $CFG->sitemailcharset;
5646 if (!empty($CFG->allowusermailcharset)) {
5647 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5648 $charset = $useremailcharset;
5652 // Convert all the necessary strings if the charset is supported.
5653 $charsets = get_list_of_charsets();
5654 unset($charsets['UTF-8']);
5655 if (in_array($charset, $charsets)) {
5656 $mail->CharSet = $charset;
5657 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5658 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5659 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5660 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5662 foreach ($temprecipients as $key => $values) {
5663 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5665 foreach ($tempreplyto as $key => $values) {
5666 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5671 foreach ($temprecipients as $values) {
5672 $mail->addAddress($values[0], $values[1]);
5674 foreach ($tempreplyto as $values) {
5675 $mail->addReplyTo($values[0], $values[1]);
5678 if ($mail->send()) {
5679 set_send_count($user);
5680 if (!empty($mail->SMTPDebug)) {
5681 echo '</pre>';
5683 return true;
5684 } else {
5685 // Trigger event for failing to send email.
5686 $event = \core\event\email_failed::create(array(
5687 'context' => context_system::instance(),
5688 'userid' => $from->id,
5689 'relateduserid' => $user->id,
5690 'other' => array(
5691 'subject' => $subject,
5692 'message' => $messagetext,
5693 'errorinfo' => $mail->ErrorInfo
5696 $event->trigger();
5697 if (CLI_SCRIPT) {
5698 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5700 if (!empty($mail->SMTPDebug)) {
5701 echo '</pre>';
5703 return false;
5708 * Generate a signoff for emails based on support settings
5710 * @return string
5712 function generate_email_signoff() {
5713 global $CFG;
5715 $signoff = "\n";
5716 if (!empty($CFG->supportname)) {
5717 $signoff .= $CFG->supportname."\n";
5719 if (!empty($CFG->supportemail)) {
5720 $signoff .= $CFG->supportemail."\n";
5722 if (!empty($CFG->supportpage)) {
5723 $signoff .= $CFG->supportpage."\n";
5725 return $signoff;
5729 * Sets specified user's password and send the new password to the user via email.
5731 * @param stdClass $user A {@link $USER} object
5732 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5733 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
5735 function setnew_password_and_mail($user, $fasthash = false) {
5736 global $CFG, $DB;
5738 // We try to send the mail in language the user understands,
5739 // unfortunately the filter_string() does not support alternative langs yet
5740 // so multilang will not work properly for site->fullname.
5741 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
5743 $site = get_site();
5745 $supportuser = core_user::get_support_user();
5747 $newpassword = generate_password();
5749 update_internal_user_password($user, $newpassword, $fasthash);
5751 $a = new stdClass();
5752 $a->firstname = fullname($user, true);
5753 $a->sitename = format_string($site->fullname);
5754 $a->username = $user->username;
5755 $a->newpassword = $newpassword;
5756 $a->link = $CFG->wwwroot .'/login/';
5757 $a->signoff = generate_email_signoff();
5759 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
5761 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
5763 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5764 return email_to_user($user, $supportuser, $subject, $message);
5769 * Resets specified user's password and send the new password to the user via email.
5771 * @param stdClass $user A {@link $USER} object
5772 * @return bool Returns true if mail was sent OK and false if there was an error.
5774 function reset_password_and_mail($user) {
5775 global $CFG;
5777 $site = get_site();
5778 $supportuser = core_user::get_support_user();
5780 $userauth = get_auth_plugin($user->auth);
5781 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
5782 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
5783 return false;
5786 $newpassword = generate_password();
5788 if (!$userauth->user_update_password($user, $newpassword)) {
5789 print_error("cannotsetpassword");
5792 $a = new stdClass();
5793 $a->firstname = $user->firstname;
5794 $a->lastname = $user->lastname;
5795 $a->sitename = format_string($site->fullname);
5796 $a->username = $user->username;
5797 $a->newpassword = $newpassword;
5798 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
5799 $a->signoff = generate_email_signoff();
5801 $message = get_string('newpasswordtext', '', $a);
5803 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
5805 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
5807 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5808 return email_to_user($user, $supportuser, $subject, $message);
5812 * Send email to specified user with confirmation text and activation link.
5814 * @param stdClass $user A {@link $USER} object
5815 * @return bool Returns true if mail was sent OK and false if there was an error.
5817 function send_confirmation_email($user) {
5818 global $CFG;
5820 $site = get_site();
5821 $supportuser = core_user::get_support_user();
5823 $data = new stdClass();
5824 $data->firstname = fullname($user);
5825 $data->sitename = format_string($site->fullname);
5826 $data->admin = generate_email_signoff();
5828 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
5830 $username = urlencode($user->username);
5831 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
5832 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
5833 $message = get_string('emailconfirmation', '', $data);
5834 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
5836 $user->mailformat = 1; // Always send HTML version as well.
5838 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5839 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
5843 * Sends a password change confirmation email.
5845 * @param stdClass $user A {@link $USER} object
5846 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
5847 * @return bool Returns true if mail was sent OK and false if there was an error.
5849 function send_password_change_confirmation_email($user, $resetrecord) {
5850 global $CFG;
5852 $site = get_site();
5853 $supportuser = core_user::get_support_user();
5854 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
5856 $data = new stdClass();
5857 $data->firstname = $user->firstname;
5858 $data->lastname = $user->lastname;
5859 $data->username = $user->username;
5860 $data->sitename = format_string($site->fullname);
5861 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
5862 $data->admin = generate_email_signoff();
5863 $data->resetminutes = $pwresetmins;
5865 $message = get_string('emailresetconfirmation', '', $data);
5866 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
5868 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5869 return email_to_user($user, $supportuser, $subject, $message);
5874 * Sends an email containinginformation on how to change your password.
5876 * @param stdClass $user A {@link $USER} object
5877 * @return bool Returns true if mail was sent OK and false if there was an error.
5879 function send_password_change_info($user) {
5880 global $CFG;
5882 $site = get_site();
5883 $supportuser = core_user::get_support_user();
5884 $systemcontext = context_system::instance();
5886 $data = new stdClass();
5887 $data->firstname = $user->firstname;
5888 $data->lastname = $user->lastname;
5889 $data->sitename = format_string($site->fullname);
5890 $data->admin = generate_email_signoff();
5892 $userauth = get_auth_plugin($user->auth);
5894 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
5895 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
5896 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5897 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5898 return email_to_user($user, $supportuser, $subject, $message);
5901 if ($userauth->can_change_password() and $userauth->change_password_url()) {
5902 // We have some external url for password changing.
5903 $data->link .= $userauth->change_password_url();
5905 } else {
5906 // No way to change password, sorry.
5907 $data->link = '';
5910 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
5911 $message = get_string('emailpasswordchangeinfo', '', $data);
5912 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5913 } else {
5914 $message = get_string('emailpasswordchangeinfofail', '', $data);
5915 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5918 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5919 return email_to_user($user, $supportuser, $subject, $message);
5924 * Check that an email is allowed. It returns an error message if there was a problem.
5926 * @param string $email Content of email
5927 * @return string|false
5929 function email_is_not_allowed($email) {
5930 global $CFG;
5932 if (!empty($CFG->allowemailaddresses)) {
5933 $allowed = explode(' ', $CFG->allowemailaddresses);
5934 foreach ($allowed as $allowedpattern) {
5935 $allowedpattern = trim($allowedpattern);
5936 if (!$allowedpattern) {
5937 continue;
5939 if (strpos($allowedpattern, '.') === 0) {
5940 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
5941 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
5942 return false;
5945 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
5946 return false;
5949 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
5951 } else if (!empty($CFG->denyemailaddresses)) {
5952 $denied = explode(' ', $CFG->denyemailaddresses);
5953 foreach ($denied as $deniedpattern) {
5954 $deniedpattern = trim($deniedpattern);
5955 if (!$deniedpattern) {
5956 continue;
5958 if (strpos($deniedpattern, '.') === 0) {
5959 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
5960 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
5961 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
5964 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
5965 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
5970 return false;
5973 // FILE HANDLING.
5976 * Returns local file storage instance
5978 * @return file_storage
5980 function get_file_storage() {
5981 global $CFG;
5983 static $fs = null;
5985 if ($fs) {
5986 return $fs;
5989 require_once("$CFG->libdir/filelib.php");
5991 if (isset($CFG->filedir)) {
5992 $filedir = $CFG->filedir;
5993 } else {
5994 $filedir = $CFG->dataroot.'/filedir';
5997 if (isset($CFG->trashdir)) {
5998 $trashdirdir = $CFG->trashdir;
5999 } else {
6000 $trashdirdir = $CFG->dataroot.'/trashdir';
6003 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6005 return $fs;
6009 * Returns local file storage instance
6011 * @return file_browser
6013 function get_file_browser() {
6014 global $CFG;
6016 static $fb = null;
6018 if ($fb) {
6019 return $fb;
6022 require_once("$CFG->libdir/filelib.php");
6024 $fb = new file_browser();
6026 return $fb;
6030 * Returns file packer
6032 * @param string $mimetype default application/zip
6033 * @return file_packer
6035 function get_file_packer($mimetype='application/zip') {
6036 global $CFG;
6038 static $fp = array();
6040 if (isset($fp[$mimetype])) {
6041 return $fp[$mimetype];
6044 switch ($mimetype) {
6045 case 'application/zip':
6046 case 'application/vnd.moodle.profiling':
6047 $classname = 'zip_packer';
6048 break;
6050 case 'application/x-gzip' :
6051 $classname = 'tgz_packer';
6052 break;
6054 case 'application/vnd.moodle.backup':
6055 $classname = 'mbz_packer';
6056 break;
6058 default:
6059 return false;
6062 require_once("$CFG->libdir/filestorage/$classname.php");
6063 $fp[$mimetype] = new $classname();
6065 return $fp[$mimetype];
6069 * Returns current name of file on disk if it exists.
6071 * @param string $newfile File to be verified
6072 * @return string Current name of file on disk if true
6074 function valid_uploaded_file($newfile) {
6075 if (empty($newfile)) {
6076 return '';
6078 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6079 return $newfile['tmp_name'];
6080 } else {
6081 return '';
6086 * Returns the maximum size for uploading files.
6088 * There are seven possible upload limits:
6089 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6090 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6091 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6092 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6093 * 5. by the Moodle admin in $CFG->maxbytes
6094 * 6. by the teacher in the current course $course->maxbytes
6095 * 7. by the teacher for the current module, eg $assignment->maxbytes
6097 * These last two are passed to this function as arguments (in bytes).
6098 * Anything defined as 0 is ignored.
6099 * The smallest of all the non-zero numbers is returned.
6101 * @todo Finish documenting this function
6103 * @param int $sitebytes Set maximum size
6104 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6105 * @param int $modulebytes Current module ->maxbytes (in bytes)
6106 * @return int The maximum size for uploading files.
6108 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6110 if (! $filesize = ini_get('upload_max_filesize')) {
6111 $filesize = '5M';
6113 $minimumsize = get_real_size($filesize);
6115 if ($postsize = ini_get('post_max_size')) {
6116 $postsize = get_real_size($postsize);
6117 if ($postsize < $minimumsize) {
6118 $minimumsize = $postsize;
6122 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6123 $minimumsize = $sitebytes;
6126 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6127 $minimumsize = $coursebytes;
6130 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6131 $minimumsize = $modulebytes;
6134 return $minimumsize;
6138 * Returns the maximum size for uploading files for the current user
6140 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6142 * @param context $context The context in which to check user capabilities
6143 * @param int $sitebytes Set maximum size
6144 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6145 * @param int $modulebytes Current module ->maxbytes (in bytes)
6146 * @param stdClass $user The user
6147 * @return int The maximum size for uploading files.
6149 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6150 global $USER;
6152 if (empty($user)) {
6153 $user = $USER;
6156 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6157 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6160 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6164 * Returns an array of possible sizes in local language
6166 * Related to {@link get_max_upload_file_size()} - this function returns an
6167 * array of possible sizes in an array, translated to the
6168 * local language.
6170 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6172 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6173 * with the value set to 0. This option will be the first in the list.
6175 * @uses SORT_NUMERIC
6176 * @param int $sitebytes Set maximum size
6177 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6178 * @param int $modulebytes Current module ->maxbytes (in bytes)
6179 * @param int|array $custombytes custom upload size/s which will be added to list,
6180 * Only value/s smaller then maxsize will be added to list.
6181 * @return array
6183 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6184 global $CFG;
6186 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6187 return array();
6190 if ($sitebytes == 0) {
6191 // Will get the minimum of upload_max_filesize or post_max_size.
6192 $sitebytes = get_max_upload_file_size();
6195 $filesize = array();
6196 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6197 5242880, 10485760, 20971520, 52428800, 104857600);
6199 // If custombytes is given and is valid then add it to the list.
6200 if (is_number($custombytes) and $custombytes > 0) {
6201 $custombytes = (int)$custombytes;
6202 if (!in_array($custombytes, $sizelist)) {
6203 $sizelist[] = $custombytes;
6205 } else if (is_array($custombytes)) {
6206 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6209 // Allow maxbytes to be selected if it falls outside the above boundaries.
6210 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6211 // Note: get_real_size() is used in order to prevent problems with invalid values.
6212 $sizelist[] = get_real_size($CFG->maxbytes);
6215 foreach ($sizelist as $sizebytes) {
6216 if ($sizebytes < $maxsize && $sizebytes > 0) {
6217 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6221 $limitlevel = '';
6222 $displaysize = '';
6223 if ($modulebytes &&
6224 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6225 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6226 $limitlevel = get_string('activity', 'core');
6227 $displaysize = display_size($modulebytes);
6228 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6230 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6231 $limitlevel = get_string('course', 'core');
6232 $displaysize = display_size($coursebytes);
6233 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6235 } else if ($sitebytes) {
6236 $limitlevel = get_string('site', 'core');
6237 $displaysize = display_size($sitebytes);
6238 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6241 krsort($filesize, SORT_NUMERIC);
6242 if ($limitlevel) {
6243 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6244 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6247 return $filesize;
6251 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6253 * If excludefiles is defined, then that file/directory is ignored
6254 * If getdirs is true, then (sub)directories are included in the output
6255 * If getfiles is true, then files are included in the output
6256 * (at least one of these must be true!)
6258 * @todo Finish documenting this function. Add examples of $excludefile usage.
6260 * @param string $rootdir A given root directory to start from
6261 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6262 * @param bool $descend If true then subdirectories are recursed as well
6263 * @param bool $getdirs If true then (sub)directories are included in the output
6264 * @param bool $getfiles If true then files are included in the output
6265 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6267 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6269 $dirs = array();
6271 if (!$getdirs and !$getfiles) { // Nothing to show.
6272 return $dirs;
6275 if (!is_dir($rootdir)) { // Must be a directory.
6276 return $dirs;
6279 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6280 return $dirs;
6283 if (!is_array($excludefiles)) {
6284 $excludefiles = array($excludefiles);
6287 while (false !== ($file = readdir($dir))) {
6288 $firstchar = substr($file, 0, 1);
6289 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6290 continue;
6292 $fullfile = $rootdir .'/'. $file;
6293 if (filetype($fullfile) == 'dir') {
6294 if ($getdirs) {
6295 $dirs[] = $file;
6297 if ($descend) {
6298 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6299 foreach ($subdirs as $subdir) {
6300 $dirs[] = $file .'/'. $subdir;
6303 } else if ($getfiles) {
6304 $dirs[] = $file;
6307 closedir($dir);
6309 asort($dirs);
6311 return $dirs;
6316 * Adds up all the files in a directory and works out the size.
6318 * @param string $rootdir The directory to start from
6319 * @param string $excludefile A file to exclude when summing directory size
6320 * @return int The summed size of all files and subfiles within the root directory
6322 function get_directory_size($rootdir, $excludefile='') {
6323 global $CFG;
6325 // Do it this way if we can, it's much faster.
6326 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6327 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6328 $output = null;
6329 $return = null;
6330 exec($command, $output, $return);
6331 if (is_array($output)) {
6332 // We told it to return k.
6333 return get_real_size(intval($output[0]).'k');
6337 if (!is_dir($rootdir)) {
6338 // Must be a directory.
6339 return 0;
6342 if (!$dir = @opendir($rootdir)) {
6343 // Can't open it for some reason.
6344 return 0;
6347 $size = 0;
6349 while (false !== ($file = readdir($dir))) {
6350 $firstchar = substr($file, 0, 1);
6351 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6352 continue;
6354 $fullfile = $rootdir .'/'. $file;
6355 if (filetype($fullfile) == 'dir') {
6356 $size += get_directory_size($fullfile, $excludefile);
6357 } else {
6358 $size += filesize($fullfile);
6361 closedir($dir);
6363 return $size;
6367 * Converts bytes into display form
6369 * @static string $gb Localized string for size in gigabytes
6370 * @static string $mb Localized string for size in megabytes
6371 * @static string $kb Localized string for size in kilobytes
6372 * @static string $b Localized string for size in bytes
6373 * @param int $size The size to convert to human readable form
6374 * @return string
6376 function display_size($size) {
6378 static $gb, $mb, $kb, $b;
6380 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6381 return get_string('unlimited');
6384 if (empty($gb)) {
6385 $gb = get_string('sizegb');
6386 $mb = get_string('sizemb');
6387 $kb = get_string('sizekb');
6388 $b = get_string('sizeb');
6391 if ($size >= 1073741824) {
6392 $size = round($size / 1073741824 * 10) / 10 . $gb;
6393 } else if ($size >= 1048576) {
6394 $size = round($size / 1048576 * 10) / 10 . $mb;
6395 } else if ($size >= 1024) {
6396 $size = round($size / 1024 * 10) / 10 . $kb;
6397 } else {
6398 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6400 return $size;
6404 * Cleans a given filename by removing suspicious or troublesome characters
6406 * @see clean_param()
6407 * @param string $string file name
6408 * @return string cleaned file name
6410 function clean_filename($string) {
6411 return clean_param($string, PARAM_FILE);
6415 // STRING TRANSLATION.
6418 * Returns the code for the current language
6420 * @category string
6421 * @return string
6423 function current_language() {
6424 global $CFG, $USER, $SESSION, $COURSE;
6426 if (!empty($SESSION->forcelang)) {
6427 // Allows overriding course-forced language (useful for admins to check
6428 // issues in courses whose language they don't understand).
6429 // Also used by some code to temporarily get language-related information in a
6430 // specific language (see force_current_language()).
6431 $return = $SESSION->forcelang;
6433 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6434 // Course language can override all other settings for this page.
6435 $return = $COURSE->lang;
6437 } else if (!empty($SESSION->lang)) {
6438 // Session language can override other settings.
6439 $return = $SESSION->lang;
6441 } else if (!empty($USER->lang)) {
6442 $return = $USER->lang;
6444 } else if (isset($CFG->lang)) {
6445 $return = $CFG->lang;
6447 } else {
6448 $return = 'en';
6451 // Just in case this slipped in from somewhere by accident.
6452 $return = str_replace('_utf8', '', $return);
6454 return $return;
6458 * Returns parent language of current active language if defined
6460 * @category string
6461 * @param string $lang null means current language
6462 * @return string
6464 function get_parent_language($lang=null) {
6466 // Let's hack around the current language.
6467 if (!empty($lang)) {
6468 $oldforcelang = force_current_language($lang);
6471 $parentlang = get_string('parentlanguage', 'langconfig');
6472 if ($parentlang === 'en') {
6473 $parentlang = '';
6476 // Let's hack around the current language.
6477 if (!empty($lang)) {
6478 force_current_language($oldforcelang);
6481 return $parentlang;
6485 * Force the current language to get strings and dates localised in the given language.
6487 * After calling this function, all strings will be provided in the given language
6488 * until this function is called again, or equivalent code is run.
6490 * @param string $language
6491 * @return string previous $SESSION->forcelang value
6493 function force_current_language($language) {
6494 global $SESSION;
6495 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6496 if ($language !== $sessionforcelang) {
6497 // Seting forcelang to null or an empty string disables it's effect.
6498 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6499 $SESSION->forcelang = $language;
6500 moodle_setlocale();
6503 return $sessionforcelang;
6507 * Returns current string_manager instance.
6509 * The param $forcereload is needed for CLI installer only where the string_manager instance
6510 * must be replaced during the install.php script life time.
6512 * @category string
6513 * @param bool $forcereload shall the singleton be released and new instance created instead?
6514 * @return core_string_manager
6516 function get_string_manager($forcereload=false) {
6517 global $CFG;
6519 static $singleton = null;
6521 if ($forcereload) {
6522 $singleton = null;
6524 if ($singleton === null) {
6525 if (empty($CFG->early_install_lang)) {
6527 if (empty($CFG->langlist)) {
6528 $translist = array();
6529 } else {
6530 $translist = explode(',', $CFG->langlist);
6533 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6534 $classname = $CFG->config_php_settings['customstringmanager'];
6536 if (class_exists($classname)) {
6537 $implements = class_implements($classname);
6539 if (isset($implements['core_string_manager'])) {
6540 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6541 return $singleton;
6543 } else {
6544 debugging('Unable to instantiate custom string manager: class '.$classname.
6545 ' does not implement the core_string_manager interface.');
6548 } else {
6549 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6553 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6555 } else {
6556 $singleton = new core_string_manager_install();
6560 return $singleton;
6564 * Returns a localized string.
6566 * Returns the translated string specified by $identifier as
6567 * for $module. Uses the same format files as STphp.
6568 * $a is an object, string or number that can be used
6569 * within translation strings
6571 * eg 'hello {$a->firstname} {$a->lastname}'
6572 * or 'hello {$a}'
6574 * If you would like to directly echo the localized string use
6575 * the function {@link print_string()}
6577 * Example usage of this function involves finding the string you would
6578 * like a local equivalent of and using its identifier and module information
6579 * to retrieve it.<br/>
6580 * If you open moodle/lang/en/moodle.php and look near line 278
6581 * you will find a string to prompt a user for their word for 'course'
6582 * <code>
6583 * $string['course'] = 'Course';
6584 * </code>
6585 * So if you want to display the string 'Course'
6586 * in any language that supports it on your site
6587 * you just need to use the identifier 'course'
6588 * <code>
6589 * $mystring = '<strong>'. get_string('course') .'</strong>';
6590 * or
6591 * </code>
6592 * If the string you want is in another file you'd take a slightly
6593 * different approach. Looking in moodle/lang/en/calendar.php you find
6594 * around line 75:
6595 * <code>
6596 * $string['typecourse'] = 'Course event';
6597 * </code>
6598 * If you want to display the string "Course event" in any language
6599 * supported you would use the identifier 'typecourse' and the module 'calendar'
6600 * (because it is in the file calendar.php):
6601 * <code>
6602 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6603 * </code>
6605 * As a last resort, should the identifier fail to map to a string
6606 * the returned string will be [[ $identifier ]]
6608 * In Moodle 2.3 there is a new argument to this function $lazyload.
6609 * Setting $lazyload to true causes get_string to return a lang_string object
6610 * rather than the string itself. The fetching of the string is then put off until
6611 * the string object is first used. The object can be used by calling it's out
6612 * method or by casting the object to a string, either directly e.g.
6613 * (string)$stringobject
6614 * or indirectly by using the string within another string or echoing it out e.g.
6615 * echo $stringobject
6616 * return "<p>{$stringobject}</p>";
6617 * It is worth noting that using $lazyload and attempting to use the string as an
6618 * array key will cause a fatal error as objects cannot be used as array keys.
6619 * But you should never do that anyway!
6620 * For more information {@link lang_string}
6622 * @category string
6623 * @param string $identifier The key identifier for the localized string
6624 * @param string $component The module where the key identifier is stored,
6625 * usually expressed as the filename in the language pack without the
6626 * .php on the end but can also be written as mod/forum or grade/export/xls.
6627 * If none is specified then moodle.php is used.
6628 * @param string|object|array $a An object, string or number that can be used
6629 * within translation strings
6630 * @param bool $lazyload If set to true a string object is returned instead of
6631 * the string itself. The string then isn't calculated until it is first used.
6632 * @return string The localized string.
6633 * @throws coding_exception
6635 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6636 global $CFG;
6638 // If the lazy load argument has been supplied return a lang_string object
6639 // instead.
6640 // We need to make sure it is true (and a bool) as you will see below there
6641 // used to be a forth argument at one point.
6642 if ($lazyload === true) {
6643 return new lang_string($identifier, $component, $a);
6646 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6647 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6650 // There is now a forth argument again, this time it is a boolean however so
6651 // we can still check for the old extralocations parameter.
6652 if (!is_bool($lazyload) && !empty($lazyload)) {
6653 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6656 if (strpos($component, '/') !== false) {
6657 debugging('The module name you passed to get_string is the deprecated format ' .
6658 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6659 $componentpath = explode('/', $component);
6661 switch ($componentpath[0]) {
6662 case 'mod':
6663 $component = $componentpath[1];
6664 break;
6665 case 'blocks':
6666 case 'block':
6667 $component = 'block_'.$componentpath[1];
6668 break;
6669 case 'enrol':
6670 $component = 'enrol_'.$componentpath[1];
6671 break;
6672 case 'format':
6673 $component = 'format_'.$componentpath[1];
6674 break;
6675 case 'grade':
6676 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6677 break;
6681 $result = get_string_manager()->get_string($identifier, $component, $a);
6683 // Debugging feature lets you display string identifier and component.
6684 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6685 $result .= ' {' . $identifier . '/' . $component . '}';
6687 return $result;
6691 * Converts an array of strings to their localized value.
6693 * @param array $array An array of strings
6694 * @param string $component The language module that these strings can be found in.
6695 * @return stdClass translated strings.
6697 function get_strings($array, $component = '') {
6698 $string = new stdClass;
6699 foreach ($array as $item) {
6700 $string->$item = get_string($item, $component);
6702 return $string;
6706 * Prints out a translated string.
6708 * Prints out a translated string using the return value from the {@link get_string()} function.
6710 * Example usage of this function when the string is in the moodle.php file:<br/>
6711 * <code>
6712 * echo '<strong>';
6713 * print_string('course');
6714 * echo '</strong>';
6715 * </code>
6717 * Example usage of this function when the string is not in the moodle.php file:<br/>
6718 * <code>
6719 * echo '<h1>';
6720 * print_string('typecourse', 'calendar');
6721 * echo '</h1>';
6722 * </code>
6724 * @category string
6725 * @param string $identifier The key identifier for the localized string
6726 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6727 * @param string|object|array $a An object, string or number that can be used within translation strings
6729 function print_string($identifier, $component = '', $a = null) {
6730 echo get_string($identifier, $component, $a);
6734 * Returns a list of charset codes
6736 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6737 * (checking that such charset is supported by the texlib library!)
6739 * @return array And associative array with contents in the form of charset => charset
6741 function get_list_of_charsets() {
6743 $charsets = array(
6744 'EUC-JP' => 'EUC-JP',
6745 'ISO-2022-JP'=> 'ISO-2022-JP',
6746 'ISO-8859-1' => 'ISO-8859-1',
6747 'SHIFT-JIS' => 'SHIFT-JIS',
6748 'GB2312' => 'GB2312',
6749 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
6750 'UTF-8' => 'UTF-8');
6752 asort($charsets);
6754 return $charsets;
6758 * Returns a list of valid and compatible themes
6760 * @return array
6762 function get_list_of_themes() {
6763 global $CFG;
6765 $themes = array();
6767 if (!empty($CFG->themelist)) { // Use admin's list of themes.
6768 $themelist = explode(',', $CFG->themelist);
6769 } else {
6770 $themelist = array_keys(core_component::get_plugin_list("theme"));
6773 foreach ($themelist as $key => $themename) {
6774 $theme = theme_config::load($themename);
6775 $themes[$themename] = $theme;
6778 core_collator::asort_objects_by_method($themes, 'get_theme_name');
6780 return $themes;
6784 * Factory function for emoticon_manager
6786 * @return emoticon_manager singleton
6788 function get_emoticon_manager() {
6789 static $singleton = null;
6791 if (is_null($singleton)) {
6792 $singleton = new emoticon_manager();
6795 return $singleton;
6799 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
6801 * Whenever this manager mentiones 'emoticon object', the following data
6802 * structure is expected: stdClass with properties text, imagename, imagecomponent,
6803 * altidentifier and altcomponent
6805 * @see admin_setting_emoticons
6807 * @copyright 2010 David Mudrak
6808 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6810 class emoticon_manager {
6813 * Returns the currently enabled emoticons
6815 * @return array of emoticon objects
6817 public function get_emoticons() {
6818 global $CFG;
6820 if (empty($CFG->emoticons)) {
6821 return array();
6824 $emoticons = $this->decode_stored_config($CFG->emoticons);
6826 if (!is_array($emoticons)) {
6827 // Something is wrong with the format of stored setting.
6828 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
6829 return array();
6832 return $emoticons;
6836 * Converts emoticon object into renderable pix_emoticon object
6838 * @param stdClass $emoticon emoticon object
6839 * @param array $attributes explicit HTML attributes to set
6840 * @return pix_emoticon
6842 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
6843 $stringmanager = get_string_manager();
6844 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
6845 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
6846 } else {
6847 $alt = s($emoticon->text);
6849 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
6853 * Encodes the array of emoticon objects into a string storable in config table
6855 * @see self::decode_stored_config()
6856 * @param array $emoticons array of emtocion objects
6857 * @return string
6859 public function encode_stored_config(array $emoticons) {
6860 return json_encode($emoticons);
6864 * Decodes the string into an array of emoticon objects
6866 * @see self::encode_stored_config()
6867 * @param string $encoded
6868 * @return string|null
6870 public function decode_stored_config($encoded) {
6871 $decoded = json_decode($encoded);
6872 if (!is_array($decoded)) {
6873 return null;
6875 return $decoded;
6879 * Returns default set of emoticons supported by Moodle
6881 * @return array of sdtClasses
6883 public function default_emoticons() {
6884 return array(
6885 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
6886 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
6887 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
6888 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
6889 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
6890 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
6891 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
6892 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
6893 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
6894 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
6895 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
6896 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
6897 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
6898 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
6899 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
6900 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
6901 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
6902 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
6903 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
6904 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
6905 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
6906 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
6907 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
6908 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
6909 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
6910 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
6911 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
6912 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
6913 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
6914 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
6919 * Helper method preparing the stdClass with the emoticon properties
6921 * @param string|array $text or array of strings
6922 * @param string $imagename to be used by {@link pix_emoticon}
6923 * @param string $altidentifier alternative string identifier, null for no alt
6924 * @param string $altcomponent where the alternative string is defined
6925 * @param string $imagecomponent to be used by {@link pix_emoticon}
6926 * @return stdClass
6928 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
6929 $altcomponent = 'core_pix', $imagecomponent = 'core') {
6930 return (object)array(
6931 'text' => $text,
6932 'imagename' => $imagename,
6933 'imagecomponent' => $imagecomponent,
6934 'altidentifier' => $altidentifier,
6935 'altcomponent' => $altcomponent,
6940 // ENCRYPTION.
6943 * rc4encrypt
6945 * @param string $data Data to encrypt.
6946 * @return string The now encrypted data.
6948 function rc4encrypt($data) {
6949 return endecrypt(get_site_identifier(), $data, '');
6953 * rc4decrypt
6955 * @param string $data Data to decrypt.
6956 * @return string The now decrypted data.
6958 function rc4decrypt($data) {
6959 return endecrypt(get_site_identifier(), $data, 'de');
6963 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
6965 * @todo Finish documenting this function
6967 * @param string $pwd The password to use when encrypting or decrypting
6968 * @param string $data The data to be decrypted/encrypted
6969 * @param string $case Either 'de' for decrypt or '' for encrypt
6970 * @return string
6972 function endecrypt ($pwd, $data, $case) {
6974 if ($case == 'de') {
6975 $data = urldecode($data);
6978 $key[] = '';
6979 $box[] = '';
6980 $pwdlength = strlen($pwd);
6982 for ($i = 0; $i <= 255; $i++) {
6983 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
6984 $box[$i] = $i;
6987 $x = 0;
6989 for ($i = 0; $i <= 255; $i++) {
6990 $x = ($x + $box[$i] + $key[$i]) % 256;
6991 $tempswap = $box[$i];
6992 $box[$i] = $box[$x];
6993 $box[$x] = $tempswap;
6996 $cipher = '';
6998 $a = 0;
6999 $j = 0;
7001 for ($i = 0; $i < strlen($data); $i++) {
7002 $a = ($a + 1) % 256;
7003 $j = ($j + $box[$a]) % 256;
7004 $temp = $box[$a];
7005 $box[$a] = $box[$j];
7006 $box[$j] = $temp;
7007 $k = $box[(($box[$a] + $box[$j]) % 256)];
7008 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7009 $cipher .= chr($cipherby);
7012 if ($case == 'de') {
7013 $cipher = urldecode(urlencode($cipher));
7014 } else {
7015 $cipher = urlencode($cipher);
7018 return $cipher;
7021 // ENVIRONMENT CHECKING.
7024 * This method validates a plug name. It is much faster than calling clean_param.
7026 * @param string $name a string that might be a plugin name.
7027 * @return bool if this string is a valid plugin name.
7029 function is_valid_plugin_name($name) {
7030 // This does not work for 'mod', bad luck, use any other type.
7031 return core_component::is_valid_plugin_name('tool', $name);
7035 * Get a list of all the plugins of a given type that define a certain API function
7036 * in a certain file. The plugin component names and function names are returned.
7038 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7039 * @param string $function the part of the name of the function after the
7040 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7041 * names like report_courselist_hook.
7042 * @param string $file the name of file within the plugin that defines the
7043 * function. Defaults to lib.php.
7044 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7045 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7047 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7048 $pluginfunctions = array();
7049 $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, $file, true);
7050 foreach ($pluginswithfile as $plugin => $notused) {
7051 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7053 if (function_exists($fullfunction)) {
7054 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7055 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7057 } else if ($plugintype === 'mod') {
7058 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7059 $shortfunction = $plugin . '_' . $function;
7060 if (function_exists($shortfunction)) {
7061 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7065 return $pluginfunctions;
7069 * Lists plugin-like directories within specified directory
7071 * This function was originally used for standard Moodle plugins, please use
7072 * new core_component::get_plugin_list() now.
7074 * This function is used for general directory listing and backwards compatility.
7076 * @param string $directory relative directory from root
7077 * @param string $exclude dir name to exclude from the list (defaults to none)
7078 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7079 * @return array Sorted array of directory names found under the requested parameters
7081 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7082 global $CFG;
7084 $plugins = array();
7086 if (empty($basedir)) {
7087 $basedir = $CFG->dirroot .'/'. $directory;
7089 } else {
7090 $basedir = $basedir .'/'. $directory;
7093 if ($CFG->debugdeveloper and empty($exclude)) {
7094 // Make sure devs do not use this to list normal plugins,
7095 // this is intended for general directories that are not plugins!
7097 $subtypes = core_component::get_plugin_types();
7098 if (in_array($basedir, $subtypes)) {
7099 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7101 unset($subtypes);
7104 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7105 if (!$dirhandle = opendir($basedir)) {
7106 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7107 return array();
7109 while (false !== ($dir = readdir($dirhandle))) {
7110 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7111 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7112 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7113 continue;
7115 if (filetype($basedir .'/'. $dir) != 'dir') {
7116 continue;
7118 $plugins[] = $dir;
7120 closedir($dirhandle);
7122 if ($plugins) {
7123 asort($plugins);
7125 return $plugins;
7129 * Invoke plugin's callback functions
7131 * @param string $type plugin type e.g. 'mod'
7132 * @param string $name plugin name
7133 * @param string $feature feature name
7134 * @param string $action feature's action
7135 * @param array $params parameters of callback function, should be an array
7136 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7137 * @return mixed
7139 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7141 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7142 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7146 * Invoke component's callback functions
7148 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7149 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7150 * @param array $params parameters of callback function
7151 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7152 * @return mixed
7154 function component_callback($component, $function, array $params = array(), $default = null) {
7156 $functionname = component_callback_exists($component, $function);
7158 if ($functionname) {
7159 // Function exists, so just return function result.
7160 $ret = call_user_func_array($functionname, $params);
7161 if (is_null($ret)) {
7162 return $default;
7163 } else {
7164 return $ret;
7167 return $default;
7171 * Determine if a component callback exists and return the function name to call. Note that this
7172 * function will include the required library files so that the functioname returned can be
7173 * called directly.
7175 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7176 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7177 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7178 * @throws coding_exception if invalid component specfied
7180 function component_callback_exists($component, $function) {
7181 global $CFG; // This is needed for the inclusions.
7183 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7184 if (empty($cleancomponent)) {
7185 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7187 $component = $cleancomponent;
7189 list($type, $name) = core_component::normalize_component($component);
7190 $component = $type . '_' . $name;
7192 $oldfunction = $name.'_'.$function;
7193 $function = $component.'_'.$function;
7195 $dir = core_component::get_component_directory($component);
7196 if (empty($dir)) {
7197 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7200 // Load library and look for function.
7201 if (file_exists($dir.'/lib.php')) {
7202 require_once($dir.'/lib.php');
7205 if (!function_exists($function) and function_exists($oldfunction)) {
7206 if ($type !== 'mod' and $type !== 'core') {
7207 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7209 $function = $oldfunction;
7212 if (function_exists($function)) {
7213 return $function;
7215 return false;
7219 * Checks whether a plugin supports a specified feature.
7221 * @param string $type Plugin type e.g. 'mod'
7222 * @param string $name Plugin name e.g. 'forum'
7223 * @param string $feature Feature code (FEATURE_xx constant)
7224 * @param mixed $default default value if feature support unknown
7225 * @return mixed Feature result (false if not supported, null if feature is unknown,
7226 * otherwise usually true but may have other feature-specific value such as array)
7227 * @throws coding_exception
7229 function plugin_supports($type, $name, $feature, $default = null) {
7230 global $CFG;
7232 if ($type === 'mod' and $name === 'NEWMODULE') {
7233 // Somebody forgot to rename the module template.
7234 return false;
7237 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7238 if (empty($component)) {
7239 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7242 $function = null;
7244 if ($type === 'mod') {
7245 // We need this special case because we support subplugins in modules,
7246 // otherwise it would end up in infinite loop.
7247 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7248 include_once("$CFG->dirroot/mod/$name/lib.php");
7249 $function = $component.'_supports';
7250 if (!function_exists($function)) {
7251 // Legacy non-frankenstyle function name.
7252 $function = $name.'_supports';
7256 } else {
7257 if (!$path = core_component::get_plugin_directory($type, $name)) {
7258 // Non existent plugin type.
7259 return false;
7261 if (file_exists("$path/lib.php")) {
7262 include_once("$path/lib.php");
7263 $function = $component.'_supports';
7267 if ($function and function_exists($function)) {
7268 $supports = $function($feature);
7269 if (is_null($supports)) {
7270 // Plugin does not know - use default.
7271 return $default;
7272 } else {
7273 return $supports;
7277 // Plugin does not care, so use default.
7278 return $default;
7282 * Returns true if the current version of PHP is greater that the specified one.
7284 * @todo Check PHP version being required here is it too low?
7286 * @param string $version The version of php being tested.
7287 * @return bool
7289 function check_php_version($version='5.2.4') {
7290 return (version_compare(phpversion(), $version) >= 0);
7294 * Determine if moodle installation requires update.
7296 * Checks version numbers of main code and all plugins to see
7297 * if there are any mismatches.
7299 * @return bool
7301 function moodle_needs_upgrading() {
7302 global $CFG;
7304 if (empty($CFG->version)) {
7305 return true;
7308 // There is no need to purge plugininfo caches here because
7309 // these caches are not used during upgrade and they are purged after
7310 // every upgrade.
7312 if (empty($CFG->allversionshash)) {
7313 return true;
7316 $hash = core_component::get_all_versions_hash();
7318 return ($hash !== $CFG->allversionshash);
7322 * Returns the major version of this site
7324 * Moodle version numbers consist of three numbers separated by a dot, for
7325 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7326 * called major version. This function extracts the major version from either
7327 * $CFG->release (default) or eventually from the $release variable defined in
7328 * the main version.php.
7330 * @param bool $fromdisk should the version if source code files be used
7331 * @return string|false the major version like '2.3', false if could not be determined
7333 function moodle_major_version($fromdisk = false) {
7334 global $CFG;
7336 if ($fromdisk) {
7337 $release = null;
7338 require($CFG->dirroot.'/version.php');
7339 if (empty($release)) {
7340 return false;
7343 } else {
7344 if (empty($CFG->release)) {
7345 return false;
7347 $release = $CFG->release;
7350 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7351 return $matches[0];
7352 } else {
7353 return false;
7357 // MISCELLANEOUS.
7360 * Sets the system locale
7362 * @category string
7363 * @param string $locale Can be used to force a locale
7365 function moodle_setlocale($locale='') {
7366 global $CFG;
7368 static $currentlocale = ''; // Last locale caching.
7370 $oldlocale = $currentlocale;
7372 // Fetch the correct locale based on ostype.
7373 if ($CFG->ostype == 'WINDOWS') {
7374 $stringtofetch = 'localewin';
7375 } else {
7376 $stringtofetch = 'locale';
7379 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7380 if (!empty($locale)) {
7381 $currentlocale = $locale;
7382 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7383 $currentlocale = $CFG->locale;
7384 } else {
7385 $currentlocale = get_string($stringtofetch, 'langconfig');
7388 // Do nothing if locale already set up.
7389 if ($oldlocale == $currentlocale) {
7390 return;
7393 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7394 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7395 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7397 // Get current values.
7398 $monetary= setlocale (LC_MONETARY, 0);
7399 $numeric = setlocale (LC_NUMERIC, 0);
7400 $ctype = setlocale (LC_CTYPE, 0);
7401 if ($CFG->ostype != 'WINDOWS') {
7402 $messages= setlocale (LC_MESSAGES, 0);
7404 // Set locale to all.
7405 $result = setlocale (LC_ALL, $currentlocale);
7406 // If setting of locale fails try the other utf8 or utf-8 variant,
7407 // some operating systems support both (Debian), others just one (OSX).
7408 if ($result === false) {
7409 if (stripos($currentlocale, '.UTF-8') !== false) {
7410 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7411 setlocale (LC_ALL, $newlocale);
7412 } else if (stripos($currentlocale, '.UTF8') !== false) {
7413 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7414 setlocale (LC_ALL, $newlocale);
7417 // Set old values.
7418 setlocale (LC_MONETARY, $monetary);
7419 setlocale (LC_NUMERIC, $numeric);
7420 if ($CFG->ostype != 'WINDOWS') {
7421 setlocale (LC_MESSAGES, $messages);
7423 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7424 // To workaround a well-known PHP problem with Turkish letter Ii.
7425 setlocale (LC_CTYPE, $ctype);
7430 * Count words in a string.
7432 * Words are defined as things between whitespace.
7434 * @category string
7435 * @param string $string The text to be searched for words.
7436 * @return int The count of words in the specified string
7438 function count_words($string) {
7439 $string = strip_tags($string);
7440 // Decode HTML entities.
7441 $string = html_entity_decode($string);
7442 // Replace underscores (which are classed as word characters) with spaces.
7443 $string = preg_replace('/_/u', ' ', $string);
7444 // Remove any characters that shouldn't be treated as word boundaries.
7445 $string = preg_replace('/[\'’-]/u', '', $string);
7446 // Remove dots and commas from within numbers only.
7447 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7449 return count(preg_split('/\w\b/u', $string)) - 1;
7453 * Count letters in a string.
7455 * Letters are defined as chars not in tags and different from whitespace.
7457 * @category string
7458 * @param string $string The text to be searched for letters.
7459 * @return int The count of letters in the specified text.
7461 function count_letters($string) {
7462 $string = strip_tags($string); // Tags are out now.
7463 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7465 return core_text::strlen($string);
7469 * Generate and return a random string of the specified length.
7471 * @param int $length The length of the string to be created.
7472 * @return string
7474 function random_string($length=15) {
7475 $randombytes = random_bytes_emulate($length);
7476 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7477 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7478 $pool .= '0123456789';
7479 $poollen = strlen($pool);
7480 $string = '';
7481 for ($i = 0; $i < $length; $i++) {
7482 $rand = ord($randombytes[$i]);
7483 $string .= substr($pool, ($rand%($poollen)), 1);
7485 return $string;
7489 * Generate a complex random string (useful for md5 salts)
7491 * This function is based on the above {@link random_string()} however it uses a
7492 * larger pool of characters and generates a string between 24 and 32 characters
7494 * @param int $length Optional if set generates a string to exactly this length
7495 * @return string
7497 function complex_random_string($length=null) {
7498 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7499 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7500 $poollen = strlen($pool);
7501 if ($length===null) {
7502 $length = floor(rand(24, 32));
7504 $randombytes = random_bytes_emulate($length);
7505 $string = '';
7506 for ($i = 0; $i < $length; $i++) {
7507 $rand = ord($randombytes[$i]);
7508 $string .= $pool[($rand%$poollen)];
7510 return $string;
7514 * Try to generates cryptographically secure pseudo-random bytes.
7516 * Note this is achieved by fallbacking between:
7517 * - PHP 7 random_bytes().
7518 * - OpenSSL openssl_random_pseudo_bytes().
7519 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
7521 * @param int $length requested length in bytes
7522 * @return string binary data
7524 function random_bytes_emulate($length) {
7525 global $CFG;
7526 if ($length <= 0) {
7527 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
7528 return '';
7530 if (function_exists('random_bytes')) {
7531 // Use PHP 7 goodness.
7532 $hash = @random_bytes($length);
7533 if ($hash !== false) {
7534 return $hash;
7537 if (function_exists('openssl_random_pseudo_bytes')) {
7538 // For PHP 5.3 and later with openssl extension.
7539 $hash = openssl_random_pseudo_bytes($length);
7540 if ($hash !== false) {
7541 return $hash;
7545 // Bad luck, there is no reliable random generator, let's just hash some unique stuff that is hard to guess.
7546 $hash = sha1(serialize($CFG) . serialize($_SERVER) . microtime(true) . uniqid('', true), true);
7547 // NOTE: the last param in sha1() is true, this means we are getting 20 bytes, not 40 chars as usual.
7548 if ($length <= 20) {
7549 return substr($hash, 0, $length);
7551 return $hash . random_bytes_emulate($length - 20);
7555 * Given some text (which may contain HTML) and an ideal length,
7556 * this function truncates the text neatly on a word boundary if possible
7558 * @category string
7559 * @param string $text text to be shortened
7560 * @param int $ideal ideal string length
7561 * @param boolean $exact if false, $text will not be cut mid-word
7562 * @param string $ending The string to append if the passed string is truncated
7563 * @return string $truncate shortened string
7565 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7566 // If the plain text is shorter than the maximum length, return the whole text.
7567 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7568 return $text;
7571 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7572 // and only tag in its 'line'.
7573 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7575 $totallength = core_text::strlen($ending);
7576 $truncate = '';
7578 // This array stores information about open and close tags and their position
7579 // in the truncated string. Each item in the array is an object with fields
7580 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7581 // (byte position in truncated text).
7582 $tagdetails = array();
7584 foreach ($lines as $linematchings) {
7585 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7586 if (!empty($linematchings[1])) {
7587 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7588 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7589 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7590 // Record closing tag.
7591 $tagdetails[] = (object) array(
7592 'open' => false,
7593 'tag' => core_text::strtolower($tagmatchings[1]),
7594 'pos' => core_text::strlen($truncate),
7597 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7598 // Record opening tag.
7599 $tagdetails[] = (object) array(
7600 'open' => true,
7601 'tag' => core_text::strtolower($tagmatchings[1]),
7602 'pos' => core_text::strlen($truncate),
7606 // Add html-tag to $truncate'd text.
7607 $truncate .= $linematchings[1];
7610 // Calculate the length of the plain text part of the line; handle entities as one character.
7611 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7612 if ($totallength + $contentlength > $ideal) {
7613 // The number of characters which are left.
7614 $left = $ideal - $totallength;
7615 $entitieslength = 0;
7616 // Search for html entities.
7617 if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $linematchings[2], $entities, PREG_OFFSET_CAPTURE)) {
7618 // Calculate the real length of all entities in the legal range.
7619 foreach ($entities[0] as $entity) {
7620 if ($entity[1]+1-$entitieslength <= $left) {
7621 $left--;
7622 $entitieslength += core_text::strlen($entity[0]);
7623 } else {
7624 // No more characters left.
7625 break;
7629 $breakpos = $left + $entitieslength;
7631 // If the words shouldn't be cut in the middle...
7632 if (!$exact) {
7633 // Search the last occurence of a space.
7634 for (; $breakpos > 0; $breakpos--) {
7635 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7636 if ($char === '.' or $char === ' ') {
7637 $breakpos += 1;
7638 break;
7639 } else if (strlen($char) > 2) {
7640 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7641 $breakpos += 1;
7642 break;
7647 if ($breakpos == 0) {
7648 // This deals with the test_shorten_text_no_spaces case.
7649 $breakpos = $left + $entitieslength;
7650 } else if ($breakpos > $left + $entitieslength) {
7651 // This deals with the previous for loop breaking on the first char.
7652 $breakpos = $left + $entitieslength;
7655 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
7656 // Maximum length is reached, so get off the loop.
7657 break;
7658 } else {
7659 $truncate .= $linematchings[2];
7660 $totallength += $contentlength;
7663 // If the maximum length is reached, get off the loop.
7664 if ($totallength >= $ideal) {
7665 break;
7669 // Add the defined ending to the text.
7670 $truncate .= $ending;
7672 // Now calculate the list of open html tags based on the truncate position.
7673 $opentags = array();
7674 foreach ($tagdetails as $taginfo) {
7675 if ($taginfo->open) {
7676 // Add tag to the beginning of $opentags list.
7677 array_unshift($opentags, $taginfo->tag);
7678 } else {
7679 // Can have multiple exact same open tags, close the last one.
7680 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
7681 if ($pos !== false) {
7682 unset($opentags[$pos]);
7687 // Close all unclosed html-tags.
7688 foreach ($opentags as $tag) {
7689 $truncate .= '</' . $tag . '>';
7692 return $truncate;
7697 * Given dates in seconds, how many weeks is the date from startdate
7698 * The first week is 1, the second 2 etc ...
7700 * @param int $startdate Timestamp for the start date
7701 * @param int $thedate Timestamp for the end date
7702 * @return string
7704 function getweek ($startdate, $thedate) {
7705 if ($thedate < $startdate) {
7706 return 0;
7709 return floor(($thedate - $startdate) / WEEKSECS) + 1;
7713 * Returns a randomly generated password of length $maxlen. inspired by
7715 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7716 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7718 * @param int $maxlen The maximum size of the password being generated.
7719 * @return string
7721 function generate_password($maxlen=10) {
7722 global $CFG;
7724 if (empty($CFG->passwordpolicy)) {
7725 $fillers = PASSWORD_DIGITS;
7726 $wordlist = file($CFG->wordlist);
7727 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7728 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7729 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
7730 $password = $word1 . $filler1 . $word2;
7731 } else {
7732 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
7733 $digits = $CFG->minpassworddigits;
7734 $lower = $CFG->minpasswordlower;
7735 $upper = $CFG->minpasswordupper;
7736 $nonalphanum = $CFG->minpasswordnonalphanum;
7737 $total = $lower + $upper + $digits + $nonalphanum;
7738 // Var minlength should be the greater one of the two ( $minlen and $total ).
7739 $minlen = $minlen < $total ? $total : $minlen;
7740 // Var maxlen can never be smaller than minlen.
7741 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
7742 $additional = $maxlen - $total;
7744 // Make sure we have enough characters to fulfill
7745 // complexity requirements.
7746 $passworddigits = PASSWORD_DIGITS;
7747 while ($digits > strlen($passworddigits)) {
7748 $passworddigits .= PASSWORD_DIGITS;
7750 $passwordlower = PASSWORD_LOWER;
7751 while ($lower > strlen($passwordlower)) {
7752 $passwordlower .= PASSWORD_LOWER;
7754 $passwordupper = PASSWORD_UPPER;
7755 while ($upper > strlen($passwordupper)) {
7756 $passwordupper .= PASSWORD_UPPER;
7758 $passwordnonalphanum = PASSWORD_NONALPHANUM;
7759 while ($nonalphanum > strlen($passwordnonalphanum)) {
7760 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
7763 // Now mix and shuffle it all.
7764 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
7765 substr(str_shuffle ($passwordupper), 0, $upper) .
7766 substr(str_shuffle ($passworddigits), 0, $digits) .
7767 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
7768 substr(str_shuffle ($passwordlower .
7769 $passwordupper .
7770 $passworddigits .
7771 $passwordnonalphanum), 0 , $additional));
7774 return substr ($password, 0, $maxlen);
7778 * Given a float, prints it nicely.
7779 * Localized floats must not be used in calculations!
7781 * The stripzeros feature is intended for making numbers look nicer in small
7782 * areas where it is not necessary to indicate the degree of accuracy by showing
7783 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
7784 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
7786 * @param float $float The float to print
7787 * @param int $decimalpoints The number of decimal places to print.
7788 * @param bool $localized use localized decimal separator
7789 * @param bool $stripzeros If true, removes final zeros after decimal point
7790 * @return string locale float
7792 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
7793 if (is_null($float)) {
7794 return '';
7796 if ($localized) {
7797 $separator = get_string('decsep', 'langconfig');
7798 } else {
7799 $separator = '.';
7801 $result = number_format($float, $decimalpoints, $separator, '');
7802 if ($stripzeros) {
7803 // Remove zeros and final dot if not needed.
7804 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
7806 return $result;
7810 * Converts locale specific floating point/comma number back to standard PHP float value
7811 * Do NOT try to do any math operations before this conversion on any user submitted floats!
7813 * @param string $localefloat locale aware float representation
7814 * @param bool $strict If true, then check the input and return false if it is not a valid number.
7815 * @return mixed float|bool - false or the parsed float.
7817 function unformat_float($localefloat, $strict = false) {
7818 $localefloat = trim($localefloat);
7820 if ($localefloat == '') {
7821 return null;
7824 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
7825 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
7827 if ($strict && !is_numeric($localefloat)) {
7828 return false;
7831 return (float)$localefloat;
7835 * Given a simple array, this shuffles it up just like shuffle()
7836 * Unlike PHP's shuffle() this function works on any machine.
7838 * @param array $array The array to be rearranged
7839 * @return array
7841 function swapshuffle($array) {
7843 $last = count($array) - 1;
7844 for ($i = 0; $i <= $last; $i++) {
7845 $from = rand(0, $last);
7846 $curr = $array[$i];
7847 $array[$i] = $array[$from];
7848 $array[$from] = $curr;
7850 return $array;
7854 * Like {@link swapshuffle()}, but works on associative arrays
7856 * @param array $array The associative array to be rearranged
7857 * @return array
7859 function swapshuffle_assoc($array) {
7861 $newarray = array();
7862 $newkeys = swapshuffle(array_keys($array));
7864 foreach ($newkeys as $newkey) {
7865 $newarray[$newkey] = $array[$newkey];
7867 return $newarray;
7871 * Given an arbitrary array, and a number of draws,
7872 * this function returns an array with that amount
7873 * of items. The indexes are retained.
7875 * @todo Finish documenting this function
7877 * @param array $array
7878 * @param int $draws
7879 * @return array
7881 function draw_rand_array($array, $draws) {
7883 $return = array();
7885 $last = count($array);
7887 if ($draws > $last) {
7888 $draws = $last;
7891 while ($draws > 0) {
7892 $last--;
7894 $keys = array_keys($array);
7895 $rand = rand(0, $last);
7897 $return[$keys[$rand]] = $array[$keys[$rand]];
7898 unset($array[$keys[$rand]]);
7900 $draws--;
7903 return $return;
7907 * Calculate the difference between two microtimes
7909 * @param string $a The first Microtime
7910 * @param string $b The second Microtime
7911 * @return string
7913 function microtime_diff($a, $b) {
7914 list($adec, $asec) = explode(' ', $a);
7915 list($bdec, $bsec) = explode(' ', $b);
7916 return $bsec - $asec + $bdec - $adec;
7920 * Given a list (eg a,b,c,d,e) this function returns
7921 * an array of 1->a, 2->b, 3->c etc
7923 * @param string $list The string to explode into array bits
7924 * @param string $separator The separator used within the list string
7925 * @return array The now assembled array
7927 function make_menu_from_list($list, $separator=',') {
7929 $array = array_reverse(explode($separator, $list), true);
7930 foreach ($array as $key => $item) {
7931 $outarray[$key+1] = trim($item);
7933 return $outarray;
7937 * Creates an array that represents all the current grades that
7938 * can be chosen using the given grading type.
7940 * Negative numbers
7941 * are scales, zero is no grade, and positive numbers are maximum
7942 * grades.
7944 * @todo Finish documenting this function or better deprecated this completely!
7946 * @param int $gradingtype
7947 * @return array
7949 function make_grades_menu($gradingtype) {
7950 global $DB;
7952 $grades = array();
7953 if ($gradingtype < 0) {
7954 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
7955 return make_menu_from_list($scale->scale);
7957 } else if ($gradingtype > 0) {
7958 for ($i=$gradingtype; $i>=0; $i--) {
7959 $grades[$i] = $i .' / '. $gradingtype;
7961 return $grades;
7963 return $grades;
7967 * This function returns the number of activities using the given scale in the given course.
7969 * @param int $courseid The course ID to check.
7970 * @param int $scaleid The scale ID to check
7971 * @return int
7973 function course_scale_used($courseid, $scaleid) {
7974 global $CFG, $DB;
7976 $return = 0;
7978 if (!empty($scaleid)) {
7979 if ($cms = get_course_mods($courseid)) {
7980 foreach ($cms as $cm) {
7981 // Check cm->name/lib.php exists.
7982 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
7983 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
7984 $functionname = $cm->modname.'_scale_used';
7985 if (function_exists($functionname)) {
7986 if ($functionname($cm->instance, $scaleid)) {
7987 $return++;
7994 // Check if any course grade item makes use of the scale.
7995 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
7997 // Check if any outcome in the course makes use of the scale.
7998 $return += $DB->count_records_sql("SELECT COUNT('x')
7999 FROM {grade_outcomes_courses} goc,
8000 {grade_outcomes} go
8001 WHERE go.id = goc.outcomeid
8002 AND go.scaleid = ? AND goc.courseid = ?",
8003 array($scaleid, $courseid));
8005 return $return;
8009 * This function returns the number of activities using scaleid in the entire site
8011 * @param int $scaleid
8012 * @param array $courses
8013 * @return int
8015 function site_scale_used($scaleid, &$courses) {
8016 $return = 0;
8018 if (!is_array($courses) || count($courses) == 0) {
8019 $courses = get_courses("all", false, "c.id, c.shortname");
8022 if (!empty($scaleid)) {
8023 if (is_array($courses) && count($courses) > 0) {
8024 foreach ($courses as $course) {
8025 $return += course_scale_used($course->id, $scaleid);
8029 return $return;
8033 * make_unique_id_code
8035 * @todo Finish documenting this function
8037 * @uses $_SERVER
8038 * @param string $extra Extra string to append to the end of the code
8039 * @return string
8041 function make_unique_id_code($extra = '') {
8043 $hostname = 'unknownhost';
8044 if (!empty($_SERVER['HTTP_HOST'])) {
8045 $hostname = $_SERVER['HTTP_HOST'];
8046 } else if (!empty($_ENV['HTTP_HOST'])) {
8047 $hostname = $_ENV['HTTP_HOST'];
8048 } else if (!empty($_SERVER['SERVER_NAME'])) {
8049 $hostname = $_SERVER['SERVER_NAME'];
8050 } else if (!empty($_ENV['SERVER_NAME'])) {
8051 $hostname = $_ENV['SERVER_NAME'];
8054 $date = gmdate("ymdHis");
8056 $random = random_string(6);
8058 if ($extra) {
8059 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8060 } else {
8061 return $hostname .'+'. $date .'+'. $random;
8067 * Function to check the passed address is within the passed subnet
8069 * The parameter is a comma separated string of subnet definitions.
8070 * Subnet strings can be in one of three formats:
8071 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8072 * 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group)
8073 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8074 * Code for type 1 modified from user posted comments by mediator at
8075 * {@link http://au.php.net/manual/en/function.ip2long.php}
8077 * @param string $addr The address you are checking
8078 * @param string $subnetstr The string of subnet addresses
8079 * @return bool
8081 function address_in_subnet($addr, $subnetstr) {
8083 if ($addr == '0.0.0.0') {
8084 return false;
8086 $subnets = explode(',', $subnetstr);
8087 $found = false;
8088 $addr = trim($addr);
8089 $addr = cleanremoteaddr($addr, false); // Normalise.
8090 if ($addr === null) {
8091 return false;
8093 $addrparts = explode(':', $addr);
8095 $ipv6 = strpos($addr, ':');
8097 foreach ($subnets as $subnet) {
8098 $subnet = trim($subnet);
8099 if ($subnet === '') {
8100 continue;
8103 if (strpos($subnet, '/') !== false) {
8104 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8105 list($ip, $mask) = explode('/', $subnet);
8106 $mask = trim($mask);
8107 if (!is_number($mask)) {
8108 continue; // Incorect mask number, eh?
8110 $ip = cleanremoteaddr($ip, false); // Normalise.
8111 if ($ip === null) {
8112 continue;
8114 if (strpos($ip, ':') !== false) {
8115 // IPv6.
8116 if (!$ipv6) {
8117 continue;
8119 if ($mask > 128 or $mask < 0) {
8120 continue; // Nonsense.
8122 if ($mask == 0) {
8123 return true; // Any address.
8125 if ($mask == 128) {
8126 if ($ip === $addr) {
8127 return true;
8129 continue;
8131 $ipparts = explode(':', $ip);
8132 $modulo = $mask % 16;
8133 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8134 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8135 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8136 if ($modulo == 0) {
8137 return true;
8139 $pos = ($mask-$modulo)/16;
8140 $ipnet = hexdec($ipparts[$pos]);
8141 $addrnet = hexdec($addrparts[$pos]);
8142 $mask = 0xffff << (16 - $modulo);
8143 if (($addrnet & $mask) == ($ipnet & $mask)) {
8144 return true;
8148 } else {
8149 // IPv4.
8150 if ($ipv6) {
8151 continue;
8153 if ($mask > 32 or $mask < 0) {
8154 continue; // Nonsense.
8156 if ($mask == 0) {
8157 return true;
8159 if ($mask == 32) {
8160 if ($ip === $addr) {
8161 return true;
8163 continue;
8165 $mask = 0xffffffff << (32 - $mask);
8166 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8167 return true;
8171 } else if (strpos($subnet, '-') !== false) {
8172 // 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy. A range of IP addresses in the last group.
8173 $parts = explode('-', $subnet);
8174 if (count($parts) != 2) {
8175 continue;
8178 if (strpos($subnet, ':') !== false) {
8179 // IPv6.
8180 if (!$ipv6) {
8181 continue;
8183 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8184 if ($ipstart === null) {
8185 continue;
8187 $ipparts = explode(':', $ipstart);
8188 $start = hexdec(array_pop($ipparts));
8189 $ipparts[] = trim($parts[1]);
8190 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8191 if ($ipend === null) {
8192 continue;
8194 $ipparts[7] = '';
8195 $ipnet = implode(':', $ipparts);
8196 if (strpos($addr, $ipnet) !== 0) {
8197 continue;
8199 $ipparts = explode(':', $ipend);
8200 $end = hexdec($ipparts[7]);
8202 $addrend = hexdec($addrparts[7]);
8204 if (($addrend >= $start) and ($addrend <= $end)) {
8205 return true;
8208 } else {
8209 // IPv4.
8210 if ($ipv6) {
8211 continue;
8213 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8214 if ($ipstart === null) {
8215 continue;
8217 $ipparts = explode('.', $ipstart);
8218 $ipparts[3] = trim($parts[1]);
8219 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8220 if ($ipend === null) {
8221 continue;
8224 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8225 return true;
8229 } else {
8230 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8231 if (strpos($subnet, ':') !== false) {
8232 // IPv6.
8233 if (!$ipv6) {
8234 continue;
8236 $parts = explode(':', $subnet);
8237 $count = count($parts);
8238 if ($parts[$count-1] === '') {
8239 unset($parts[$count-1]); // Trim trailing :'s.
8240 $count--;
8241 $subnet = implode('.', $parts);
8243 $isip = cleanremoteaddr($subnet, false); // Normalise.
8244 if ($isip !== null) {
8245 if ($isip === $addr) {
8246 return true;
8248 continue;
8249 } else if ($count > 8) {
8250 continue;
8252 $zeros = array_fill(0, 8-$count, '0');
8253 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8254 if (address_in_subnet($addr, $subnet)) {
8255 return true;
8258 } else {
8259 // IPv4.
8260 if ($ipv6) {
8261 continue;
8263 $parts = explode('.', $subnet);
8264 $count = count($parts);
8265 if ($parts[$count-1] === '') {
8266 unset($parts[$count-1]); // Trim trailing .
8267 $count--;
8268 $subnet = implode('.', $parts);
8270 if ($count == 4) {
8271 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8272 if ($subnet === $addr) {
8273 return true;
8275 continue;
8276 } else if ($count > 4) {
8277 continue;
8279 $zeros = array_fill(0, 4-$count, '0');
8280 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8281 if (address_in_subnet($addr, $subnet)) {
8282 return true;
8288 return false;
8292 * For outputting debugging info
8294 * @param string $string The string to write
8295 * @param string $eol The end of line char(s) to use
8296 * @param string $sleep Period to make the application sleep
8297 * This ensures any messages have time to display before redirect
8299 function mtrace($string, $eol="\n", $sleep=0) {
8301 if (defined('STDOUT') and !PHPUNIT_TEST) {
8302 fwrite(STDOUT, $string.$eol);
8303 } else {
8304 echo $string . $eol;
8307 flush();
8309 // Delay to keep message on user's screen in case of subsequent redirect.
8310 if ($sleep) {
8311 sleep($sleep);
8316 * Replace 1 or more slashes or backslashes to 1 slash
8318 * @param string $path The path to strip
8319 * @return string the path with double slashes removed
8321 function cleardoubleslashes ($path) {
8322 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8326 * Is current ip in give list?
8328 * @param string $list
8329 * @return bool
8331 function remoteip_in_list($list) {
8332 $inlist = false;
8333 $clientip = getremoteaddr(null);
8335 if (!$clientip) {
8336 // Ensure access on cli.
8337 return true;
8340 $list = explode("\n", $list);
8341 foreach ($list as $subnet) {
8342 $subnet = trim($subnet);
8343 if (address_in_subnet($clientip, $subnet)) {
8344 $inlist = true;
8345 break;
8348 return $inlist;
8352 * Returns most reliable client address
8354 * @param string $default If an address can't be determined, then return this
8355 * @return string The remote IP address
8357 function getremoteaddr($default='0.0.0.0') {
8358 global $CFG;
8360 if (empty($CFG->getremoteaddrconf)) {
8361 // This will happen, for example, before just after the upgrade, as the
8362 // user is redirected to the admin screen.
8363 $variablestoskip = 0;
8364 } else {
8365 $variablestoskip = $CFG->getremoteaddrconf;
8367 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8368 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8369 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8370 return $address ? $address : $default;
8373 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8374 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8375 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8376 $address = $forwardedaddresses[0];
8378 if (substr_count($address, ":") > 1) {
8379 // Remove port and brackets from IPv6.
8380 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8381 $address = $matches[1];
8383 } else {
8384 // Remove port from IPv4.
8385 if (substr_count($address, ":") == 1) {
8386 $parts = explode(":", $address);
8387 $address = $parts[0];
8391 $address = cleanremoteaddr($address);
8392 return $address ? $address : $default;
8395 if (!empty($_SERVER['REMOTE_ADDR'])) {
8396 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8397 return $address ? $address : $default;
8398 } else {
8399 return $default;
8404 * Cleans an ip address. Internal addresses are now allowed.
8405 * (Originally local addresses were not allowed.)
8407 * @param string $addr IPv4 or IPv6 address
8408 * @param bool $compress use IPv6 address compression
8409 * @return string normalised ip address string, null if error
8411 function cleanremoteaddr($addr, $compress=false) {
8412 $addr = trim($addr);
8414 // TODO: maybe add a separate function is_addr_public() or something like this.
8416 if (strpos($addr, ':') !== false) {
8417 // Can be only IPv6.
8418 $parts = explode(':', $addr);
8419 $count = count($parts);
8421 if (strpos($parts[$count-1], '.') !== false) {
8422 // Legacy ipv4 notation.
8423 $last = array_pop($parts);
8424 $ipv4 = cleanremoteaddr($last, true);
8425 if ($ipv4 === null) {
8426 return null;
8428 $bits = explode('.', $ipv4);
8429 $parts[] = dechex($bits[0]).dechex($bits[1]);
8430 $parts[] = dechex($bits[2]).dechex($bits[3]);
8431 $count = count($parts);
8432 $addr = implode(':', $parts);
8435 if ($count < 3 or $count > 8) {
8436 return null; // Severly malformed.
8439 if ($count != 8) {
8440 if (strpos($addr, '::') === false) {
8441 return null; // Malformed.
8443 // Uncompress.
8444 $insertat = array_search('', $parts, true);
8445 $missing = array_fill(0, 1 + 8 - $count, '0');
8446 array_splice($parts, $insertat, 1, $missing);
8447 foreach ($parts as $key => $part) {
8448 if ($part === '') {
8449 $parts[$key] = '0';
8454 $adr = implode(':', $parts);
8455 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8456 return null; // Incorrect format - sorry.
8459 // Normalise 0s and case.
8460 $parts = array_map('hexdec', $parts);
8461 $parts = array_map('dechex', $parts);
8463 $result = implode(':', $parts);
8465 if (!$compress) {
8466 return $result;
8469 if ($result === '0:0:0:0:0:0:0:0') {
8470 return '::'; // All addresses.
8473 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8474 if ($compressed !== $result) {
8475 return $compressed;
8478 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8479 if ($compressed !== $result) {
8480 return $compressed;
8483 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8484 if ($compressed !== $result) {
8485 return $compressed;
8488 return $result;
8491 // First get all things that look like IPv4 addresses.
8492 $parts = array();
8493 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8494 return null;
8496 unset($parts[0]);
8498 foreach ($parts as $key => $match) {
8499 if ($match > 255) {
8500 return null;
8502 $parts[$key] = (int)$match; // Normalise 0s.
8505 return implode('.', $parts);
8509 * This function will make a complete copy of anything it's given,
8510 * regardless of whether it's an object or not.
8512 * @param mixed $thing Something you want cloned
8513 * @return mixed What ever it is you passed it
8515 function fullclone($thing) {
8516 return unserialize(serialize($thing));
8520 * If new messages are waiting for the current user, then insert
8521 * JavaScript to pop up the messaging window into the page
8523 * @return void
8525 function message_popup_window() {
8526 global $USER, $DB, $PAGE, $CFG;
8528 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8529 return;
8532 if (!isloggedin() || isguestuser()) {
8533 return;
8536 if (!isset($USER->message_lastpopup)) {
8537 $USER->message_lastpopup = 0;
8538 } else if ($USER->message_lastpopup > (time()-120)) {
8539 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8540 return;
8543 // A quick query to check whether the user has new messages.
8544 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8545 if ($messagecount < 1) {
8546 return;
8549 // There are unread messages so now do a more complex but slower query.
8550 $messagesql = "SELECT m.id, c.blocked
8551 FROM {message} m
8552 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8553 JOIN {message_processors} p ON mw.processorid=p.id
8554 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8555 AND c.userid = m.useridto
8556 WHERE m.useridto = :userid
8557 AND p.name='popup'";
8559 // If the user was last notified over an hour ago we can re-notify them of old messages
8560 // so don't worry about when the new message was sent.
8561 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8562 if (!$lastnotifiedlongago) {
8563 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8566 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8568 $validmessages = 0;
8569 foreach ($waitingmessages as $messageinfo) {
8570 if ($messageinfo->blocked) {
8571 // Message is from a user who has since been blocked so just mark it read.
8572 // Get the full message to mark as read.
8573 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
8574 message_mark_message_read($messageobject, time());
8575 } else {
8576 $validmessages++;
8580 if ($validmessages > 0) {
8581 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8582 $strgomessage = get_string('gotomessages', 'message');
8583 $strstaymessage = get_string('ignore', 'admin');
8585 $notificationsound = null;
8586 $beep = get_user_preferences('message_beepnewmessage', '');
8587 if (!empty($beep)) {
8588 // Browsers will work down this list until they find something they support.
8589 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8590 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8591 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8592 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8594 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8597 $url = $CFG->wwwroot.'/message/index.php';
8598 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8599 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8600 $strmessages.
8601 html_writer::end_tag('div').
8603 $notificationsound.
8604 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8605 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
8606 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8607 html_writer::end_tag('div');
8608 html_writer::end_tag('div');
8610 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8612 $USER->message_lastpopup = time();
8617 * Used to make sure that $min <= $value <= $max
8619 * Make sure that value is between min, and max
8621 * @param int $min The minimum value
8622 * @param int $value The value to check
8623 * @param int $max The maximum value
8624 * @return int
8626 function bounded_number($min, $value, $max) {
8627 if ($value < $min) {
8628 return $min;
8630 if ($value > $max) {
8631 return $max;
8633 return $value;
8637 * Check if there is a nested array within the passed array
8639 * @param array $array
8640 * @return bool true if there is a nested array false otherwise
8642 function array_is_nested($array) {
8643 foreach ($array as $value) {
8644 if (is_array($value)) {
8645 return true;
8648 return false;
8652 * get_performance_info() pairs up with init_performance_info()
8653 * loaded in setup.php. Returns an array with 'html' and 'txt'
8654 * values ready for use, and each of the individual stats provided
8655 * separately as well.
8657 * @return array
8659 function get_performance_info() {
8660 global $CFG, $PERF, $DB, $PAGE;
8662 $info = array();
8663 $info['html'] = ''; // Holds userfriendly HTML representation.
8664 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8666 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8668 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8669 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8671 if (function_exists('memory_get_usage')) {
8672 $info['memory_total'] = memory_get_usage();
8673 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8674 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8675 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8676 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8679 if (function_exists('memory_get_peak_usage')) {
8680 $info['memory_peak'] = memory_get_peak_usage();
8681 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8682 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8685 $inc = get_included_files();
8686 $info['includecount'] = count($inc);
8687 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8688 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8690 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8691 // We can not track more performance before installation or before PAGE init, sorry.
8692 return $info;
8695 $filtermanager = filter_manager::instance();
8696 if (method_exists($filtermanager, 'get_performance_summary')) {
8697 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8698 $info = array_merge($filterinfo, $info);
8699 foreach ($filterinfo as $key => $value) {
8700 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8701 $info['txt'] .= "$key: $value ";
8705 $stringmanager = get_string_manager();
8706 if (method_exists($stringmanager, 'get_performance_summary')) {
8707 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8708 $info = array_merge($filterinfo, $info);
8709 foreach ($filterinfo as $key => $value) {
8710 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8711 $info['txt'] .= "$key: $value ";
8715 if (!empty($PERF->logwrites)) {
8716 $info['logwrites'] = $PERF->logwrites;
8717 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8718 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8721 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
8722 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8723 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8725 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8726 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
8727 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8729 if (function_exists('posix_times')) {
8730 $ptimes = posix_times();
8731 if (is_array($ptimes)) {
8732 foreach ($ptimes as $key => $val) {
8733 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
8735 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8736 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8740 // Grab the load average for the last minute.
8741 // /proc will only work under some linux configurations
8742 // while uptime is there under MacOSX/Darwin and other unices.
8743 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
8744 list($serverload) = explode(' ', $loadavg[0]);
8745 unset($loadavg);
8746 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
8747 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8748 $serverload = $matches[1];
8749 } else {
8750 trigger_error('Could not parse uptime output!');
8753 if (!empty($serverload)) {
8754 $info['serverload'] = $serverload;
8755 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
8756 $info['txt'] .= "serverload: {$info['serverload']} ";
8759 // Display size of session if session started.
8760 if ($si = \core\session\manager::get_performance_info()) {
8761 $info['sessionsize'] = $si['size'];
8762 $info['html'] .= $si['html'];
8763 $info['txt'] .= $si['txt'];
8766 if ($stats = cache_helper::get_stats()) {
8767 $html = '<span class="cachesused">';
8768 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
8769 $text = 'Caches used (hits/misses/sets): ';
8770 $hits = 0;
8771 $misses = 0;
8772 $sets = 0;
8773 foreach ($stats as $definition => $details) {
8774 switch ($details['mode']) {
8775 case cache_store::MODE_APPLICATION:
8776 $modeclass = 'application';
8777 $mode = ' <span title="application cache">[a]</span>';
8778 break;
8779 case cache_store::MODE_SESSION:
8780 $modeclass = 'session';
8781 $mode = ' <span title="session cache">[s]</span>';
8782 break;
8783 case cache_store::MODE_REQUEST:
8784 $modeclass = 'request';
8785 $mode = ' <span title="request cache">[r]</span>';
8786 break;
8788 $html .= '<span class="cache-definition-stats cache-mode-'.$modeclass.'">';
8789 $html .= '<span class="cache-definition-stats-heading">'.$definition.$mode.'</span>';
8790 $text .= "$definition {";
8791 foreach ($details['stores'] as $store => $data) {
8792 $hits += $data['hits'];
8793 $misses += $data['misses'];
8794 $sets += $data['sets'];
8795 if ($data['hits'] == 0 and $data['misses'] > 0) {
8796 $cachestoreclass = 'nohits';
8797 } else if ($data['hits'] < $data['misses']) {
8798 $cachestoreclass = 'lowhits';
8799 } else {
8800 $cachestoreclass = 'hihits';
8802 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
8803 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
8805 $html .= '</span>';
8806 $text .= '} ';
8808 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
8809 $html .= '</span> ';
8810 $info['cachesused'] = "$hits / $misses / $sets";
8811 $info['html'] .= $html;
8812 $info['txt'] .= $text.'. ';
8813 } else {
8814 $info['cachesused'] = '0 / 0 / 0';
8815 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
8816 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
8819 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
8820 return $info;
8824 * Legacy function.
8826 * @todo Document this function linux people
8828 function apd_get_profiling() {
8829 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
8833 * Delete directory or only its content
8835 * @param string $dir directory path
8836 * @param bool $contentonly
8837 * @return bool success, true also if dir does not exist
8839 function remove_dir($dir, $contentonly=false) {
8840 if (!file_exists($dir)) {
8841 // Nothing to do.
8842 return true;
8844 if (!$handle = opendir($dir)) {
8845 return false;
8847 $result = true;
8848 while (false!==($item = readdir($handle))) {
8849 if ($item != '.' && $item != '..') {
8850 if (is_dir($dir.'/'.$item)) {
8851 $result = remove_dir($dir.'/'.$item) && $result;
8852 } else {
8853 $result = unlink($dir.'/'.$item) && $result;
8857 closedir($handle);
8858 if ($contentonly) {
8859 clearstatcache(); // Make sure file stat cache is properly invalidated.
8860 return $result;
8862 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
8863 clearstatcache(); // Make sure file stat cache is properly invalidated.
8864 return $result;
8868 * Detect if an object or a class contains a given property
8869 * will take an actual object or the name of a class
8871 * @param mix $obj Name of class or real object to test
8872 * @param string $property name of property to find
8873 * @return bool true if property exists
8875 function object_property_exists( $obj, $property ) {
8876 if (is_string( $obj )) {
8877 $properties = get_class_vars( $obj );
8878 } else {
8879 $properties = get_object_vars( $obj );
8881 return array_key_exists( $property, $properties );
8885 * Converts an object into an associative array
8887 * This function converts an object into an associative array by iterating
8888 * over its public properties. Because this function uses the foreach
8889 * construct, Iterators are respected. It works recursively on arrays of objects.
8890 * Arrays and simple values are returned as is.
8892 * If class has magic properties, it can implement IteratorAggregate
8893 * and return all available properties in getIterator()
8895 * @param mixed $var
8896 * @return array
8898 function convert_to_array($var) {
8899 $result = array();
8901 // Loop over elements/properties.
8902 foreach ($var as $key => $value) {
8903 // Recursively convert objects.
8904 if (is_object($value) || is_array($value)) {
8905 $result[$key] = convert_to_array($value);
8906 } else {
8907 // Simple values are untouched.
8908 $result[$key] = $value;
8911 return $result;
8915 * Detect a custom script replacement in the data directory that will
8916 * replace an existing moodle script
8918 * @return string|bool full path name if a custom script exists, false if no custom script exists
8920 function custom_script_path() {
8921 global $CFG, $SCRIPT;
8923 if ($SCRIPT === null) {
8924 // Probably some weird external script.
8925 return false;
8928 $scriptpath = $CFG->customscripts . $SCRIPT;
8930 // Check the custom script exists.
8931 if (file_exists($scriptpath) and is_file($scriptpath)) {
8932 return $scriptpath;
8933 } else {
8934 return false;
8939 * Returns whether or not the user object is a remote MNET user. This function
8940 * is in moodlelib because it does not rely on loading any of the MNET code.
8942 * @param object $user A valid user object
8943 * @return bool True if the user is from a remote Moodle.
8945 function is_mnet_remote_user($user) {
8946 global $CFG;
8948 if (!isset($CFG->mnet_localhost_id)) {
8949 include_once($CFG->dirroot . '/mnet/lib.php');
8950 $env = new mnet_environment();
8951 $env->init();
8952 unset($env);
8955 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
8959 * This function will search for browser prefereed languages, setting Moodle
8960 * to use the best one available if $SESSION->lang is undefined
8962 function setup_lang_from_browser() {
8963 global $CFG, $SESSION, $USER;
8965 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
8966 // Lang is defined in session or user profile, nothing to do.
8967 return;
8970 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
8971 return;
8974 // Extract and clean langs from headers.
8975 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
8976 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
8977 $rawlangs = explode(',', $rawlangs); // Convert to array.
8978 $langs = array();
8980 $order = 1.0;
8981 foreach ($rawlangs as $lang) {
8982 if (strpos($lang, ';') === false) {
8983 $langs[(string)$order] = $lang;
8984 $order = $order-0.01;
8985 } else {
8986 $parts = explode(';', $lang);
8987 $pos = strpos($parts[1], '=');
8988 $langs[substr($parts[1], $pos+1)] = $parts[0];
8991 krsort($langs, SORT_NUMERIC);
8993 // Look for such langs under standard locations.
8994 foreach ($langs as $lang) {
8995 // Clean it properly for include.
8996 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
8997 if (get_string_manager()->translation_exists($lang, false)) {
8998 // Lang exists, set it in session.
8999 $SESSION->lang = $lang;
9000 // We have finished. Go out.
9001 break;
9004 return;
9008 * Check if $url matches anything in proxybypass list
9010 * Any errors just result in the proxy being used (least bad)
9012 * @param string $url url to check
9013 * @return boolean true if we should bypass the proxy
9015 function is_proxybypass( $url ) {
9016 global $CFG;
9018 // Sanity check.
9019 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9020 return false;
9023 // Get the host part out of the url.
9024 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9025 return false;
9028 // Get the possible bypass hosts into an array.
9029 $matches = explode( ',', $CFG->proxybypass );
9031 // Check for a match.
9032 // (IPs need to match the left hand side and hosts the right of the url,
9033 // but we can recklessly check both as there can't be a false +ve).
9034 foreach ($matches as $match) {
9035 $match = trim($match);
9037 // Try for IP match (Left side).
9038 $lhs = substr($host, 0, strlen($match));
9039 if (strcasecmp($match, $lhs)==0) {
9040 return true;
9043 // Try for host match (Right side).
9044 $rhs = substr($host, -strlen($match));
9045 if (strcasecmp($match, $rhs)==0) {
9046 return true;
9050 // Nothing matched.
9051 return false;
9055 * Check if the passed navigation is of the new style
9057 * @param mixed $navigation
9058 * @return bool true for yes false for no
9060 function is_newnav($navigation) {
9061 if (is_array($navigation) && !empty($navigation['newnav'])) {
9062 return true;
9063 } else {
9064 return false;
9069 * Checks whether the given variable name is defined as a variable within the given object.
9071 * This will NOT work with stdClass objects, which have no class variables.
9073 * @param string $var The variable name
9074 * @param object $object The object to check
9075 * @return boolean
9077 function in_object_vars($var, $object) {
9078 $classvars = get_class_vars(get_class($object));
9079 $classvars = array_keys($classvars);
9080 return in_array($var, $classvars);
9084 * Returns an array without repeated objects.
9085 * This function is similar to array_unique, but for arrays that have objects as values
9087 * @param array $array
9088 * @param bool $keepkeyassoc
9089 * @return array
9091 function object_array_unique($array, $keepkeyassoc = true) {
9092 $duplicatekeys = array();
9093 $tmp = array();
9095 foreach ($array as $key => $val) {
9096 // Convert objects to arrays, in_array() does not support objects.
9097 if (is_object($val)) {
9098 $val = (array)$val;
9101 if (!in_array($val, $tmp)) {
9102 $tmp[] = $val;
9103 } else {
9104 $duplicatekeys[] = $key;
9108 foreach ($duplicatekeys as $key) {
9109 unset($array[$key]);
9112 return $keepkeyassoc ? $array : array_values($array);
9116 * Is a userid the primary administrator?
9118 * @param int $userid int id of user to check
9119 * @return boolean
9121 function is_primary_admin($userid) {
9122 $primaryadmin = get_admin();
9124 if ($userid == $primaryadmin->id) {
9125 return true;
9126 } else {
9127 return false;
9132 * Returns the site identifier
9134 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9136 function get_site_identifier() {
9137 global $CFG;
9138 // Check to see if it is missing. If so, initialise it.
9139 if (empty($CFG->siteidentifier)) {
9140 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9142 // Return it.
9143 return $CFG->siteidentifier;
9147 * Check whether the given password has no more than the specified
9148 * number of consecutive identical characters.
9150 * @param string $password password to be checked against the password policy
9151 * @param integer $maxchars maximum number of consecutive identical characters
9152 * @return bool
9154 function check_consecutive_identical_characters($password, $maxchars) {
9156 if ($maxchars < 1) {
9157 return true; // Zero 0 is to disable this check.
9159 if (strlen($password) <= $maxchars) {
9160 return true; // Too short to fail this test.
9163 $previouschar = '';
9164 $consecutivecount = 1;
9165 foreach (str_split($password) as $char) {
9166 if ($char != $previouschar) {
9167 $consecutivecount = 1;
9168 } else {
9169 $consecutivecount++;
9170 if ($consecutivecount > $maxchars) {
9171 return false; // Check failed already.
9175 $previouschar = $char;
9178 return true;
9182 * Helper function to do partial function binding.
9183 * so we can use it for preg_replace_callback, for example
9184 * this works with php functions, user functions, static methods and class methods
9185 * it returns you a callback that you can pass on like so:
9187 * $callback = partial('somefunction', $arg1, $arg2);
9188 * or
9189 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9190 * or even
9191 * $obj = new someclass();
9192 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9194 * and then the arguments that are passed through at calltime are appended to the argument list.
9196 * @param mixed $function a php callback
9197 * @param mixed $arg1,... $argv arguments to partially bind with
9198 * @return array Array callback
9200 function partial() {
9201 if (!class_exists('partial')) {
9203 * Used to manage function binding.
9204 * @copyright 2009 Penny Leach
9205 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9207 class partial{
9208 /** @var array */
9209 public $values = array();
9210 /** @var string The function to call as a callback. */
9211 public $func;
9213 * Constructor
9214 * @param string $func
9215 * @param array $args
9217 public function __construct($func, $args) {
9218 $this->values = $args;
9219 $this->func = $func;
9222 * Calls the callback function.
9223 * @return mixed
9225 public function method() {
9226 $args = func_get_args();
9227 return call_user_func_array($this->func, array_merge($this->values, $args));
9231 $args = func_get_args();
9232 $func = array_shift($args);
9233 $p = new partial($func, $args);
9234 return array($p, 'method');
9238 * helper function to load up and initialise the mnet environment
9239 * this must be called before you use mnet functions.
9241 * @return mnet_environment the equivalent of old $MNET global
9243 function get_mnet_environment() {
9244 global $CFG;
9245 require_once($CFG->dirroot . '/mnet/lib.php');
9246 static $instance = null;
9247 if (empty($instance)) {
9248 $instance = new mnet_environment();
9249 $instance->init();
9251 return $instance;
9255 * during xmlrpc server code execution, any code wishing to access
9256 * information about the remote peer must use this to get it.
9258 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9260 function get_mnet_remote_client() {
9261 if (!defined('MNET_SERVER')) {
9262 debugging(get_string('notinxmlrpcserver', 'mnet'));
9263 return false;
9265 global $MNET_REMOTE_CLIENT;
9266 if (isset($MNET_REMOTE_CLIENT)) {
9267 return $MNET_REMOTE_CLIENT;
9269 return false;
9273 * during the xmlrpc server code execution, this will be called
9274 * to setup the object returned by {@link get_mnet_remote_client}
9276 * @param mnet_remote_client $client the client to set up
9277 * @throws moodle_exception
9279 function set_mnet_remote_client($client) {
9280 if (!defined('MNET_SERVER')) {
9281 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9283 global $MNET_REMOTE_CLIENT;
9284 $MNET_REMOTE_CLIENT = $client;
9288 * return the jump url for a given remote user
9289 * this is used for rewriting forum post links in emails, etc
9291 * @param stdclass $user the user to get the idp url for
9293 function mnet_get_idp_jump_url($user) {
9294 global $CFG;
9296 static $mnetjumps = array();
9297 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9298 $idp = mnet_get_peer_host($user->mnethostid);
9299 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9300 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9302 return $mnetjumps[$user->mnethostid];
9306 * Gets the homepage to use for the current user
9308 * @return int One of HOMEPAGE_*
9310 function get_home_page() {
9311 global $CFG;
9313 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9314 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9315 return HOMEPAGE_MY;
9316 } else {
9317 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9320 return HOMEPAGE_SITE;
9324 * Gets the name of a course to be displayed when showing a list of courses.
9325 * By default this is just $course->fullname but user can configure it. The
9326 * result of this function should be passed through print_string.
9327 * @param stdClass|course_in_list $course Moodle course object
9328 * @return string Display name of course (either fullname or short + fullname)
9330 function get_course_display_name_for_list($course) {
9331 global $CFG;
9332 if (!empty($CFG->courselistshortnames)) {
9333 if (!($course instanceof stdClass)) {
9334 $course = (object)convert_to_array($course);
9336 return get_string('courseextendednamedisplay', '', $course);
9337 } else {
9338 return $course->fullname;
9343 * The lang_string class
9345 * This special class is used to create an object representation of a string request.
9346 * It is special because processing doesn't occur until the object is first used.
9347 * The class was created especially to aid performance in areas where strings were
9348 * required to be generated but were not necessarily used.
9349 * As an example the admin tree when generated uses over 1500 strings, of which
9350 * normally only 1/3 are ever actually printed at any time.
9351 * The performance advantage is achieved by not actually processing strings that
9352 * arn't being used, as such reducing the processing required for the page.
9354 * How to use the lang_string class?
9355 * There are two methods of using the lang_string class, first through the
9356 * forth argument of the get_string function, and secondly directly.
9357 * The following are examples of both.
9358 * 1. Through get_string calls e.g.
9359 * $string = get_string($identifier, $component, $a, true);
9360 * $string = get_string('yes', 'moodle', null, true);
9361 * 2. Direct instantiation
9362 * $string = new lang_string($identifier, $component, $a, $lang);
9363 * $string = new lang_string('yes');
9365 * How do I use a lang_string object?
9366 * The lang_string object makes use of a magic __toString method so that you
9367 * are able to use the object exactly as you would use a string in most cases.
9368 * This means you are able to collect it into a variable and then directly
9369 * echo it, or concatenate it into another string, or similar.
9370 * The other thing you can do is manually get the string by calling the
9371 * lang_strings out method e.g.
9372 * $string = new lang_string('yes');
9373 * $string->out();
9374 * Also worth noting is that the out method can take one argument, $lang which
9375 * allows the developer to change the language on the fly.
9377 * When should I use a lang_string object?
9378 * The lang_string object is designed to be used in any situation where a
9379 * string may not be needed, but needs to be generated.
9380 * The admin tree is a good example of where lang_string objects should be
9381 * used.
9382 * A more practical example would be any class that requries strings that may
9383 * not be printed (after all classes get renderer by renderers and who knows
9384 * what they will do ;))
9386 * When should I not use a lang_string object?
9387 * Don't use lang_strings when you are going to use a string immediately.
9388 * There is no need as it will be processed immediately and there will be no
9389 * advantage, and in fact perhaps a negative hit as a class has to be
9390 * instantiated for a lang_string object, however get_string won't require
9391 * that.
9393 * Limitations:
9394 * 1. You cannot use a lang_string object as an array offset. Doing so will
9395 * result in PHP throwing an error. (You can use it as an object property!)
9397 * @package core
9398 * @category string
9399 * @copyright 2011 Sam Hemelryk
9400 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9402 class lang_string {
9404 /** @var string The strings identifier */
9405 protected $identifier;
9406 /** @var string The strings component. Default '' */
9407 protected $component = '';
9408 /** @var array|stdClass Any arguments required for the string. Default null */
9409 protected $a = null;
9410 /** @var string The language to use when processing the string. Default null */
9411 protected $lang = null;
9413 /** @var string The processed string (once processed) */
9414 protected $string = null;
9417 * A special boolean. If set to true then the object has been woken up and
9418 * cannot be regenerated. If this is set then $this->string MUST be used.
9419 * @var bool
9421 protected $forcedstring = false;
9424 * Constructs a lang_string object
9426 * This function should do as little processing as possible to ensure the best
9427 * performance for strings that won't be used.
9429 * @param string $identifier The strings identifier
9430 * @param string $component The strings component
9431 * @param stdClass|array $a Any arguments the string requires
9432 * @param string $lang The language to use when processing the string.
9433 * @throws coding_exception
9435 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9436 if (empty($component)) {
9437 $component = 'moodle';
9440 $this->identifier = $identifier;
9441 $this->component = $component;
9442 $this->lang = $lang;
9444 // We MUST duplicate $a to ensure that it if it changes by reference those
9445 // changes are not carried across.
9446 // To do this we always ensure $a or its properties/values are strings
9447 // and that any properties/values that arn't convertable are forgotten.
9448 if (!empty($a)) {
9449 if (is_scalar($a)) {
9450 $this->a = $a;
9451 } else if ($a instanceof lang_string) {
9452 $this->a = $a->out();
9453 } else if (is_object($a) or is_array($a)) {
9454 $a = (array)$a;
9455 $this->a = array();
9456 foreach ($a as $key => $value) {
9457 // Make sure conversion errors don't get displayed (results in '').
9458 if (is_array($value)) {
9459 $this->a[$key] = '';
9460 } else if (is_object($value)) {
9461 if (method_exists($value, '__toString')) {
9462 $this->a[$key] = $value->__toString();
9463 } else {
9464 $this->a[$key] = '';
9466 } else {
9467 $this->a[$key] = (string)$value;
9473 if (debugging(false, DEBUG_DEVELOPER)) {
9474 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9475 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9477 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9478 throw new coding_exception('Invalid string compontent. Please check your string definition');
9480 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9481 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9487 * Processes the string.
9489 * This function actually processes the string, stores it in the string property
9490 * and then returns it.
9491 * You will notice that this function is VERY similar to the get_string method.
9492 * That is because it is pretty much doing the same thing.
9493 * However as this function is an upgrade it isn't as tolerant to backwards
9494 * compatibility.
9496 * @return string
9497 * @throws coding_exception
9499 protected function get_string() {
9500 global $CFG;
9502 // Check if we need to process the string.
9503 if ($this->string === null) {
9504 // Check the quality of the identifier.
9505 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9506 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition', DEBUG_DEVELOPER);
9509 // Process the string.
9510 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9511 // Debugging feature lets you display string identifier and component.
9512 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9513 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9516 // Return the string.
9517 return $this->string;
9521 * Returns the string
9523 * @param string $lang The langauge to use when processing the string
9524 * @return string
9526 public function out($lang = null) {
9527 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9528 if ($this->forcedstring) {
9529 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9530 return $this->get_string();
9532 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9533 return $translatedstring->out();
9535 return $this->get_string();
9539 * Magic __toString method for printing a string
9541 * @return string
9543 public function __toString() {
9544 return $this->get_string();
9548 * Magic __set_state method used for var_export
9550 * @return string
9552 public function __set_state() {
9553 return $this->get_string();
9557 * Prepares the lang_string for sleep and stores only the forcedstring and
9558 * string properties... the string cannot be regenerated so we need to ensure
9559 * it is generated for this.
9561 * @return string
9563 public function __sleep() {
9564 $this->get_string();
9565 $this->forcedstring = true;
9566 return array('forcedstring', 'string', 'lang');