Merge branch 'MDL-66992-master' of https://github.com/tungthai/moodle
[moodle.git] / lib / moodlelib.php
blob6f4a6c08927782079e90474982efd7e621b8ca5c
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 receiving
119 * the input (required/optional_param or formslib) and then sanitise 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 * Use PARAM_LOCALISEDFLOAT instead.
142 define('PARAM_FLOAT', 'float');
145 * PARAM_LOCALISEDFLOAT - a localised real/floating point number.
146 * This is preferred over PARAM_FLOAT for numbers typed in by the user.
147 * Cleans localised numbers to computer readable numbers; false for invalid numbers.
149 define('PARAM_LOCALISEDFLOAT', 'localisedfloat');
152 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
154 define('PARAM_HOST', 'host');
157 * PARAM_INT - integers only, use when expecting only numbers.
159 define('PARAM_INT', 'int');
162 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
164 define('PARAM_LANG', 'lang');
167 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
168 * others! Implies PARAM_URL!)
170 define('PARAM_LOCALURL', 'localurl');
173 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
175 define('PARAM_NOTAGS', 'notags');
178 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
179 * traversals note: the leading slash is not removed, window drive letter is not allowed
181 define('PARAM_PATH', 'path');
184 * PARAM_PEM - Privacy Enhanced Mail format
186 define('PARAM_PEM', 'pem');
189 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
191 define('PARAM_PERMISSION', 'permission');
194 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
196 define('PARAM_RAW', 'raw');
199 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
201 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
204 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
206 define('PARAM_SAFEDIR', 'safedir');
209 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
211 define('PARAM_SAFEPATH', 'safepath');
214 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
216 define('PARAM_SEQUENCE', 'sequence');
219 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
221 define('PARAM_TAG', 'tag');
224 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
226 define('PARAM_TAGLIST', 'taglist');
229 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
231 define('PARAM_TEXT', 'text');
234 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
236 define('PARAM_THEME', 'theme');
239 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
240 * http://localhost.localdomain/ is ok.
242 define('PARAM_URL', 'url');
245 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
246 * accounts, do NOT use when syncing with external systems!!
248 define('PARAM_USERNAME', 'username');
251 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
253 define('PARAM_STRINGID', 'stringid');
255 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
257 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
258 * It was one of the first types, that is why it is abused so much ;-)
259 * @deprecated since 2.0
261 define('PARAM_CLEAN', 'clean');
264 * PARAM_INTEGER - deprecated alias for PARAM_INT
265 * @deprecated since 2.0
267 define('PARAM_INTEGER', 'int');
270 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
271 * @deprecated since 2.0
273 define('PARAM_NUMBER', 'float');
276 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
277 * NOTE: originally alias for PARAM_APLHA
278 * @deprecated since 2.0
280 define('PARAM_ACTION', 'alphanumext');
283 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
284 * NOTE: originally alias for PARAM_APLHA
285 * @deprecated since 2.0
287 define('PARAM_FORMAT', 'alphanumext');
290 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
291 * @deprecated since 2.0
293 define('PARAM_MULTILANG', 'text');
296 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
297 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
298 * America/Port-au-Prince)
300 define('PARAM_TIMEZONE', 'timezone');
303 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
305 define('PARAM_CLEANFILE', 'file');
308 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
309 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
310 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
311 * NOTE: numbers and underscores are strongly discouraged in plugin names!
313 define('PARAM_COMPONENT', 'component');
316 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
317 * It is usually used together with context id and component.
318 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
320 define('PARAM_AREA', 'area');
323 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
324 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
325 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
327 define('PARAM_PLUGIN', 'plugin');
330 // Web Services.
333 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
335 define('VALUE_REQUIRED', 1);
338 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
340 define('VALUE_OPTIONAL', 2);
343 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
345 define('VALUE_DEFAULT', 0);
348 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
350 define('NULL_NOT_ALLOWED', false);
353 * NULL_ALLOWED - the parameter can be set to null in the database
355 define('NULL_ALLOWED', true);
357 // Page types.
360 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
362 define('PAGE_COURSE_VIEW', 'course-view');
364 /** Get remote addr constant */
365 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
366 /** Get remote addr constant */
367 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
369 // Blog access level constant declaration.
370 define ('BLOG_USER_LEVEL', 1);
371 define ('BLOG_GROUP_LEVEL', 2);
372 define ('BLOG_COURSE_LEVEL', 3);
373 define ('BLOG_SITE_LEVEL', 4);
374 define ('BLOG_GLOBAL_LEVEL', 5);
377 // Tag constants.
379 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
380 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
381 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
383 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
385 define('TAG_MAX_LENGTH', 50);
387 // Password policy constants.
388 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
389 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
390 define ('PASSWORD_DIGITS', '0123456789');
391 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
393 // Feature constants.
394 // Used for plugin_supports() to report features that are, or are not, supported by a module.
396 /** True if module can provide a grade */
397 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
398 /** True if module supports outcomes */
399 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
400 /** True if module supports advanced grading methods */
401 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
402 /** True if module controls the grade visibility over the gradebook */
403 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
404 /** True if module supports plagiarism plugins */
405 define('FEATURE_PLAGIARISM', 'plagiarism');
407 /** True if module has code to track whether somebody viewed it */
408 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
409 /** True if module has custom completion rules */
410 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
412 /** True if module has no 'view' page (like label) */
413 define('FEATURE_NO_VIEW_LINK', 'viewlink');
414 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
415 define('FEATURE_IDNUMBER', 'idnumber');
416 /** True if module supports groups */
417 define('FEATURE_GROUPS', 'groups');
418 /** True if module supports groupings */
419 define('FEATURE_GROUPINGS', 'groupings');
421 * True if module supports groupmembersonly (which no longer exists)
422 * @deprecated Since Moodle 2.8
424 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
426 /** Type of module */
427 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
428 /** True if module supports intro editor */
429 define('FEATURE_MOD_INTRO', 'mod_intro');
430 /** True if module has default completion */
431 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
433 define('FEATURE_COMMENT', 'comment');
435 define('FEATURE_RATE', 'rate');
436 /** True if module supports backup/restore of moodle2 format */
437 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
439 /** True if module can show description on course main page */
440 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
442 /** True if module uses the question bank */
443 define('FEATURE_USES_QUESTIONS', 'usesquestions');
446 * Maximum filename char size
448 define('MAX_FILENAME_SIZE', 100);
450 /** Unspecified module archetype */
451 define('MOD_ARCHETYPE_OTHER', 0);
452 /** Resource-like type module */
453 define('MOD_ARCHETYPE_RESOURCE', 1);
454 /** Assignment module archetype */
455 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
456 /** System (not user-addable) module archetype */
457 define('MOD_ARCHETYPE_SYSTEM', 3);
460 * Security token used for allowing access
461 * from external application such as web services.
462 * Scripts do not use any session, performance is relatively
463 * low because we need to load access info in each request.
464 * Scripts are executed in parallel.
466 define('EXTERNAL_TOKEN_PERMANENT', 0);
469 * Security token used for allowing access
470 * of embedded applications, the code is executed in the
471 * active user session. Token is invalidated after user logs out.
472 * Scripts are executed serially - normal session locking is used.
474 define('EXTERNAL_TOKEN_EMBEDDED', 1);
477 * The home page should be the site home
479 define('HOMEPAGE_SITE', 0);
481 * The home page should be the users my page
483 define('HOMEPAGE_MY', 1);
485 * The home page can be chosen by the user
487 define('HOMEPAGE_USER', 2);
490 * URL of the Moodle sites registration portal.
492 defined('HUB_MOODLEORGHUBURL') || define('HUB_MOODLEORGHUBURL', 'https://stats.moodle.org');
495 * Moodle mobile app service name
497 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
500 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
502 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
505 * Course display settings: display all sections on one page.
507 define('COURSE_DISPLAY_SINGLEPAGE', 0);
509 * Course display settings: split pages into a page per section.
511 define('COURSE_DISPLAY_MULTIPAGE', 1);
514 * Authentication constant: String used in password field when password is not stored.
516 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
519 * Email from header to never include via information.
521 define('EMAIL_VIA_NEVER', 0);
524 * Email from header to always include via information.
526 define('EMAIL_VIA_ALWAYS', 1);
529 * Email from header to only include via information if the address is no-reply.
531 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
533 // PARAMETER HANDLING.
536 * Returns a particular value for the named variable, taken from
537 * POST or GET. If the parameter doesn't exist then an error is
538 * thrown because we require this variable.
540 * This function should be used to initialise all required values
541 * in a script that are based on parameters. Usually it will be
542 * used like this:
543 * $id = required_param('id', PARAM_INT);
545 * Please note the $type parameter is now required and the value can not be array.
547 * @param string $parname the name of the page parameter we want
548 * @param string $type expected type of parameter
549 * @return mixed
550 * @throws coding_exception
552 function required_param($parname, $type) {
553 if (func_num_args() != 2 or empty($parname) or empty($type)) {
554 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
556 // POST has precedence.
557 if (isset($_POST[$parname])) {
558 $param = $_POST[$parname];
559 } else if (isset($_GET[$parname])) {
560 $param = $_GET[$parname];
561 } else {
562 print_error('missingparam', '', '', $parname);
565 if (is_array($param)) {
566 debugging('Invalid array parameter detected in required_param(): '.$parname);
567 // TODO: switch to fatal error in Moodle 2.3.
568 return required_param_array($parname, $type);
571 return clean_param($param, $type);
575 * Returns a particular array value for the named variable, taken from
576 * POST or GET. If the parameter doesn't exist then an error is
577 * thrown because we require this variable.
579 * This function should be used to initialise all required values
580 * in a script that are based on parameters. Usually it will be
581 * used like this:
582 * $ids = required_param_array('ids', PARAM_INT);
584 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
586 * @param string $parname the name of the page parameter we want
587 * @param string $type expected type of parameter
588 * @return array
589 * @throws coding_exception
591 function required_param_array($parname, $type) {
592 if (func_num_args() != 2 or empty($parname) or empty($type)) {
593 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
595 // POST has precedence.
596 if (isset($_POST[$parname])) {
597 $param = $_POST[$parname];
598 } else if (isset($_GET[$parname])) {
599 $param = $_GET[$parname];
600 } else {
601 print_error('missingparam', '', '', $parname);
603 if (!is_array($param)) {
604 print_error('missingparam', '', '', $parname);
607 $result = array();
608 foreach ($param as $key => $value) {
609 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
610 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
611 continue;
613 $result[$key] = clean_param($value, $type);
616 return $result;
620 * Returns a particular value for the named variable, taken from
621 * POST or GET, otherwise returning a given default.
623 * This function should be used to initialise all optional values
624 * in a script that are based on parameters. Usually it will be
625 * used like this:
626 * $name = optional_param('name', 'Fred', PARAM_TEXT);
628 * Please note the $type parameter is now required and the value can not be array.
630 * @param string $parname the name of the page parameter we want
631 * @param mixed $default the default value to return if nothing is found
632 * @param string $type expected type of parameter
633 * @return mixed
634 * @throws coding_exception
636 function optional_param($parname, $default, $type) {
637 if (func_num_args() != 3 or empty($parname) or empty($type)) {
638 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
641 // POST has precedence.
642 if (isset($_POST[$parname])) {
643 $param = $_POST[$parname];
644 } else if (isset($_GET[$parname])) {
645 $param = $_GET[$parname];
646 } else {
647 return $default;
650 if (is_array($param)) {
651 debugging('Invalid array parameter detected in required_param(): '.$parname);
652 // TODO: switch to $default in Moodle 2.3.
653 return optional_param_array($parname, $default, $type);
656 return clean_param($param, $type);
660 * Returns a particular array value for the named variable, taken from
661 * POST or GET, otherwise returning a given default.
663 * This function should be used to initialise all optional values
664 * in a script that are based on parameters. Usually it will be
665 * used like this:
666 * $ids = optional_param('id', array(), PARAM_INT);
668 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
670 * @param string $parname the name of the page parameter we want
671 * @param mixed $default the default value to return if nothing is found
672 * @param string $type expected type of parameter
673 * @return array
674 * @throws coding_exception
676 function optional_param_array($parname, $default, $type) {
677 if (func_num_args() != 3 or empty($parname) or empty($type)) {
678 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
681 // POST has precedence.
682 if (isset($_POST[$parname])) {
683 $param = $_POST[$parname];
684 } else if (isset($_GET[$parname])) {
685 $param = $_GET[$parname];
686 } else {
687 return $default;
689 if (!is_array($param)) {
690 debugging('optional_param_array() expects array parameters only: '.$parname);
691 return $default;
694 $result = array();
695 foreach ($param as $key => $value) {
696 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
697 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
698 continue;
700 $result[$key] = clean_param($value, $type);
703 return $result;
707 * Strict validation of parameter values, the values are only converted
708 * to requested PHP type. Internally it is using clean_param, the values
709 * before and after cleaning must be equal - otherwise
710 * an invalid_parameter_exception is thrown.
711 * Objects and classes are not accepted.
713 * @param mixed $param
714 * @param string $type PARAM_ constant
715 * @param bool $allownull are nulls valid value?
716 * @param string $debuginfo optional debug information
717 * @return mixed the $param value converted to PHP type
718 * @throws invalid_parameter_exception if $param is not of given type
720 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
721 if (is_null($param)) {
722 if ($allownull == NULL_ALLOWED) {
723 return null;
724 } else {
725 throw new invalid_parameter_exception($debuginfo);
728 if (is_array($param) or is_object($param)) {
729 throw new invalid_parameter_exception($debuginfo);
732 $cleaned = clean_param($param, $type);
734 if ($type == PARAM_FLOAT) {
735 // Do not detect precision loss here.
736 if (is_float($param) or is_int($param)) {
737 // These always fit.
738 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
739 throw new invalid_parameter_exception($debuginfo);
741 } else if ((string)$param !== (string)$cleaned) {
742 // Conversion to string is usually lossless.
743 throw new invalid_parameter_exception($debuginfo);
746 return $cleaned;
750 * Makes sure array contains only the allowed types, this function does not validate array key names!
752 * <code>
753 * $options = clean_param($options, PARAM_INT);
754 * </code>
756 * @param array $param the variable array we are cleaning
757 * @param string $type expected format of param after cleaning.
758 * @param bool $recursive clean recursive arrays
759 * @return array
760 * @throws coding_exception
762 function clean_param_array(array $param = null, $type, $recursive = false) {
763 // Convert null to empty array.
764 $param = (array)$param;
765 foreach ($param as $key => $value) {
766 if (is_array($value)) {
767 if ($recursive) {
768 $param[$key] = clean_param_array($value, $type, true);
769 } else {
770 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
772 } else {
773 $param[$key] = clean_param($value, $type);
776 return $param;
780 * Used by {@link optional_param()} and {@link required_param()} to
781 * clean the variables and/or cast to specific types, based on
782 * an options field.
783 * <code>
784 * $course->format = clean_param($course->format, PARAM_ALPHA);
785 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
786 * </code>
788 * @param mixed $param the variable we are cleaning
789 * @param string $type expected format of param after cleaning.
790 * @return mixed
791 * @throws coding_exception
793 function clean_param($param, $type) {
794 global $CFG;
796 if (is_array($param)) {
797 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
798 } else if (is_object($param)) {
799 if (method_exists($param, '__toString')) {
800 $param = $param->__toString();
801 } else {
802 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
806 switch ($type) {
807 case PARAM_RAW:
808 // No cleaning at all.
809 $param = fix_utf8($param);
810 return $param;
812 case PARAM_RAW_TRIMMED:
813 // No cleaning, but strip leading and trailing whitespace.
814 $param = fix_utf8($param);
815 return trim($param);
817 case PARAM_CLEAN:
818 // General HTML cleaning, try to use more specific type if possible this is deprecated!
819 // Please use more specific type instead.
820 if (is_numeric($param)) {
821 return $param;
823 $param = fix_utf8($param);
824 // Sweep for scripts, etc.
825 return clean_text($param);
827 case PARAM_CLEANHTML:
828 // Clean html fragment.
829 $param = fix_utf8($param);
830 // Sweep for scripts, etc.
831 $param = clean_text($param, FORMAT_HTML);
832 return trim($param);
834 case PARAM_INT:
835 // Convert to integer.
836 return (int)$param;
838 case PARAM_FLOAT:
839 // Convert to float.
840 return (float)$param;
842 case PARAM_LOCALISEDFLOAT:
843 // Convert to float.
844 return unformat_float($param, true);
846 case PARAM_ALPHA:
847 // Remove everything not `a-z`.
848 return preg_replace('/[^a-zA-Z]/i', '', $param);
850 case PARAM_ALPHAEXT:
851 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
852 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
854 case PARAM_ALPHANUM:
855 // Remove everything not `a-zA-Z0-9`.
856 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
858 case PARAM_ALPHANUMEXT:
859 // Remove everything not `a-zA-Z0-9_-`.
860 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
862 case PARAM_SEQUENCE:
863 // Remove everything not `0-9,`.
864 return preg_replace('/[^0-9,]/i', '', $param);
866 case PARAM_BOOL:
867 // Convert to 1 or 0.
868 $tempstr = strtolower($param);
869 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
870 $param = 1;
871 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
872 $param = 0;
873 } else {
874 $param = empty($param) ? 0 : 1;
876 return $param;
878 case PARAM_NOTAGS:
879 // Strip all tags.
880 $param = fix_utf8($param);
881 return strip_tags($param);
883 case PARAM_TEXT:
884 // Leave only tags needed for multilang.
885 $param = fix_utf8($param);
886 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
887 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
888 do {
889 if (strpos($param, '</lang>') !== false) {
890 // Old and future mutilang syntax.
891 $param = strip_tags($param, '<lang>');
892 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
893 break;
895 $open = false;
896 foreach ($matches[0] as $match) {
897 if ($match === '</lang>') {
898 if ($open) {
899 $open = false;
900 continue;
901 } else {
902 break 2;
905 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
906 break 2;
907 } else {
908 $open = true;
911 if ($open) {
912 break;
914 return $param;
916 } else if (strpos($param, '</span>') !== false) {
917 // Current problematic multilang syntax.
918 $param = strip_tags($param, '<span>');
919 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
920 break;
922 $open = false;
923 foreach ($matches[0] as $match) {
924 if ($match === '</span>') {
925 if ($open) {
926 $open = false;
927 continue;
928 } else {
929 break 2;
932 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
933 break 2;
934 } else {
935 $open = true;
938 if ($open) {
939 break;
941 return $param;
943 } while (false);
944 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
945 return strip_tags($param);
947 case PARAM_COMPONENT:
948 // We do not want any guessing here, either the name is correct or not
949 // please note only normalised component names are accepted.
950 if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
951 return '';
953 if (strpos($param, '__') !== false) {
954 return '';
956 if (strpos($param, 'mod_') === 0) {
957 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
958 if (substr_count($param, '_') != 1) {
959 return '';
962 return $param;
964 case PARAM_PLUGIN:
965 case PARAM_AREA:
966 // We do not want any guessing here, either the name is correct or not.
967 if (!is_valid_plugin_name($param)) {
968 return '';
970 return $param;
972 case PARAM_SAFEDIR:
973 // Remove everything not a-zA-Z0-9_- .
974 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
976 case PARAM_SAFEPATH:
977 // Remove everything not a-zA-Z0-9/_- .
978 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
980 case PARAM_FILE:
981 // Strip all suspicious characters from filename.
982 $param = fix_utf8($param);
983 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
984 if ($param === '.' || $param === '..') {
985 $param = '';
987 return $param;
989 case PARAM_PATH:
990 // Strip all suspicious characters from file path.
991 $param = fix_utf8($param);
992 $param = str_replace('\\', '/', $param);
994 // Explode the path and clean each element using the PARAM_FILE rules.
995 $breadcrumb = explode('/', $param);
996 foreach ($breadcrumb as $key => $crumb) {
997 if ($crumb === '.' && $key === 0) {
998 // Special condition to allow for relative current path such as ./currentdirfile.txt.
999 } else {
1000 $crumb = clean_param($crumb, PARAM_FILE);
1002 $breadcrumb[$key] = $crumb;
1004 $param = implode('/', $breadcrumb);
1006 // Remove multiple current path (./././) and multiple slashes (///).
1007 $param = preg_replace('~//+~', '/', $param);
1008 $param = preg_replace('~/(\./)+~', '/', $param);
1009 return $param;
1011 case PARAM_HOST:
1012 // Allow FQDN or IPv4 dotted quad.
1013 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1014 // Match ipv4 dotted quad.
1015 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1016 // Confirm values are ok.
1017 if ( $match[0] > 255
1018 || $match[1] > 255
1019 || $match[3] > 255
1020 || $match[4] > 255 ) {
1021 // Hmmm, what kind of dotted quad is this?
1022 $param = '';
1024 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1025 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1026 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1028 // All is ok - $param is respected.
1029 } else {
1030 // All is not ok...
1031 $param='';
1033 return $param;
1035 case PARAM_URL:
1036 // Allow safe urls.
1037 $param = fix_utf8($param);
1038 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1039 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1040 // All is ok, param is respected.
1041 } else {
1042 // Not really ok.
1043 $param ='';
1045 return $param;
1047 case PARAM_LOCALURL:
1048 // Allow http absolute, root relative and relative URLs within wwwroot.
1049 $param = clean_param($param, PARAM_URL);
1050 if (!empty($param)) {
1052 if ($param === $CFG->wwwroot) {
1053 // Exact match;
1054 } else if (preg_match(':^/:', $param)) {
1055 // Root-relative, ok!
1056 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1057 // Absolute, and matches our wwwroot.
1058 } else {
1059 // Relative - let's make sure there are no tricks.
1060 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1061 // Looks ok.
1062 } else {
1063 $param = '';
1067 return $param;
1069 case PARAM_PEM:
1070 $param = trim($param);
1071 // PEM formatted strings may contain letters/numbers and the symbols:
1072 // forward slash: /
1073 // plus sign: +
1074 // equal sign: =
1075 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1076 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1077 list($wholething, $body) = $matches;
1078 unset($wholething, $matches);
1079 $b64 = clean_param($body, PARAM_BASE64);
1080 if (!empty($b64)) {
1081 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1082 } else {
1083 return '';
1086 return '';
1088 case PARAM_BASE64:
1089 if (!empty($param)) {
1090 // PEM formatted strings may contain letters/numbers and the symbols
1091 // forward slash: /
1092 // plus sign: +
1093 // equal sign: =.
1094 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1095 return '';
1097 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1098 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1099 // than (or equal to) 64 characters long.
1100 for ($i=0, $j=count($lines); $i < $j; $i++) {
1101 if ($i + 1 == $j) {
1102 if (64 < strlen($lines[$i])) {
1103 return '';
1105 continue;
1108 if (64 != strlen($lines[$i])) {
1109 return '';
1112 return implode("\n", $lines);
1113 } else {
1114 return '';
1117 case PARAM_TAG:
1118 $param = fix_utf8($param);
1119 // Please note it is not safe to use the tag name directly anywhere,
1120 // it must be processed with s(), urlencode() before embedding anywhere.
1121 // Remove some nasties.
1122 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1123 // Convert many whitespace chars into one.
1124 $param = preg_replace('/\s+/u', ' ', $param);
1125 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1126 return $param;
1128 case PARAM_TAGLIST:
1129 $param = fix_utf8($param);
1130 $tags = explode(',', $param);
1131 $result = array();
1132 foreach ($tags as $tag) {
1133 $res = clean_param($tag, PARAM_TAG);
1134 if ($res !== '') {
1135 $result[] = $res;
1138 if ($result) {
1139 return implode(',', $result);
1140 } else {
1141 return '';
1144 case PARAM_CAPABILITY:
1145 if (get_capability_info($param)) {
1146 return $param;
1147 } else {
1148 return '';
1151 case PARAM_PERMISSION:
1152 $param = (int)$param;
1153 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1154 return $param;
1155 } else {
1156 return CAP_INHERIT;
1159 case PARAM_AUTH:
1160 $param = clean_param($param, PARAM_PLUGIN);
1161 if (empty($param)) {
1162 return '';
1163 } else if (exists_auth_plugin($param)) {
1164 return $param;
1165 } else {
1166 return '';
1169 case PARAM_LANG:
1170 $param = clean_param($param, PARAM_SAFEDIR);
1171 if (get_string_manager()->translation_exists($param)) {
1172 return $param;
1173 } else {
1174 // Specified language is not installed or param malformed.
1175 return '';
1178 case PARAM_THEME:
1179 $param = clean_param($param, PARAM_PLUGIN);
1180 if (empty($param)) {
1181 return '';
1182 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1183 return $param;
1184 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1185 return $param;
1186 } else {
1187 // Specified theme is not installed.
1188 return '';
1191 case PARAM_USERNAME:
1192 $param = fix_utf8($param);
1193 $param = trim($param);
1194 // Convert uppercase to lowercase MDL-16919.
1195 $param = core_text::strtolower($param);
1196 if (empty($CFG->extendedusernamechars)) {
1197 $param = str_replace(" " , "", $param);
1198 // Regular expression, eliminate all chars EXCEPT:
1199 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1200 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1202 return $param;
1204 case PARAM_EMAIL:
1205 $param = fix_utf8($param);
1206 if (validate_email($param)) {
1207 return $param;
1208 } else {
1209 return '';
1212 case PARAM_STRINGID:
1213 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1214 return $param;
1215 } else {
1216 return '';
1219 case PARAM_TIMEZONE:
1220 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1221 $param = fix_utf8($param);
1222 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1223 if (preg_match($timezonepattern, $param)) {
1224 return $param;
1225 } else {
1226 return '';
1229 default:
1230 // Doh! throw error, switched parameters in optional_param or another serious problem.
1231 print_error("unknownparamtype", '', '', $type);
1236 * Whether the PARAM_* type is compatible in RTL.
1238 * Being compatible with RTL means that the data they contain can flow
1239 * from right-to-left or left-to-right without compromising the user experience.
1241 * Take URLs for example, they are not RTL compatible as they should always
1242 * flow from the left to the right. This also applies to numbers, email addresses,
1243 * configuration snippets, base64 strings, etc...
1245 * This function tries to best guess which parameters can contain localised strings.
1247 * @param string $paramtype Constant PARAM_*.
1248 * @return bool
1250 function is_rtl_compatible($paramtype) {
1251 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1255 * Makes sure the data is using valid utf8, invalid characters are discarded.
1257 * Note: this function is not intended for full objects with methods and private properties.
1259 * @param mixed $value
1260 * @return mixed with proper utf-8 encoding
1262 function fix_utf8($value) {
1263 if (is_null($value) or $value === '') {
1264 return $value;
1266 } else if (is_string($value)) {
1267 if ((string)(int)$value === $value) {
1268 // Shortcut.
1269 return $value;
1271 // No null bytes expected in our data, so let's remove it.
1272 $value = str_replace("\0", '', $value);
1274 // Note: this duplicates min_fix_utf8() intentionally.
1275 static $buggyiconv = null;
1276 if ($buggyiconv === null) {
1277 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1280 if ($buggyiconv) {
1281 if (function_exists('mb_convert_encoding')) {
1282 $subst = mb_substitute_character();
1283 mb_substitute_character('');
1284 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1285 mb_substitute_character($subst);
1287 } else {
1288 // Warn admins on admin/index.php page.
1289 $result = $value;
1292 } else {
1293 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1296 return $result;
1298 } else if (is_array($value)) {
1299 foreach ($value as $k => $v) {
1300 $value[$k] = fix_utf8($v);
1302 return $value;
1304 } else if (is_object($value)) {
1305 // Do not modify original.
1306 $value = clone($value);
1307 foreach ($value as $k => $v) {
1308 $value->$k = fix_utf8($v);
1310 return $value;
1312 } else {
1313 // This is some other type, no utf-8 here.
1314 return $value;
1319 * Return true if given value is integer or string with integer value
1321 * @param mixed $value String or Int
1322 * @return bool true if number, false if not
1324 function is_number($value) {
1325 if (is_int($value)) {
1326 return true;
1327 } else if (is_string($value)) {
1328 return ((string)(int)$value) === $value;
1329 } else {
1330 return false;
1335 * Returns host part from url.
1337 * @param string $url full url
1338 * @return string host, null if not found
1340 function get_host_from_url($url) {
1341 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1342 if ($matches) {
1343 return $matches[1];
1345 return null;
1349 * Tests whether anything was returned by text editor
1351 * This function is useful for testing whether something you got back from
1352 * the HTML editor actually contains anything. Sometimes the HTML editor
1353 * appear to be empty, but actually you get back a <br> tag or something.
1355 * @param string $string a string containing HTML.
1356 * @return boolean does the string contain any actual content - that is text,
1357 * images, objects, etc.
1359 function html_is_blank($string) {
1360 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1364 * Set a key in global configuration
1366 * Set a key/value pair in both this session's {@link $CFG} global variable
1367 * and in the 'config' database table for future sessions.
1369 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1370 * In that case it doesn't affect $CFG.
1372 * A NULL value will delete the entry.
1374 * NOTE: this function is called from lib/db/upgrade.php
1376 * @param string $name the key to set
1377 * @param string $value the value to set (without magic quotes)
1378 * @param string $plugin (optional) the plugin scope, default null
1379 * @return bool true or exception
1381 function set_config($name, $value, $plugin=null) {
1382 global $CFG, $DB;
1384 if (empty($plugin)) {
1385 if (!array_key_exists($name, $CFG->config_php_settings)) {
1386 // So it's defined for this invocation at least.
1387 if (is_null($value)) {
1388 unset($CFG->$name);
1389 } else {
1390 // Settings from db are always strings.
1391 $CFG->$name = (string)$value;
1395 if ($DB->get_field('config', 'name', array('name' => $name))) {
1396 if ($value === null) {
1397 $DB->delete_records('config', array('name' => $name));
1398 } else {
1399 $DB->set_field('config', 'value', $value, array('name' => $name));
1401 } else {
1402 if ($value !== null) {
1403 $config = new stdClass();
1404 $config->name = $name;
1405 $config->value = $value;
1406 $DB->insert_record('config', $config, false);
1408 // When setting config during a Behat test (in the CLI script, not in the web browser
1409 // requests), remember which ones are set so that we can clear them later.
1410 if (defined('BEHAT_TEST')) {
1411 if (!property_exists($CFG, 'behat_cli_added_config')) {
1412 $CFG->behat_cli_added_config = [];
1414 $CFG->behat_cli_added_config[$name] = true;
1417 if ($name === 'siteidentifier') {
1418 cache_helper::update_site_identifier($value);
1420 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1421 } else {
1422 // Plugin scope.
1423 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1424 if ($value===null) {
1425 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1426 } else {
1427 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1429 } else {
1430 if ($value !== null) {
1431 $config = new stdClass();
1432 $config->plugin = $plugin;
1433 $config->name = $name;
1434 $config->value = $value;
1435 $DB->insert_record('config_plugins', $config, false);
1438 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1441 return true;
1445 * Get configuration values from the global config table
1446 * or the config_plugins table.
1448 * If called with one parameter, it will load all the config
1449 * variables for one plugin, and return them as an object.
1451 * If called with 2 parameters it will return a string single
1452 * value or false if the value is not found.
1454 * NOTE: this function is called from lib/db/upgrade.php
1456 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1457 * that we need only fetch it once per request.
1458 * @param string $plugin full component name
1459 * @param string $name default null
1460 * @return mixed hash-like object or single value, return false no config found
1461 * @throws dml_exception
1463 function get_config($plugin, $name = null) {
1464 global $CFG, $DB;
1466 static $siteidentifier = null;
1468 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1469 $forced =& $CFG->config_php_settings;
1470 $iscore = true;
1471 $plugin = 'core';
1472 } else {
1473 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1474 $forced =& $CFG->forced_plugin_settings[$plugin];
1475 } else {
1476 $forced = array();
1478 $iscore = false;
1481 if ($siteidentifier === null) {
1482 try {
1483 // This may fail during installation.
1484 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1485 // install the database.
1486 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1487 } catch (dml_exception $ex) {
1488 // Set siteidentifier to false. We don't want to trip this continually.
1489 $siteidentifier = false;
1490 throw $ex;
1494 if (!empty($name)) {
1495 if (array_key_exists($name, $forced)) {
1496 return (string)$forced[$name];
1497 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1498 return $siteidentifier;
1502 $cache = cache::make('core', 'config');
1503 $result = $cache->get($plugin);
1504 if ($result === false) {
1505 // The user is after a recordset.
1506 if (!$iscore) {
1507 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1508 } else {
1509 // This part is not really used any more, but anyway...
1510 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1512 $cache->set($plugin, $result);
1515 if (!empty($name)) {
1516 if (array_key_exists($name, $result)) {
1517 return $result[$name];
1519 return false;
1522 if ($plugin === 'core') {
1523 $result['siteidentifier'] = $siteidentifier;
1526 foreach ($forced as $key => $value) {
1527 if (is_null($value) or is_array($value) or is_object($value)) {
1528 // We do not want any extra mess here, just real settings that could be saved in db.
1529 unset($result[$key]);
1530 } else {
1531 // Convert to string as if it went through the DB.
1532 $result[$key] = (string)$value;
1536 return (object)$result;
1540 * Removes a key from global configuration.
1542 * NOTE: this function is called from lib/db/upgrade.php
1544 * @param string $name the key to set
1545 * @param string $plugin (optional) the plugin scope
1546 * @return boolean whether the operation succeeded.
1548 function unset_config($name, $plugin=null) {
1549 global $CFG, $DB;
1551 if (empty($plugin)) {
1552 unset($CFG->$name);
1553 $DB->delete_records('config', array('name' => $name));
1554 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1555 } else {
1556 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1557 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1560 return true;
1564 * Remove all the config variables for a given plugin.
1566 * NOTE: this function is called from lib/db/upgrade.php
1568 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1569 * @return boolean whether the operation succeeded.
1571 function unset_all_config_for_plugin($plugin) {
1572 global $DB;
1573 // Delete from the obvious config_plugins first.
1574 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1575 // Next delete any suspect settings from config.
1576 $like = $DB->sql_like('name', '?', true, true, false, '|');
1577 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1578 $DB->delete_records_select('config', $like, $params);
1579 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1580 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1582 return true;
1586 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1588 * All users are verified if they still have the necessary capability.
1590 * @param string $value the value of the config setting.
1591 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1592 * @param bool $includeadmins include administrators.
1593 * @return array of user objects.
1595 function get_users_from_config($value, $capability, $includeadmins = true) {
1596 if (empty($value) or $value === '$@NONE@$') {
1597 return array();
1600 // We have to make sure that users still have the necessary capability,
1601 // it should be faster to fetch them all first and then test if they are present
1602 // instead of validating them one-by-one.
1603 $users = get_users_by_capability(context_system::instance(), $capability);
1604 if ($includeadmins) {
1605 $admins = get_admins();
1606 foreach ($admins as $admin) {
1607 $users[$admin->id] = $admin;
1611 if ($value === '$@ALL@$') {
1612 return $users;
1615 $result = array(); // Result in correct order.
1616 $allowed = explode(',', $value);
1617 foreach ($allowed as $uid) {
1618 if (isset($users[$uid])) {
1619 $user = $users[$uid];
1620 $result[$user->id] = $user;
1624 return $result;
1629 * Invalidates browser caches and cached data in temp.
1631 * @return void
1633 function purge_all_caches() {
1634 purge_caches();
1638 * Selectively invalidate different types of cache.
1640 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1641 * areas alone or in combination.
1643 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1644 * 'muc' Purge MUC caches?
1645 * 'theme' Purge theme cache?
1646 * 'lang' Purge language string cache?
1647 * 'js' Purge javascript cache?
1648 * 'filter' Purge text filter cache?
1649 * 'other' Purge all other caches?
1651 function purge_caches($options = []) {
1652 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1653 if (empty(array_filter($options))) {
1654 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1655 } else {
1656 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1658 if ($options['muc']) {
1659 cache_helper::purge_all();
1661 if ($options['theme']) {
1662 theme_reset_all_caches();
1664 if ($options['lang']) {
1665 get_string_manager()->reset_caches();
1667 if ($options['js']) {
1668 js_reset_all_caches();
1670 if ($options['template']) {
1671 template_reset_all_caches();
1673 if ($options['filter']) {
1674 reset_text_filters_cache();
1676 if ($options['other']) {
1677 purge_other_caches();
1682 * Purge all non-MUC caches not otherwise purged in purge_caches.
1684 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1685 * {@link phpunit_util::reset_dataroot()}
1687 function purge_other_caches() {
1688 global $DB, $CFG;
1689 core_text::reset_caches();
1690 if (class_exists('core_plugin_manager')) {
1691 core_plugin_manager::reset_caches();
1694 // Bump up cacherev field for all courses.
1695 try {
1696 increment_revision_number('course', 'cacherev', '');
1697 } catch (moodle_exception $e) {
1698 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1701 $DB->reset_caches();
1703 // Purge all other caches: rss, simplepie, etc.
1704 clearstatcache();
1705 remove_dir($CFG->cachedir.'', true);
1707 // Make sure cache dir is writable, throws exception if not.
1708 make_cache_directory('');
1710 // This is the only place where we purge local caches, we are only adding files there.
1711 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1712 remove_dir($CFG->localcachedir, true);
1713 set_config('localcachedirpurged', time());
1714 make_localcache_directory('', true);
1715 \core\task\manager::clear_static_caches();
1719 * Get volatile flags
1721 * @param string $type
1722 * @param int $changedsince default null
1723 * @return array records array
1725 function get_cache_flags($type, $changedsince = null) {
1726 global $DB;
1728 $params = array('type' => $type, 'expiry' => time());
1729 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1730 if ($changedsince !== null) {
1731 $params['changedsince'] = $changedsince;
1732 $sqlwhere .= " AND timemodified > :changedsince";
1734 $cf = array();
1735 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1736 foreach ($flags as $flag) {
1737 $cf[$flag->name] = $flag->value;
1740 return $cf;
1744 * Get volatile flags
1746 * @param string $type
1747 * @param string $name
1748 * @param int $changedsince default null
1749 * @return string|false The cache flag value or false
1751 function get_cache_flag($type, $name, $changedsince=null) {
1752 global $DB;
1754 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1756 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1757 if ($changedsince !== null) {
1758 $params['changedsince'] = $changedsince;
1759 $sqlwhere .= " AND timemodified > :changedsince";
1762 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1766 * Set a volatile flag
1768 * @param string $type the "type" namespace for the key
1769 * @param string $name the key to set
1770 * @param string $value the value to set (without magic quotes) - null will remove the flag
1771 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1772 * @return bool Always returns true
1774 function set_cache_flag($type, $name, $value, $expiry = null) {
1775 global $DB;
1777 $timemodified = time();
1778 if ($expiry === null || $expiry < $timemodified) {
1779 $expiry = $timemodified + 24 * 60 * 60;
1780 } else {
1781 $expiry = (int)$expiry;
1784 if ($value === null) {
1785 unset_cache_flag($type, $name);
1786 return true;
1789 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1790 // This is a potential problem in DEBUG_DEVELOPER.
1791 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1792 return true; // No need to update.
1794 $f->value = $value;
1795 $f->expiry = $expiry;
1796 $f->timemodified = $timemodified;
1797 $DB->update_record('cache_flags', $f);
1798 } else {
1799 $f = new stdClass();
1800 $f->flagtype = $type;
1801 $f->name = $name;
1802 $f->value = $value;
1803 $f->expiry = $expiry;
1804 $f->timemodified = $timemodified;
1805 $DB->insert_record('cache_flags', $f);
1807 return true;
1811 * Removes a single volatile flag
1813 * @param string $type the "type" namespace for the key
1814 * @param string $name the key to set
1815 * @return bool
1817 function unset_cache_flag($type, $name) {
1818 global $DB;
1819 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1820 return true;
1824 * Garbage-collect volatile flags
1826 * @return bool Always returns true
1828 function gc_cache_flags() {
1829 global $DB;
1830 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1831 return true;
1834 // USER PREFERENCE API.
1837 * Refresh user preference cache. This is used most often for $USER
1838 * object that is stored in session, but it also helps with performance in cron script.
1840 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1842 * @package core
1843 * @category preference
1844 * @access public
1845 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1846 * @param int $cachelifetime Cache life time on the current page (in seconds)
1847 * @throws coding_exception
1848 * @return null
1850 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1851 global $DB;
1852 // Static cache, we need to check on each page load, not only every 2 minutes.
1853 static $loadedusers = array();
1855 if (!isset($user->id)) {
1856 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1859 if (empty($user->id) or isguestuser($user->id)) {
1860 // No permanent storage for not-logged-in users and guest.
1861 if (!isset($user->preference)) {
1862 $user->preference = array();
1864 return;
1867 $timenow = time();
1869 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1870 // Already loaded at least once on this page. Are we up to date?
1871 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1872 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1873 return;
1875 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1876 // No change since the lastcheck on this page.
1877 $user->preference['_lastloaded'] = $timenow;
1878 return;
1882 // OK, so we have to reload all preferences.
1883 $loadedusers[$user->id] = true;
1884 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1885 $user->preference['_lastloaded'] = $timenow;
1889 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1891 * NOTE: internal function, do not call from other code.
1893 * @package core
1894 * @access private
1895 * @param integer $userid the user whose prefs were changed.
1897 function mark_user_preferences_changed($userid) {
1898 global $CFG;
1900 if (empty($userid) or isguestuser($userid)) {
1901 // No cache flags for guest and not-logged-in users.
1902 return;
1905 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1909 * Sets a preference for the specified user.
1911 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1913 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1915 * @package core
1916 * @category preference
1917 * @access public
1918 * @param string $name The key to set as preference for the specified user
1919 * @param string $value The value to set for the $name key in the specified user's
1920 * record, null means delete current value.
1921 * @param stdClass|int|null $user A moodle user object or id, null means current user
1922 * @throws coding_exception
1923 * @return bool Always true or exception
1925 function set_user_preference($name, $value, $user = null) {
1926 global $USER, $DB;
1928 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1929 throw new coding_exception('Invalid preference name in set_user_preference() call');
1932 if (is_null($value)) {
1933 // Null means delete current.
1934 return unset_user_preference($name, $user);
1935 } else if (is_object($value)) {
1936 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1937 } else if (is_array($value)) {
1938 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1940 // Value column maximum length is 1333 characters.
1941 $value = (string)$value;
1942 if (core_text::strlen($value) > 1333) {
1943 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1946 if (is_null($user)) {
1947 $user = $USER;
1948 } else if (isset($user->id)) {
1949 // It is a valid object.
1950 } else if (is_numeric($user)) {
1951 $user = (object)array('id' => (int)$user);
1952 } else {
1953 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1956 check_user_preferences_loaded($user);
1958 if (empty($user->id) or isguestuser($user->id)) {
1959 // No permanent storage for not-logged-in users and guest.
1960 $user->preference[$name] = $value;
1961 return true;
1964 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1965 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1966 // Preference already set to this value.
1967 return true;
1969 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1971 } else {
1972 $preference = new stdClass();
1973 $preference->userid = $user->id;
1974 $preference->name = $name;
1975 $preference->value = $value;
1976 $DB->insert_record('user_preferences', $preference);
1979 // Update value in cache.
1980 $user->preference[$name] = $value;
1981 // Update the $USER in case where we've not a direct reference to $USER.
1982 if ($user !== $USER && $user->id == $USER->id) {
1983 $USER->preference[$name] = $value;
1986 // Set reload flag for other sessions.
1987 mark_user_preferences_changed($user->id);
1989 return true;
1993 * Sets a whole array of preferences for the current user
1995 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1997 * @package core
1998 * @category preference
1999 * @access public
2000 * @param array $prefarray An array of key/value pairs to be set
2001 * @param stdClass|int|null $user A moodle user object or id, null means current user
2002 * @return bool Always true or exception
2004 function set_user_preferences(array $prefarray, $user = null) {
2005 foreach ($prefarray as $name => $value) {
2006 set_user_preference($name, $value, $user);
2008 return true;
2012 * Unsets a preference completely by deleting it from the database
2014 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2016 * @package core
2017 * @category preference
2018 * @access public
2019 * @param string $name The key to unset as preference for the specified user
2020 * @param stdClass|int|null $user A moodle user object or id, null means current user
2021 * @throws coding_exception
2022 * @return bool Always true or exception
2024 function unset_user_preference($name, $user = null) {
2025 global $USER, $DB;
2027 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2028 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2031 if (is_null($user)) {
2032 $user = $USER;
2033 } else if (isset($user->id)) {
2034 // It is a valid object.
2035 } else if (is_numeric($user)) {
2036 $user = (object)array('id' => (int)$user);
2037 } else {
2038 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2041 check_user_preferences_loaded($user);
2043 if (empty($user->id) or isguestuser($user->id)) {
2044 // No permanent storage for not-logged-in user and guest.
2045 unset($user->preference[$name]);
2046 return true;
2049 // Delete from DB.
2050 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2052 // Delete the preference from cache.
2053 unset($user->preference[$name]);
2054 // Update the $USER in case where we've not a direct reference to $USER.
2055 if ($user !== $USER && $user->id == $USER->id) {
2056 unset($USER->preference[$name]);
2059 // Set reload flag for other sessions.
2060 mark_user_preferences_changed($user->id);
2062 return true;
2066 * Used to fetch user preference(s)
2068 * If no arguments are supplied this function will return
2069 * all of the current user preferences as an array.
2071 * If a name is specified then this function
2072 * attempts to return that particular preference value. If
2073 * none is found, then the optional value $default is returned,
2074 * otherwise null.
2076 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2078 * @package core
2079 * @category preference
2080 * @access public
2081 * @param string $name Name of the key to use in finding a preference value
2082 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2083 * @param stdClass|int|null $user A moodle user object or id, null means current user
2084 * @throws coding_exception
2085 * @return string|mixed|null A string containing the value of a single preference. An
2086 * array with all of the preferences or null
2088 function get_user_preferences($name = null, $default = null, $user = null) {
2089 global $USER;
2091 if (is_null($name)) {
2092 // All prefs.
2093 } else if (is_numeric($name) or $name === '_lastloaded') {
2094 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2097 if (is_null($user)) {
2098 $user = $USER;
2099 } else if (isset($user->id)) {
2100 // Is a valid object.
2101 } else if (is_numeric($user)) {
2102 if ($USER->id == $user) {
2103 $user = $USER;
2104 } else {
2105 $user = (object)array('id' => (int)$user);
2107 } else {
2108 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2111 check_user_preferences_loaded($user);
2113 if (empty($name)) {
2114 // All values.
2115 return $user->preference;
2116 } else if (isset($user->preference[$name])) {
2117 // The single string value.
2118 return $user->preference[$name];
2119 } else {
2120 // Default value (null if not specified).
2121 return $default;
2125 // FUNCTIONS FOR HANDLING TIME.
2128 * Given Gregorian date parts in user time produce a GMT timestamp.
2130 * @package core
2131 * @category time
2132 * @param int $year The year part to create timestamp of
2133 * @param int $month The month part to create timestamp of
2134 * @param int $day The day part to create timestamp of
2135 * @param int $hour The hour part to create timestamp of
2136 * @param int $minute The minute part to create timestamp of
2137 * @param int $second The second part to create timestamp of
2138 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2139 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2140 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2141 * applied only if timezone is 99 or string.
2142 * @return int GMT timestamp
2144 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2145 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2146 $date->setDate((int)$year, (int)$month, (int)$day);
2147 $date->setTime((int)$hour, (int)$minute, (int)$second);
2149 $time = $date->getTimestamp();
2151 if ($time === false) {
2152 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2153 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2156 // Moodle BC DST stuff.
2157 if (!$applydst) {
2158 $time += dst_offset_on($time, $timezone);
2161 return $time;
2166 * Format a date/time (seconds) as weeks, days, hours etc as needed
2168 * Given an amount of time in seconds, returns string
2169 * formatted nicely as years, days, hours etc as needed
2171 * @package core
2172 * @category time
2173 * @uses MINSECS
2174 * @uses HOURSECS
2175 * @uses DAYSECS
2176 * @uses YEARSECS
2177 * @param int $totalsecs Time in seconds
2178 * @param stdClass $str Should be a time object
2179 * @return string A nicely formatted date/time string
2181 function format_time($totalsecs, $str = null) {
2183 $totalsecs = abs($totalsecs);
2185 if (!$str) {
2186 // Create the str structure the slow way.
2187 $str = new stdClass();
2188 $str->day = get_string('day');
2189 $str->days = get_string('days');
2190 $str->hour = get_string('hour');
2191 $str->hours = get_string('hours');
2192 $str->min = get_string('min');
2193 $str->mins = get_string('mins');
2194 $str->sec = get_string('sec');
2195 $str->secs = get_string('secs');
2196 $str->year = get_string('year');
2197 $str->years = get_string('years');
2200 $years = floor($totalsecs/YEARSECS);
2201 $remainder = $totalsecs - ($years*YEARSECS);
2202 $days = floor($remainder/DAYSECS);
2203 $remainder = $totalsecs - ($days*DAYSECS);
2204 $hours = floor($remainder/HOURSECS);
2205 $remainder = $remainder - ($hours*HOURSECS);
2206 $mins = floor($remainder/MINSECS);
2207 $secs = $remainder - ($mins*MINSECS);
2209 $ss = ($secs == 1) ? $str->sec : $str->secs;
2210 $sm = ($mins == 1) ? $str->min : $str->mins;
2211 $sh = ($hours == 1) ? $str->hour : $str->hours;
2212 $sd = ($days == 1) ? $str->day : $str->days;
2213 $sy = ($years == 1) ? $str->year : $str->years;
2215 $oyears = '';
2216 $odays = '';
2217 $ohours = '';
2218 $omins = '';
2219 $osecs = '';
2221 if ($years) {
2222 $oyears = $years .' '. $sy;
2224 if ($days) {
2225 $odays = $days .' '. $sd;
2227 if ($hours) {
2228 $ohours = $hours .' '. $sh;
2230 if ($mins) {
2231 $omins = $mins .' '. $sm;
2233 if ($secs) {
2234 $osecs = $secs .' '. $ss;
2237 if ($years) {
2238 return trim($oyears .' '. $odays);
2240 if ($days) {
2241 return trim($odays .' '. $ohours);
2243 if ($hours) {
2244 return trim($ohours .' '. $omins);
2246 if ($mins) {
2247 return trim($omins .' '. $osecs);
2249 if ($secs) {
2250 return $osecs;
2252 return get_string('now');
2256 * Returns a formatted string that represents a date in user time.
2258 * @package core
2259 * @category time
2260 * @param int $date the timestamp in UTC, as obtained from the database.
2261 * @param string $format strftime format. You should probably get this using
2262 * get_string('strftime...', 'langconfig');
2263 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2264 * not 99 then daylight saving will not be added.
2265 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2266 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2267 * If false then the leading zero is maintained.
2268 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2269 * @return string the formatted date/time.
2271 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2272 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2273 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2277 * Returns a html "time" tag with both the exact user date with timezone information
2278 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2280 * @package core
2281 * @category time
2282 * @param int $date the timestamp in UTC, as obtained from the database.
2283 * @param string $format strftime format. You should probably get this using
2284 * get_string('strftime...', 'langconfig');
2285 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2286 * not 99 then daylight saving will not be added.
2287 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2288 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2289 * If false then the leading zero is maintained.
2290 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2291 * @return string the formatted date/time.
2293 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2294 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2295 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2296 return $userdatestr;
2298 $machinedate = new DateTime();
2299 $machinedate->setTimestamp(intval($date));
2300 $machinedate->setTimezone(core_date::get_user_timezone_object());
2302 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2306 * Returns a formatted date ensuring it is UTF-8.
2308 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2309 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2311 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2312 * @param string $format strftime format.
2313 * @param int|float|string $tz the user timezone
2314 * @return string the formatted date/time.
2315 * @since Moodle 2.3.3
2317 function date_format_string($date, $format, $tz = 99) {
2318 global $CFG;
2320 $localewincharset = null;
2321 // Get the calendar type user is using.
2322 if ($CFG->ostype == 'WINDOWS') {
2323 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2324 $localewincharset = $calendartype->locale_win_charset();
2327 if ($localewincharset) {
2328 $format = core_text::convert($format, 'utf-8', $localewincharset);
2331 date_default_timezone_set(core_date::get_user_timezone($tz));
2332 $datestring = strftime($format, $date);
2333 core_date::set_default_server_timezone();
2335 if ($localewincharset) {
2336 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2339 return $datestring;
2343 * Given a $time timestamp in GMT (seconds since epoch),
2344 * returns an array that represents the Gregorian date in user time
2346 * @package core
2347 * @category time
2348 * @param int $time Timestamp in GMT
2349 * @param float|int|string $timezone user timezone
2350 * @return array An array that represents the date in user time
2352 function usergetdate($time, $timezone=99) {
2353 date_default_timezone_set(core_date::get_user_timezone($timezone));
2354 $result = getdate($time);
2355 core_date::set_default_server_timezone();
2357 return $result;
2361 * Given a GMT timestamp (seconds since epoch), offsets it by
2362 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2364 * NOTE: this function does not include DST properly,
2365 * you should use the PHP date stuff instead!
2367 * @package core
2368 * @category time
2369 * @param int $date Timestamp in GMT
2370 * @param float|int|string $timezone user timezone
2371 * @return int
2373 function usertime($date, $timezone=99) {
2374 $userdate = new DateTime('@' . $date);
2375 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2376 $dst = dst_offset_on($date, $timezone);
2378 return $date - $userdate->getOffset() + $dst;
2382 * Get a formatted string representation of an interval between two unix timestamps.
2384 * E.g.
2385 * $intervalstring = get_time_interval_string(12345600, 12345660);
2386 * Will produce the string:
2387 * '0d 0h 1m'
2389 * @param int $time1 unix timestamp
2390 * @param int $time2 unix timestamp
2391 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2392 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2394 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2395 $dtdate = new DateTime();
2396 $dtdate->setTimeStamp($time1);
2397 $dtdate2 = new DateTime();
2398 $dtdate2->setTimeStamp($time2);
2399 $interval = $dtdate2->diff($dtdate);
2400 $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2401 return $interval->format($format);
2405 * Given a time, return the GMT timestamp of the most recent midnight
2406 * for the current user.
2408 * @package core
2409 * @category time
2410 * @param int $date Timestamp in GMT
2411 * @param float|int|string $timezone user timezone
2412 * @return int Returns a GMT timestamp
2414 function usergetmidnight($date, $timezone=99) {
2416 $userdate = usergetdate($date, $timezone);
2418 // Time of midnight of this user's day, in GMT.
2419 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2424 * Returns a string that prints the user's timezone
2426 * @package core
2427 * @category time
2428 * @param float|int|string $timezone user timezone
2429 * @return string
2431 function usertimezone($timezone=99) {
2432 $tz = core_date::get_user_timezone($timezone);
2433 return core_date::get_localised_timezone($tz);
2437 * Returns a float or a string which denotes the user's timezone
2438 * 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)
2439 * means that for this timezone there are also DST rules to be taken into account
2440 * Checks various settings and picks the most dominant of those which have a value
2442 * @package core
2443 * @category time
2444 * @param float|int|string $tz timezone to calculate GMT time offset before
2445 * calculating user timezone, 99 is default user timezone
2446 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2447 * @return float|string
2449 function get_user_timezone($tz = 99) {
2450 global $USER, $CFG;
2452 $timezones = array(
2453 $tz,
2454 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2455 isset($USER->timezone) ? $USER->timezone : 99,
2456 isset($CFG->timezone) ? $CFG->timezone : 99,
2459 $tz = 99;
2461 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2462 foreach ($timezones as $nextvalue) {
2463 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2464 $tz = $nextvalue;
2467 return is_numeric($tz) ? (float) $tz : $tz;
2471 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2472 * - Note: Daylight saving only works for string timezones and not for float.
2474 * @package core
2475 * @category time
2476 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2477 * @param int|float|string $strtimezone user timezone
2478 * @return int
2480 function dst_offset_on($time, $strtimezone = null) {
2481 $tz = core_date::get_user_timezone($strtimezone);
2482 $date = new DateTime('@' . $time);
2483 $date->setTimezone(new DateTimeZone($tz));
2484 if ($date->format('I') == '1') {
2485 if ($tz === 'Australia/Lord_Howe') {
2486 return 1800;
2488 return 3600;
2490 return 0;
2494 * Calculates when the day appears in specific month
2496 * @package core
2497 * @category time
2498 * @param int $startday starting day of the month
2499 * @param int $weekday The day when week starts (normally taken from user preferences)
2500 * @param int $month The month whose day is sought
2501 * @param int $year The year of the month whose day is sought
2502 * @return int
2504 function find_day_in_month($startday, $weekday, $month, $year) {
2505 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2507 $daysinmonth = days_in_month($month, $year);
2508 $daysinweek = count($calendartype->get_weekdays());
2510 if ($weekday == -1) {
2511 // Don't care about weekday, so return:
2512 // abs($startday) if $startday != -1
2513 // $daysinmonth otherwise.
2514 return ($startday == -1) ? $daysinmonth : abs($startday);
2517 // From now on we 're looking for a specific weekday.
2518 // Give "end of month" its actual value, since we know it.
2519 if ($startday == -1) {
2520 $startday = -1 * $daysinmonth;
2523 // Starting from day $startday, the sign is the direction.
2524 if ($startday < 1) {
2525 $startday = abs($startday);
2526 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2528 // This is the last such weekday of the month.
2529 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2530 if ($lastinmonth > $daysinmonth) {
2531 $lastinmonth -= $daysinweek;
2534 // Find the first such weekday <= $startday.
2535 while ($lastinmonth > $startday) {
2536 $lastinmonth -= $daysinweek;
2539 return $lastinmonth;
2540 } else {
2541 $indexweekday = dayofweek($startday, $month, $year);
2543 $diff = $weekday - $indexweekday;
2544 if ($diff < 0) {
2545 $diff += $daysinweek;
2548 // This is the first such weekday of the month equal to or after $startday.
2549 $firstfromindex = $startday + $diff;
2551 return $firstfromindex;
2556 * Calculate the number of days in a given month
2558 * @package core
2559 * @category time
2560 * @param int $month The month whose day count is sought
2561 * @param int $year The year of the month whose day count is sought
2562 * @return int
2564 function days_in_month($month, $year) {
2565 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2566 return $calendartype->get_num_days_in_month($year, $month);
2570 * Calculate the position in the week of a specific calendar day
2572 * @package core
2573 * @category time
2574 * @param int $day The day of the date whose position in the week is sought
2575 * @param int $month The month of the date whose position in the week is sought
2576 * @param int $year The year of the date whose position in the week is sought
2577 * @return int
2579 function dayofweek($day, $month, $year) {
2580 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2581 return $calendartype->get_weekday($year, $month, $day);
2584 // USER AUTHENTICATION AND LOGIN.
2587 * Returns full login url.
2589 * Any form submissions for authentication to this URL must include username,
2590 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2592 * @return string login url
2594 function get_login_url() {
2595 global $CFG;
2597 return "$CFG->wwwroot/login/index.php";
2601 * This function checks that the current user is logged in and has the
2602 * required privileges
2604 * This function checks that the current user is logged in, and optionally
2605 * whether they are allowed to be in a particular course and view a particular
2606 * course module.
2607 * If they are not logged in, then it redirects them to the site login unless
2608 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2609 * case they are automatically logged in as guests.
2610 * If $courseid is given and the user is not enrolled in that course then the
2611 * user is redirected to the course enrolment page.
2612 * If $cm is given and the course module is hidden and the user is not a teacher
2613 * in the course then the user is redirected to the course home page.
2615 * When $cm parameter specified, this function sets page layout to 'module'.
2616 * You need to change it manually later if some other layout needed.
2618 * @package core_access
2619 * @category access
2621 * @param mixed $courseorid id of the course or course object
2622 * @param bool $autologinguest default true
2623 * @param object $cm course module object
2624 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2625 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2626 * in order to keep redirects working properly. MDL-14495
2627 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2628 * @return mixed Void, exit, and die depending on path
2629 * @throws coding_exception
2630 * @throws require_login_exception
2631 * @throws moodle_exception
2633 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2634 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2636 // Must not redirect when byteserving already started.
2637 if (!empty($_SERVER['HTTP_RANGE'])) {
2638 $preventredirect = true;
2641 if (AJAX_SCRIPT) {
2642 // We cannot redirect for AJAX scripts either.
2643 $preventredirect = true;
2646 // Setup global $COURSE, themes, language and locale.
2647 if (!empty($courseorid)) {
2648 if (is_object($courseorid)) {
2649 $course = $courseorid;
2650 } else if ($courseorid == SITEID) {
2651 $course = clone($SITE);
2652 } else {
2653 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2655 if ($cm) {
2656 if ($cm->course != $course->id) {
2657 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2659 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2660 if (!($cm instanceof cm_info)) {
2661 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2662 // db queries so this is not really a performance concern, however it is obviously
2663 // better if you use get_fast_modinfo to get the cm before calling this.
2664 $modinfo = get_fast_modinfo($course);
2665 $cm = $modinfo->get_cm($cm->id);
2668 } else {
2669 // Do not touch global $COURSE via $PAGE->set_course(),
2670 // the reasons is we need to be able to call require_login() at any time!!
2671 $course = $SITE;
2672 if ($cm) {
2673 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2677 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2678 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2679 // risk leading the user back to the AJAX request URL.
2680 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2681 $setwantsurltome = false;
2684 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2685 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2686 if ($preventredirect) {
2687 throw new require_login_session_timeout_exception();
2688 } else {
2689 if ($setwantsurltome) {
2690 $SESSION->wantsurl = qualified_me();
2692 redirect(get_login_url());
2696 // If the user is not even logged in yet then make sure they are.
2697 if (!isloggedin()) {
2698 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2699 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2700 // Misconfigured site guest, just redirect to login page.
2701 redirect(get_login_url());
2702 exit; // Never reached.
2704 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2705 complete_user_login($guest);
2706 $USER->autologinguest = true;
2707 $SESSION->lang = $lang;
2708 } else {
2709 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2710 if ($preventredirect) {
2711 throw new require_login_exception('You are not logged in');
2714 if ($setwantsurltome) {
2715 $SESSION->wantsurl = qualified_me();
2718 $referer = get_local_referer(false);
2719 if (!empty($referer)) {
2720 $SESSION->fromurl = $referer;
2723 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2724 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2725 foreach($authsequence as $authname) {
2726 $authplugin = get_auth_plugin($authname);
2727 $authplugin->pre_loginpage_hook();
2728 if (isloggedin()) {
2729 if ($cm) {
2730 $modinfo = get_fast_modinfo($course);
2731 $cm = $modinfo->get_cm($cm->id);
2733 set_access_log_user();
2734 break;
2738 // If we're still not logged in then go to the login page
2739 if (!isloggedin()) {
2740 redirect(get_login_url());
2741 exit; // Never reached.
2746 // Loginas as redirection if needed.
2747 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2748 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2749 if ($USER->loginascontext->instanceid != $course->id) {
2750 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2755 // Check whether the user should be changing password (but only if it is REALLY them).
2756 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2757 $userauth = get_auth_plugin($USER->auth);
2758 if ($userauth->can_change_password() and !$preventredirect) {
2759 if ($setwantsurltome) {
2760 $SESSION->wantsurl = qualified_me();
2762 if ($changeurl = $userauth->change_password_url()) {
2763 // Use plugin custom url.
2764 redirect($changeurl);
2765 } else {
2766 // Use moodle internal method.
2767 redirect($CFG->wwwroot .'/login/change_password.php');
2769 } else if ($userauth->can_change_password()) {
2770 throw new moodle_exception('forcepasswordchangenotice');
2771 } else {
2772 throw new moodle_exception('nopasswordchangeforced', 'auth');
2776 // Check that the user account is properly set up. If we can't redirect to
2777 // edit their profile and this is not a WS request, perform just the lax check.
2778 // It will allow them to use filepicker on the profile edit page.
2780 if ($preventredirect && !WS_SERVER) {
2781 $usernotfullysetup = user_not_fully_set_up($USER, false);
2782 } else {
2783 $usernotfullysetup = user_not_fully_set_up($USER, true);
2786 if ($usernotfullysetup) {
2787 if ($preventredirect) {
2788 throw new moodle_exception('usernotfullysetup');
2790 if ($setwantsurltome) {
2791 $SESSION->wantsurl = qualified_me();
2793 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2796 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2797 sesskey();
2799 if (\core\session\manager::is_loggedinas()) {
2800 // During a "logged in as" session we should force all content to be cleaned because the
2801 // logged in user will be viewing potentially malicious user generated content.
2802 // See MDL-63786 for more details.
2803 $CFG->forceclean = true;
2806 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2808 // Do not bother admins with any formalities, except for activities pending deletion.
2809 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2810 // Set the global $COURSE.
2811 if ($cm) {
2812 $PAGE->set_cm($cm, $course);
2813 $PAGE->set_pagelayout('incourse');
2814 } else if (!empty($courseorid)) {
2815 $PAGE->set_course($course);
2817 // Set accesstime or the user will appear offline which messes up messaging.
2818 // Do not update access time for webservice or ajax requests.
2819 if (!WS_SERVER && !AJAX_SCRIPT) {
2820 user_accesstime_log($course->id);
2823 foreach ($afterlogins as $plugintype => $plugins) {
2824 foreach ($plugins as $pluginfunction) {
2825 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2828 return;
2831 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2832 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2833 if (!defined('NO_SITEPOLICY_CHECK')) {
2834 define('NO_SITEPOLICY_CHECK', false);
2837 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2838 // Do not test if the script explicitly asked for skipping the site policies check.
2839 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2840 $manager = new \core_privacy\local\sitepolicy\manager();
2841 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2842 if ($preventredirect) {
2843 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2845 if ($setwantsurltome) {
2846 $SESSION->wantsurl = qualified_me();
2848 redirect($policyurl);
2852 // Fetch the system context, the course context, and prefetch its child contexts.
2853 $sysctx = context_system::instance();
2854 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2855 if ($cm) {
2856 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2857 } else {
2858 $cmcontext = null;
2861 // If the site is currently under maintenance, then print a message.
2862 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2863 if ($preventredirect) {
2864 throw new require_login_exception('Maintenance in progress');
2866 $PAGE->set_context(null);
2867 print_maintenance_message();
2870 // Make sure the course itself is not hidden.
2871 if ($course->id == SITEID) {
2872 // Frontpage can not be hidden.
2873 } else {
2874 if (is_role_switched($course->id)) {
2875 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2876 } else {
2877 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2878 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2879 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2880 if ($preventredirect) {
2881 throw new require_login_exception('Course is hidden');
2883 $PAGE->set_context(null);
2884 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2885 // the navigation will mess up when trying to find it.
2886 navigation_node::override_active_url(new moodle_url('/'));
2887 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2892 // Is the user enrolled?
2893 if ($course->id == SITEID) {
2894 // Everybody is enrolled on the frontpage.
2895 } else {
2896 if (\core\session\manager::is_loggedinas()) {
2897 // Make sure the REAL person can access this course first.
2898 $realuser = \core\session\manager::get_realuser();
2899 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2900 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2901 if ($preventredirect) {
2902 throw new require_login_exception('Invalid course login-as access');
2904 $PAGE->set_context(null);
2905 echo $OUTPUT->header();
2906 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2910 $access = false;
2912 if (is_role_switched($course->id)) {
2913 // Ok, user had to be inside this course before the switch.
2914 $access = true;
2916 } else if (is_viewing($coursecontext, $USER)) {
2917 // Ok, no need to mess with enrol.
2918 $access = true;
2920 } else {
2921 if (isset($USER->enrol['enrolled'][$course->id])) {
2922 if ($USER->enrol['enrolled'][$course->id] > time()) {
2923 $access = true;
2924 if (isset($USER->enrol['tempguest'][$course->id])) {
2925 unset($USER->enrol['tempguest'][$course->id]);
2926 remove_temp_course_roles($coursecontext);
2928 } else {
2929 // Expired.
2930 unset($USER->enrol['enrolled'][$course->id]);
2933 if (isset($USER->enrol['tempguest'][$course->id])) {
2934 if ($USER->enrol['tempguest'][$course->id] == 0) {
2935 $access = true;
2936 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2937 $access = true;
2938 } else {
2939 // Expired.
2940 unset($USER->enrol['tempguest'][$course->id]);
2941 remove_temp_course_roles($coursecontext);
2945 if (!$access) {
2946 // Cache not ok.
2947 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2948 if ($until !== false) {
2949 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2950 if ($until == 0) {
2951 $until = ENROL_MAX_TIMESTAMP;
2953 $USER->enrol['enrolled'][$course->id] = $until;
2954 $access = true;
2956 } else if (core_course_category::can_view_course_info($course)) {
2957 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2958 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2959 $enrols = enrol_get_plugins(true);
2960 // First ask all enabled enrol instances in course if they want to auto enrol user.
2961 foreach ($instances as $instance) {
2962 if (!isset($enrols[$instance->enrol])) {
2963 continue;
2965 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2966 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2967 if ($until !== false) {
2968 if ($until == 0) {
2969 $until = ENROL_MAX_TIMESTAMP;
2971 $USER->enrol['enrolled'][$course->id] = $until;
2972 $access = true;
2973 break;
2976 // If not enrolled yet try to gain temporary guest access.
2977 if (!$access) {
2978 foreach ($instances as $instance) {
2979 if (!isset($enrols[$instance->enrol])) {
2980 continue;
2982 // Get a duration for the guest access, a timestamp in the future or false.
2983 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2984 if ($until !== false and $until > time()) {
2985 $USER->enrol['tempguest'][$course->id] = $until;
2986 $access = true;
2987 break;
2991 } else {
2992 // User is not enrolled and is not allowed to browse courses here.
2993 if ($preventredirect) {
2994 throw new require_login_exception('Course is not available');
2996 $PAGE->set_context(null);
2997 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2998 // the navigation will mess up when trying to find it.
2999 navigation_node::override_active_url(new moodle_url('/'));
3000 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3005 if (!$access) {
3006 if ($preventredirect) {
3007 throw new require_login_exception('Not enrolled');
3009 if ($setwantsurltome) {
3010 $SESSION->wantsurl = qualified_me();
3012 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3016 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3017 if ($cm && $cm->deletioninprogress) {
3018 if ($preventredirect) {
3019 throw new moodle_exception('activityisscheduledfordeletion');
3021 require_once($CFG->dirroot . '/course/lib.php');
3022 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3025 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3026 if ($cm && !$cm->uservisible) {
3027 if ($preventredirect) {
3028 throw new require_login_exception('Activity is hidden');
3030 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3031 $PAGE->set_course($course);
3032 $renderer = $PAGE->get_renderer('course');
3033 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3034 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3037 // Set the global $COURSE.
3038 if ($cm) {
3039 $PAGE->set_cm($cm, $course);
3040 $PAGE->set_pagelayout('incourse');
3041 } else if (!empty($courseorid)) {
3042 $PAGE->set_course($course);
3045 foreach ($afterlogins as $plugintype => $plugins) {
3046 foreach ($plugins as $pluginfunction) {
3047 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3051 // Finally access granted, update lastaccess times.
3052 // Do not update access time for webservice or ajax requests.
3053 if (!WS_SERVER && !AJAX_SCRIPT) {
3054 user_accesstime_log($course->id);
3059 * A convenience function for where we must be logged in as admin
3060 * @return void
3062 function require_admin() {
3063 require_login(null, false);
3064 require_capability('moodle/site:config', context_system::instance());
3068 * This function just makes sure a user is logged out.
3070 * @package core_access
3071 * @category access
3073 function require_logout() {
3074 global $USER, $DB;
3076 if (!isloggedin()) {
3077 // This should not happen often, no need for hooks or events here.
3078 \core\session\manager::terminate_current();
3079 return;
3082 // Execute hooks before action.
3083 $authplugins = array();
3084 $authsequence = get_enabled_auth_plugins();
3085 foreach ($authsequence as $authname) {
3086 $authplugins[$authname] = get_auth_plugin($authname);
3087 $authplugins[$authname]->prelogout_hook();
3090 // Store info that gets removed during logout.
3091 $sid = session_id();
3092 $event = \core\event\user_loggedout::create(
3093 array(
3094 'userid' => $USER->id,
3095 'objectid' => $USER->id,
3096 'other' => array('sessionid' => $sid),
3099 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3100 $event->add_record_snapshot('sessions', $session);
3103 // Clone of $USER object to be used by auth plugins.
3104 $user = fullclone($USER);
3106 // Delete session record and drop $_SESSION content.
3107 \core\session\manager::terminate_current();
3109 // Trigger event AFTER action.
3110 $event->trigger();
3112 // Hook to execute auth plugins redirection after event trigger.
3113 foreach ($authplugins as $authplugin) {
3114 $authplugin->postlogout_hook($user);
3119 * Weaker version of require_login()
3121 * This is a weaker version of {@link require_login()} which only requires login
3122 * when called from within a course rather than the site page, unless
3123 * the forcelogin option is turned on.
3124 * @see require_login()
3126 * @package core_access
3127 * @category access
3129 * @param mixed $courseorid The course object or id in question
3130 * @param bool $autologinguest Allow autologin guests if that is wanted
3131 * @param object $cm Course activity module if known
3132 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3133 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3134 * in order to keep redirects working properly. MDL-14495
3135 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3136 * @return void
3137 * @throws coding_exception
3139 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3140 global $CFG, $PAGE, $SITE;
3141 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3142 or (!is_object($courseorid) and $courseorid == SITEID));
3143 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3144 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3145 // db queries so this is not really a performance concern, however it is obviously
3146 // better if you use get_fast_modinfo to get the cm before calling this.
3147 if (is_object($courseorid)) {
3148 $course = $courseorid;
3149 } else {
3150 $course = clone($SITE);
3152 $modinfo = get_fast_modinfo($course);
3153 $cm = $modinfo->get_cm($cm->id);
3155 if (!empty($CFG->forcelogin)) {
3156 // Login required for both SITE and courses.
3157 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3159 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3160 // Always login for hidden activities.
3161 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3163 } else if (isloggedin() && !isguestuser()) {
3164 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3165 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3167 } else if ($issite) {
3168 // Login for SITE not required.
3169 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3170 if (!empty($courseorid)) {
3171 if (is_object($courseorid)) {
3172 $course = $courseorid;
3173 } else {
3174 $course = clone $SITE;
3176 if ($cm) {
3177 if ($cm->course != $course->id) {
3178 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3180 $PAGE->set_cm($cm, $course);
3181 $PAGE->set_pagelayout('incourse');
3182 } else {
3183 $PAGE->set_course($course);
3185 } else {
3186 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3187 $PAGE->set_course($PAGE->course);
3189 // Do not update access time for webservice or ajax requests.
3190 if (!WS_SERVER && !AJAX_SCRIPT) {
3191 user_accesstime_log(SITEID);
3193 return;
3195 } else {
3196 // Course login always required.
3197 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3202 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3204 * @param string $keyvalue the key value
3205 * @param string $script unique script identifier
3206 * @param int $instance instance id
3207 * @return stdClass the key entry in the user_private_key table
3208 * @since Moodle 3.2
3209 * @throws moodle_exception
3211 function validate_user_key($keyvalue, $script, $instance) {
3212 global $DB;
3214 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3215 print_error('invalidkey');
3218 if (!empty($key->validuntil) and $key->validuntil < time()) {
3219 print_error('expiredkey');
3222 if ($key->iprestriction) {
3223 $remoteaddr = getremoteaddr(null);
3224 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3225 print_error('ipmismatch');
3228 return $key;
3232 * Require key login. Function terminates with error if key not found or incorrect.
3234 * @uses NO_MOODLE_COOKIES
3235 * @uses PARAM_ALPHANUM
3236 * @param string $script unique script identifier
3237 * @param int $instance optional instance id
3238 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3239 * @return int Instance ID
3241 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3242 global $DB;
3244 if (!NO_MOODLE_COOKIES) {
3245 print_error('sessioncookiesdisable');
3248 // Extra safety.
3249 \core\session\manager::write_close();
3251 if (null === $keyvalue) {
3252 $keyvalue = required_param('key', PARAM_ALPHANUM);
3255 $key = validate_user_key($keyvalue, $script, $instance);
3257 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3258 print_error('invaliduserid');
3261 core_user::require_active_user($user, true, true);
3263 // Emulate normal session.
3264 enrol_check_plugins($user);
3265 \core\session\manager::set_user($user);
3267 // Note we are not using normal login.
3268 if (!defined('USER_KEY_LOGIN')) {
3269 define('USER_KEY_LOGIN', true);
3272 // Return instance id - it might be empty.
3273 return $key->instance;
3277 * Creates a new private user access key.
3279 * @param string $script unique target identifier
3280 * @param int $userid
3281 * @param int $instance optional instance id
3282 * @param string $iprestriction optional ip restricted access
3283 * @param int $validuntil key valid only until given data
3284 * @return string access key value
3286 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3287 global $DB;
3289 $key = new stdClass();
3290 $key->script = $script;
3291 $key->userid = $userid;
3292 $key->instance = $instance;
3293 $key->iprestriction = $iprestriction;
3294 $key->validuntil = $validuntil;
3295 $key->timecreated = time();
3297 // Something long and unique.
3298 $key->value = md5($userid.'_'.time().random_string(40));
3299 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3300 // Must be unique.
3301 $key->value = md5($userid.'_'.time().random_string(40));
3303 $DB->insert_record('user_private_key', $key);
3304 return $key->value;
3308 * Delete the user's new private user access keys for a particular script.
3310 * @param string $script unique target identifier
3311 * @param int $userid
3312 * @return void
3314 function delete_user_key($script, $userid) {
3315 global $DB;
3316 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3320 * Gets a private user access key (and creates one if one doesn't exist).
3322 * @param string $script unique target identifier
3323 * @param int $userid
3324 * @param int $instance optional instance id
3325 * @param string $iprestriction optional ip restricted access
3326 * @param int $validuntil key valid only until given date
3327 * @return string access key value
3329 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3330 global $DB;
3332 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3333 'instance' => $instance, 'iprestriction' => $iprestriction,
3334 'validuntil' => $validuntil))) {
3335 return $key->value;
3336 } else {
3337 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3343 * Modify the user table by setting the currently logged in user's last login to now.
3345 * @return bool Always returns true
3347 function update_user_login_times() {
3348 global $USER, $DB;
3350 if (isguestuser()) {
3351 // Do not update guest access times/ips for performance.
3352 return true;
3355 $now = time();
3357 $user = new stdClass();
3358 $user->id = $USER->id;
3360 // Make sure all users that logged in have some firstaccess.
3361 if ($USER->firstaccess == 0) {
3362 $USER->firstaccess = $user->firstaccess = $now;
3365 // Store the previous current as lastlogin.
3366 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3368 $USER->currentlogin = $user->currentlogin = $now;
3370 // Function user_accesstime_log() may not update immediately, better do it here.
3371 $USER->lastaccess = $user->lastaccess = $now;
3372 $USER->lastip = $user->lastip = getremoteaddr();
3374 // Note: do not call user_update_user() here because this is part of the login process,
3375 // the login event means that these fields were updated.
3376 $DB->update_record('user', $user);
3377 return true;
3381 * Determines if a user has completed setting up their account.
3383 * The lax mode (with $strict = false) has been introduced for special cases
3384 * only where we want to skip certain checks intentionally. This is valid in
3385 * certain mnet or ajax scenarios when the user cannot / should not be
3386 * redirected to edit their profile. In most cases, you should perform the
3387 * strict check.
3389 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3390 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3391 * @return bool
3393 function user_not_fully_set_up($user, $strict = true) {
3394 global $CFG;
3395 require_once($CFG->dirroot.'/user/profile/lib.php');
3397 if (isguestuser($user)) {
3398 return false;
3401 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3402 return true;
3405 if ($strict) {
3406 if (empty($user->id)) {
3407 // Strict mode can be used with existing accounts only.
3408 return true;
3410 if (!profile_has_required_custom_fields_set($user->id)) {
3411 return true;
3415 return false;
3419 * Check whether the user has exceeded the bounce threshold
3421 * @param stdClass $user A {@link $USER} object
3422 * @return bool true => User has exceeded bounce threshold
3424 function over_bounce_threshold($user) {
3425 global $CFG, $DB;
3427 if (empty($CFG->handlebounces)) {
3428 return false;
3431 if (empty($user->id)) {
3432 // No real (DB) user, nothing to do here.
3433 return false;
3436 // Set sensible defaults.
3437 if (empty($CFG->minbounces)) {
3438 $CFG->minbounces = 10;
3440 if (empty($CFG->bounceratio)) {
3441 $CFG->bounceratio = .20;
3443 $bouncecount = 0;
3444 $sendcount = 0;
3445 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3446 $bouncecount = $bounce->value;
3448 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3449 $sendcount = $send->value;
3451 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3455 * Used to increment or reset email sent count
3457 * @param stdClass $user object containing an id
3458 * @param bool $reset will reset the count to 0
3459 * @return void
3461 function set_send_count($user, $reset=false) {
3462 global $DB;
3464 if (empty($user->id)) {
3465 // No real (DB) user, nothing to do here.
3466 return;
3469 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3470 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3471 $DB->update_record('user_preferences', $pref);
3472 } else if (!empty($reset)) {
3473 // If it's not there and we're resetting, don't bother. Make a new one.
3474 $pref = new stdClass();
3475 $pref->name = 'email_send_count';
3476 $pref->value = 1;
3477 $pref->userid = $user->id;
3478 $DB->insert_record('user_preferences', $pref, false);
3483 * Increment or reset user's email bounce count
3485 * @param stdClass $user object containing an id
3486 * @param bool $reset will reset the count to 0
3488 function set_bounce_count($user, $reset=false) {
3489 global $DB;
3491 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3492 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3493 $DB->update_record('user_preferences', $pref);
3494 } else if (!empty($reset)) {
3495 // If it's not there and we're resetting, don't bother. Make a new one.
3496 $pref = new stdClass();
3497 $pref->name = 'email_bounce_count';
3498 $pref->value = 1;
3499 $pref->userid = $user->id;
3500 $DB->insert_record('user_preferences', $pref, false);
3505 * Determines if the logged in user is currently moving an activity
3507 * @param int $courseid The id of the course being tested
3508 * @return bool
3510 function ismoving($courseid) {
3511 global $USER;
3513 if (!empty($USER->activitycopy)) {
3514 return ($USER->activitycopycourse == $courseid);
3516 return false;
3520 * Returns a persons full name
3522 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3523 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3524 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3525 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3527 * @param stdClass $user A {@link $USER} object to get full name of.
3528 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3529 * @return string
3531 function fullname($user, $override=false) {
3532 global $CFG, $SESSION;
3534 if (!isset($user->firstname) and !isset($user->lastname)) {
3535 return '';
3538 // Get all of the name fields.
3539 $allnames = get_all_user_name_fields();
3540 if ($CFG->debugdeveloper) {
3541 foreach ($allnames as $allname) {
3542 if (!property_exists($user, $allname)) {
3543 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3544 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3545 // Message has been sent, no point in sending the message multiple times.
3546 break;
3551 if (!$override) {
3552 if (!empty($CFG->forcefirstname)) {
3553 $user->firstname = $CFG->forcefirstname;
3555 if (!empty($CFG->forcelastname)) {
3556 $user->lastname = $CFG->forcelastname;
3560 if (!empty($SESSION->fullnamedisplay)) {
3561 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3564 $template = null;
3565 // If the fullnamedisplay setting is available, set the template to that.
3566 if (isset($CFG->fullnamedisplay)) {
3567 $template = $CFG->fullnamedisplay;
3569 // If the template is empty, or set to language, return the language string.
3570 if ((empty($template) || $template == 'language') && !$override) {
3571 return get_string('fullnamedisplay', null, $user);
3574 // Check to see if we are displaying according to the alternative full name format.
3575 if ($override) {
3576 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3577 // Default to show just the user names according to the fullnamedisplay string.
3578 return get_string('fullnamedisplay', null, $user);
3579 } else {
3580 // If the override is true, then change the template to use the complete name.
3581 $template = $CFG->alternativefullnameformat;
3585 $requirednames = array();
3586 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3587 foreach ($allnames as $allname) {
3588 if (strpos($template, $allname) !== false) {
3589 $requirednames[] = $allname;
3593 $displayname = $template;
3594 // Switch in the actual data into the template.
3595 foreach ($requirednames as $altname) {
3596 if (isset($user->$altname)) {
3597 // Using empty() on the below if statement causes breakages.
3598 if ((string)$user->$altname == '') {
3599 $displayname = str_replace($altname, 'EMPTY', $displayname);
3600 } else {
3601 $displayname = str_replace($altname, $user->$altname, $displayname);
3603 } else {
3604 $displayname = str_replace($altname, 'EMPTY', $displayname);
3607 // Tidy up any misc. characters (Not perfect, but gets most characters).
3608 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3609 // katakana and parenthesis.
3610 $patterns = array();
3611 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3612 // filled in by a user.
3613 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3614 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3615 // This regular expression is to remove any double spaces in the display name.
3616 $patterns[] = '/\s{2,}/u';
3617 foreach ($patterns as $pattern) {
3618 $displayname = preg_replace($pattern, ' ', $displayname);
3621 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3622 $displayname = trim($displayname);
3623 if (empty($displayname)) {
3624 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3625 // people in general feel is a good setting to fall back on.
3626 $displayname = $user->firstname;
3628 return $displayname;
3632 * A centralised location for the all name fields. Returns an array / sql string snippet.
3634 * @param bool $returnsql True for an sql select field snippet.
3635 * @param string $tableprefix table query prefix to use in front of each field.
3636 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3637 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3638 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3639 * @return array|string All name fields.
3641 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3642 // This array is provided in this order because when called by fullname() (above) if firstname is before
3643 // firstnamephonetic str_replace() will change the wrong placeholder.
3644 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3645 'lastnamephonetic' => 'lastnamephonetic',
3646 'middlename' => 'middlename',
3647 'alternatename' => 'alternatename',
3648 'firstname' => 'firstname',
3649 'lastname' => 'lastname');
3651 // Let's add a prefix to the array of user name fields if provided.
3652 if ($prefix) {
3653 foreach ($alternatenames as $key => $altname) {
3654 $alternatenames[$key] = $prefix . $altname;
3658 // If we want the end result to have firstname and lastname at the front / top of the result.
3659 if ($order) {
3660 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3661 for ($i = 0; $i < 2; $i++) {
3662 // Get the last element.
3663 $lastelement = end($alternatenames);
3664 // Remove it from the array.
3665 unset($alternatenames[$lastelement]);
3666 // Put the element back on the top of the array.
3667 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3671 // Create an sql field snippet if requested.
3672 if ($returnsql) {
3673 if ($tableprefix) {
3674 if ($fieldprefix) {
3675 foreach ($alternatenames as $key => $altname) {
3676 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3678 } else {
3679 foreach ($alternatenames as $key => $altname) {
3680 $alternatenames[$key] = $tableprefix . '.' . $altname;
3684 $alternatenames = implode(',', $alternatenames);
3686 return $alternatenames;
3690 * Reduces lines of duplicated code for getting user name fields.
3692 * See also {@link user_picture::unalias()}
3694 * @param object $addtoobject Object to add user name fields to.
3695 * @param object $secondobject Object that contains user name field information.
3696 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3697 * @param array $additionalfields Additional fields to be matched with data in the second object.
3698 * The key can be set to the user table field name.
3699 * @return object User name fields.
3701 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3702 $fields = get_all_user_name_fields(false, null, $prefix);
3703 if ($additionalfields) {
3704 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3705 // the key is a number and then sets the key to the array value.
3706 foreach ($additionalfields as $key => $value) {
3707 if (is_numeric($key)) {
3708 $additionalfields[$value] = $prefix . $value;
3709 unset($additionalfields[$key]);
3710 } else {
3711 $additionalfields[$key] = $prefix . $value;
3714 $fields = array_merge($fields, $additionalfields);
3716 foreach ($fields as $key => $field) {
3717 // Important that we have all of the user name fields present in the object that we are sending back.
3718 $addtoobject->$key = '';
3719 if (isset($secondobject->$field)) {
3720 $addtoobject->$key = $secondobject->$field;
3723 return $addtoobject;
3727 * Returns an array of values in order of occurance in a provided string.
3728 * The key in the result is the character postion in the string.
3730 * @param array $values Values to be found in the string format
3731 * @param string $stringformat The string which may contain values being searched for.
3732 * @return array An array of values in order according to placement in the string format.
3734 function order_in_string($values, $stringformat) {
3735 $valuearray = array();
3736 foreach ($values as $value) {
3737 $pattern = "/$value\b/";
3738 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3739 if (preg_match($pattern, $stringformat)) {
3740 $replacement = "thing";
3741 // Replace the value with something more unique to ensure we get the right position when using strpos().
3742 $newformat = preg_replace($pattern, $replacement, $stringformat);
3743 $position = strpos($newformat, $replacement);
3744 $valuearray[$position] = $value;
3747 ksort($valuearray);
3748 return $valuearray;
3752 * Checks if current user is shown any extra fields when listing users.
3754 * @param object $context Context
3755 * @param array $already Array of fields that we're going to show anyway
3756 * so don't bother listing them
3757 * @return array Array of field names from user table, not including anything
3758 * listed in $already
3760 function get_extra_user_fields($context, $already = array()) {
3761 global $CFG;
3763 // Only users with permission get the extra fields.
3764 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3765 return array();
3768 // Split showuseridentity on comma (filter needed in case the showuseridentity is empty).
3769 $extra = array_filter(explode(',', $CFG->showuseridentity));
3771 foreach ($extra as $key => $field) {
3772 if (in_array($field, $already)) {
3773 unset($extra[$key]);
3777 // If the identity fields are also among hidden fields, make sure the user can see them.
3778 $hiddenfields = array_filter(explode(',', $CFG->hiddenuserfields));
3779 $hiddenidentifiers = array_intersect($extra, $hiddenfields);
3781 if ($hiddenidentifiers) {
3782 if ($context->get_course_context(false)) {
3783 // We are somewhere inside a course.
3784 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3786 } else {
3787 // We are not inside a course.
3788 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
3791 if (!$canviewhiddenuserfields) {
3792 // Remove hidden identifiers from the list.
3793 $extra = array_diff($extra, $hiddenidentifiers);
3797 // Re-index the entries.
3798 $extra = array_values($extra);
3800 return $extra;
3804 * If the current user is to be shown extra user fields when listing or
3805 * selecting users, returns a string suitable for including in an SQL select
3806 * clause to retrieve those fields.
3808 * @param context $context Context
3809 * @param string $alias Alias of user table, e.g. 'u' (default none)
3810 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3811 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3812 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3814 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3815 $fields = get_extra_user_fields($context, $already);
3816 $result = '';
3817 // Add punctuation for alias.
3818 if ($alias !== '') {
3819 $alias .= '.';
3821 foreach ($fields as $field) {
3822 $result .= ', ' . $alias . $field;
3823 if ($prefix) {
3824 $result .= ' AS ' . $prefix . $field;
3827 return $result;
3831 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3832 * @param string $field Field name, e.g. 'phone1'
3833 * @return string Text description taken from language file, e.g. 'Phone number'
3835 function get_user_field_name($field) {
3836 // Some fields have language strings which are not the same as field name.
3837 switch ($field) {
3838 case 'url' : {
3839 return get_string('webpage');
3841 case 'icq' : {
3842 return get_string('icqnumber');
3844 case 'skype' : {
3845 return get_string('skypeid');
3847 case 'aim' : {
3848 return get_string('aimid');
3850 case 'yahoo' : {
3851 return get_string('yahooid');
3853 case 'msn' : {
3854 return get_string('msnid');
3856 case 'picture' : {
3857 return get_string('pictureofuser');
3860 // Otherwise just use the same lang string.
3861 return get_string($field);
3865 * Returns whether a given authentication plugin exists.
3867 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3868 * @return boolean Whether the plugin is available.
3870 function exists_auth_plugin($auth) {
3871 global $CFG;
3873 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3874 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3876 return false;
3880 * Checks if a given plugin is in the list of enabled authentication plugins.
3882 * @param string $auth Authentication plugin.
3883 * @return boolean Whether the plugin is enabled.
3885 function is_enabled_auth($auth) {
3886 if (empty($auth)) {
3887 return false;
3890 $enabled = get_enabled_auth_plugins();
3892 return in_array($auth, $enabled);
3896 * Returns an authentication plugin instance.
3898 * @param string $auth name of authentication plugin
3899 * @return auth_plugin_base An instance of the required authentication plugin.
3901 function get_auth_plugin($auth) {
3902 global $CFG;
3904 // Check the plugin exists first.
3905 if (! exists_auth_plugin($auth)) {
3906 print_error('authpluginnotfound', 'debug', '', $auth);
3909 // Return auth plugin instance.
3910 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3911 $class = "auth_plugin_$auth";
3912 return new $class;
3916 * Returns array of active auth plugins.
3918 * @param bool $fix fix $CFG->auth if needed
3919 * @return array
3921 function get_enabled_auth_plugins($fix=false) {
3922 global $CFG;
3924 $default = array('manual', 'nologin');
3926 if (empty($CFG->auth)) {
3927 $auths = array();
3928 } else {
3929 $auths = explode(',', $CFG->auth);
3932 if ($fix) {
3933 $auths = array_unique($auths);
3934 foreach ($auths as $k => $authname) {
3935 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3936 unset($auths[$k]);
3939 $newconfig = implode(',', $auths);
3940 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3941 set_config('auth', $newconfig);
3945 return (array_merge($default, $auths));
3949 * Returns true if an internal authentication method is being used.
3950 * if method not specified then, global default is assumed
3952 * @param string $auth Form of authentication required
3953 * @return bool
3955 function is_internal_auth($auth) {
3956 // Throws error if bad $auth.
3957 $authplugin = get_auth_plugin($auth);
3958 return $authplugin->is_internal();
3962 * Returns true if the user is a 'restored' one.
3964 * Used in the login process to inform the user and allow him/her to reset the password
3966 * @param string $username username to be checked
3967 * @return bool
3969 function is_restored_user($username) {
3970 global $CFG, $DB;
3972 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3976 * Returns an array of user fields
3978 * @return array User field/column names
3980 function get_user_fieldnames() {
3981 global $DB;
3983 $fieldarray = $DB->get_columns('user');
3984 unset($fieldarray['id']);
3985 $fieldarray = array_keys($fieldarray);
3987 return $fieldarray;
3991 * Creates a bare-bones user record
3993 * @todo Outline auth types and provide code example
3995 * @param string $username New user's username to add to record
3996 * @param string $password New user's password to add to record
3997 * @param string $auth Form of authentication required
3998 * @return stdClass A complete user object
4000 function create_user_record($username, $password, $auth = 'manual') {
4001 global $CFG, $DB;
4002 require_once($CFG->dirroot.'/user/profile/lib.php');
4003 require_once($CFG->dirroot.'/user/lib.php');
4005 // Just in case check text case.
4006 $username = trim(core_text::strtolower($username));
4008 $authplugin = get_auth_plugin($auth);
4009 $customfields = $authplugin->get_custom_user_profile_fields();
4010 $newuser = new stdClass();
4011 if ($newinfo = $authplugin->get_userinfo($username)) {
4012 $newinfo = truncate_userinfo($newinfo);
4013 foreach ($newinfo as $key => $value) {
4014 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
4015 $newuser->$key = $value;
4020 if (!empty($newuser->email)) {
4021 if (email_is_not_allowed($newuser->email)) {
4022 unset($newuser->email);
4026 if (!isset($newuser->city)) {
4027 $newuser->city = '';
4030 $newuser->auth = $auth;
4031 $newuser->username = $username;
4033 // Fix for MDL-8480
4034 // user CFG lang for user if $newuser->lang is empty
4035 // or $user->lang is not an installed language.
4036 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
4037 $newuser->lang = $CFG->lang;
4039 $newuser->confirmed = 1;
4040 $newuser->lastip = getremoteaddr();
4041 $newuser->timecreated = time();
4042 $newuser->timemodified = $newuser->timecreated;
4043 $newuser->mnethostid = $CFG->mnet_localhost_id;
4045 $newuser->id = user_create_user($newuser, false, false);
4047 // Save user profile data.
4048 profile_save_data($newuser);
4050 $user = get_complete_user_data('id', $newuser->id);
4051 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
4052 set_user_preference('auth_forcepasswordchange', 1, $user);
4054 // Set the password.
4055 update_internal_user_password($user, $password);
4057 // Trigger event.
4058 \core\event\user_created::create_from_userid($newuser->id)->trigger();
4060 return $user;
4064 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4066 * @param string $username user's username to update the record
4067 * @return stdClass A complete user object
4069 function update_user_record($username) {
4070 global $DB, $CFG;
4071 // Just in case check text case.
4072 $username = trim(core_text::strtolower($username));
4074 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
4075 return update_user_record_by_id($oldinfo->id);
4079 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4081 * @param int $id user id
4082 * @return stdClass A complete user object
4084 function update_user_record_by_id($id) {
4085 global $DB, $CFG;
4086 require_once($CFG->dirroot."/user/profile/lib.php");
4087 require_once($CFG->dirroot.'/user/lib.php');
4089 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
4090 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
4092 $newuser = array();
4093 $userauth = get_auth_plugin($oldinfo->auth);
4095 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4096 $newinfo = truncate_userinfo($newinfo);
4097 $customfields = $userauth->get_custom_user_profile_fields();
4099 foreach ($newinfo as $key => $value) {
4100 $iscustom = in_array($key, $customfields);
4101 if (!$iscustom) {
4102 $key = strtolower($key);
4104 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4105 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4106 // Unknown or must not be changed.
4107 continue;
4109 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
4110 continue;
4112 $confval = $userauth->config->{'field_updatelocal_' . $key};
4113 $lockval = $userauth->config->{'field_lock_' . $key};
4114 if ($confval === 'onlogin') {
4115 // MDL-4207 Don't overwrite modified user profile values with
4116 // empty LDAP values when 'unlocked if empty' is set. The purpose
4117 // of the setting 'unlocked if empty' is to allow the user to fill
4118 // in a value for the selected field _if LDAP is giving
4119 // nothing_ for this field. Thus it makes sense to let this value
4120 // stand in until LDAP is giving a value for this field.
4121 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4122 if ($iscustom || (in_array($key, $userauth->userfields) &&
4123 ((string)$oldinfo->$key !== (string)$value))) {
4124 $newuser[$key] = (string)$value;
4129 if ($newuser) {
4130 $newuser['id'] = $oldinfo->id;
4131 $newuser['timemodified'] = time();
4132 user_update_user((object) $newuser, false, false);
4134 // Save user profile data.
4135 profile_save_data((object) $newuser);
4137 // Trigger event.
4138 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4142 return get_complete_user_data('id', $oldinfo->id);
4146 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4148 * @param array $info Array of user properties to truncate if needed
4149 * @return array The now truncated information that was passed in
4151 function truncate_userinfo(array $info) {
4152 // Define the limits.
4153 $limit = array(
4154 'username' => 100,
4155 'idnumber' => 255,
4156 'firstname' => 100,
4157 'lastname' => 100,
4158 'email' => 100,
4159 'icq' => 15,
4160 'phone1' => 20,
4161 'phone2' => 20,
4162 'institution' => 255,
4163 'department' => 255,
4164 'address' => 255,
4165 'city' => 120,
4166 'country' => 2,
4167 'url' => 255,
4170 // Apply where needed.
4171 foreach (array_keys($info) as $key) {
4172 if (!empty($limit[$key])) {
4173 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4177 return $info;
4181 * Marks user deleted in internal user database and notifies the auth plugin.
4182 * Also unenrols user from all roles and does other cleanup.
4184 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4186 * @param stdClass $user full user object before delete
4187 * @return boolean success
4188 * @throws coding_exception if invalid $user parameter detected
4190 function delete_user(stdClass $user) {
4191 global $CFG, $DB, $SESSION;
4192 require_once($CFG->libdir.'/grouplib.php');
4193 require_once($CFG->libdir.'/gradelib.php');
4194 require_once($CFG->dirroot.'/message/lib.php');
4195 require_once($CFG->dirroot.'/user/lib.php');
4197 // Make sure nobody sends bogus record type as parameter.
4198 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4199 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4202 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4203 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4204 debugging('Attempt to delete unknown user account.');
4205 return false;
4208 // There must be always exactly one guest record, originally the guest account was identified by username only,
4209 // now we use $CFG->siteguest for performance reasons.
4210 if ($user->username === 'guest' or isguestuser($user)) {
4211 debugging('Guest user account can not be deleted.');
4212 return false;
4215 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4216 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4217 if ($user->auth === 'manual' and is_siteadmin($user)) {
4218 debugging('Local administrator accounts can not be deleted.');
4219 return false;
4222 // Allow plugins to use this user object before we completely delete it.
4223 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4224 foreach ($pluginsfunction as $plugintype => $plugins) {
4225 foreach ($plugins as $pluginfunction) {
4226 $pluginfunction($user);
4231 // Keep user record before updating it, as we have to pass this to user_deleted event.
4232 $olduser = clone $user;
4234 // Keep a copy of user context, we need it for event.
4235 $usercontext = context_user::instance($user->id);
4237 // Delete all grades - backup is kept in grade_grades_history table.
4238 grade_user_delete($user->id);
4240 // TODO: remove from cohorts using standard API here.
4242 // Remove user tags.
4243 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4245 // Unconditionally unenrol from all courses.
4246 enrol_user_delete($user);
4248 // Unenrol from all roles in all contexts.
4249 // This might be slow but it is really needed - modules might do some extra cleanup!
4250 role_unassign_all(array('userid' => $user->id));
4252 // Notify the competency subsystem.
4253 \core_competency\api::hook_user_deleted($user->id);
4255 // Now do a brute force cleanup.
4257 // Delete all user events and subscription events.
4258 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
4260 // Now, delete all calendar subscription from the user.
4261 $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
4263 // Remove from all cohorts.
4264 $DB->delete_records('cohort_members', array('userid' => $user->id));
4266 // Remove from all groups.
4267 $DB->delete_records('groups_members', array('userid' => $user->id));
4269 // Brute force unenrol from all courses.
4270 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4272 // Purge user preferences.
4273 $DB->delete_records('user_preferences', array('userid' => $user->id));
4275 // Purge user extra profile info.
4276 $DB->delete_records('user_info_data', array('userid' => $user->id));
4278 // Purge log of previous password hashes.
4279 $DB->delete_records('user_password_history', array('userid' => $user->id));
4281 // Last course access not necessary either.
4282 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4283 // Remove all user tokens.
4284 $DB->delete_records('external_tokens', array('userid' => $user->id));
4286 // Unauthorise the user for all services.
4287 $DB->delete_records('external_services_users', array('userid' => $user->id));
4289 // Remove users private keys.
4290 $DB->delete_records('user_private_key', array('userid' => $user->id));
4292 // Remove users customised pages.
4293 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4295 // Delete user from $SESSION->bulk_users.
4296 if (isset($SESSION->bulk_users[$user->id])) {
4297 unset($SESSION->bulk_users[$user->id]);
4300 // Force logout - may fail if file based sessions used, sorry.
4301 \core\session\manager::kill_user_sessions($user->id);
4303 // Generate username from email address, or a fake email.
4304 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4306 $deltime = time();
4307 $deltimelength = core_text::strlen((string) $deltime);
4309 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4310 $delname = clean_param($delemail, PARAM_USERNAME);
4311 $delname = core_text::substr($delname, 0, 100 - ($deltimelength + 1)) . ".{$deltime}";
4313 // Workaround for bulk deletes of users with the same email address.
4314 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4315 $delname++;
4318 // Mark internal user record as "deleted".
4319 $updateuser = new stdClass();
4320 $updateuser->id = $user->id;
4321 $updateuser->deleted = 1;
4322 $updateuser->username = $delname; // Remember it just in case.
4323 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4324 $updateuser->idnumber = ''; // Clear this field to free it up.
4325 $updateuser->picture = 0;
4326 $updateuser->timemodified = $deltime;
4328 // Don't trigger update event, as user is being deleted.
4329 user_update_user($updateuser, false, false);
4331 // Delete all content associated with the user context, but not the context itself.
4332 $usercontext->delete_content();
4334 // Delete any search data.
4335 \core_search\manager::context_deleted($usercontext);
4337 // Any plugin that needs to cleanup should register this event.
4338 // Trigger event.
4339 $event = \core\event\user_deleted::create(
4340 array(
4341 'objectid' => $user->id,
4342 'relateduserid' => $user->id,
4343 'context' => $usercontext,
4344 'other' => array(
4345 'username' => $user->username,
4346 'email' => $user->email,
4347 'idnumber' => $user->idnumber,
4348 'picture' => $user->picture,
4349 'mnethostid' => $user->mnethostid
4353 $event->add_record_snapshot('user', $olduser);
4354 $event->trigger();
4356 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4357 // should know about this updated property persisted to the user's table.
4358 $user->timemodified = $updateuser->timemodified;
4360 // Notify auth plugin - do not block the delete even when plugin fails.
4361 $authplugin = get_auth_plugin($user->auth);
4362 $authplugin->user_delete($user);
4364 return true;
4368 * Retrieve the guest user object.
4370 * @return stdClass A {@link $USER} object
4372 function guest_user() {
4373 global $CFG, $DB;
4375 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4376 $newuser->confirmed = 1;
4377 $newuser->lang = $CFG->lang;
4378 $newuser->lastip = getremoteaddr();
4381 return $newuser;
4385 * Authenticates a user against the chosen authentication mechanism
4387 * Given a username and password, this function looks them
4388 * up using the currently selected authentication mechanism,
4389 * and if the authentication is successful, it returns a
4390 * valid $user object from the 'user' table.
4392 * Uses auth_ functions from the currently active auth module
4394 * After authenticate_user_login() returns success, you will need to
4395 * log that the user has logged in, and call complete_user_login() to set
4396 * the session up.
4398 * Note: this function works only with non-mnet accounts!
4400 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4401 * @param string $password User's password
4402 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4403 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4404 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4405 * @return stdClass|false A {@link $USER} object or false if error
4407 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4408 global $CFG, $DB, $PAGE;
4409 require_once("$CFG->libdir/authlib.php");
4411 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4412 // we have found the user
4414 } else if (!empty($CFG->authloginviaemail)) {
4415 if ($email = clean_param($username, PARAM_EMAIL)) {
4416 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4417 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4418 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4419 if (count($users) === 1) {
4420 // Use email for login only if unique.
4421 $user = reset($users);
4422 $user = get_complete_user_data('id', $user->id);
4423 $username = $user->username;
4425 unset($users);
4429 // Make sure this request came from the login form.
4430 if (!\core\session\manager::validate_login_token($logintoken)) {
4431 $failurereason = AUTH_LOGIN_FAILED;
4433 // Trigger login failed event (specifying the ID of the found user, if available).
4434 \core\event\user_login_failed::create([
4435 'userid' => ($user->id ?? 0),
4436 'other' => [
4437 'username' => $username,
4438 'reason' => $failurereason,
4440 ])->trigger();
4442 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4443 return false;
4446 $authsenabled = get_enabled_auth_plugins();
4448 if ($user) {
4449 // Use manual if auth not set.
4450 $auth = empty($user->auth) ? 'manual' : $user->auth;
4452 if (in_array($user->auth, $authsenabled)) {
4453 $authplugin = get_auth_plugin($user->auth);
4454 $authplugin->pre_user_login_hook($user);
4457 if (!empty($user->suspended)) {
4458 $failurereason = AUTH_LOGIN_SUSPENDED;
4460 // Trigger login failed event.
4461 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4462 'other' => array('username' => $username, 'reason' => $failurereason)));
4463 $event->trigger();
4464 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4465 return false;
4467 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4468 // Legacy way to suspend user.
4469 $failurereason = AUTH_LOGIN_SUSPENDED;
4471 // Trigger login failed event.
4472 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4473 'other' => array('username' => $username, 'reason' => $failurereason)));
4474 $event->trigger();
4475 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4476 return false;
4478 $auths = array($auth);
4480 } else {
4481 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4482 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4483 $failurereason = AUTH_LOGIN_NOUSER;
4485 // Trigger login failed event.
4486 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4487 'reason' => $failurereason)));
4488 $event->trigger();
4489 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4490 return false;
4493 // User does not exist.
4494 $auths = $authsenabled;
4495 $user = new stdClass();
4496 $user->id = 0;
4499 if ($ignorelockout) {
4500 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4501 // or this function is called from a SSO script.
4502 } else if ($user->id) {
4503 // Verify login lockout after other ways that may prevent user login.
4504 if (login_is_lockedout($user)) {
4505 $failurereason = AUTH_LOGIN_LOCKOUT;
4507 // Trigger login failed event.
4508 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4509 'other' => array('username' => $username, 'reason' => $failurereason)));
4510 $event->trigger();
4512 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4513 return false;
4515 } else {
4516 // We can not lockout non-existing accounts.
4519 foreach ($auths as $auth) {
4520 $authplugin = get_auth_plugin($auth);
4522 // On auth fail fall through to the next plugin.
4523 if (!$authplugin->user_login($username, $password)) {
4524 continue;
4527 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4528 if (!empty($CFG->passwordpolicycheckonlogin)) {
4529 $errmsg = '';
4530 $passed = check_password_policy($password, $errmsg, $user);
4531 if (!$passed) {
4532 // First trigger event for failure.
4533 $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
4534 $failedevent->trigger();
4536 // If able to change password, set flag and move on.
4537 if ($authplugin->can_change_password()) {
4538 // Check if we are on internal change password page, or service is external, don't show notification.
4539 $internalchangeurl = new moodle_url('/login/change_password.php');
4540 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
4541 \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
4543 set_user_preference('auth_forcepasswordchange', 1, $user);
4544 } else if ($authplugin->can_reset_password()) {
4545 // Else force a reset if possible.
4546 \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
4547 redirect(new moodle_url('/login/forgot_password.php'));
4548 } else {
4549 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4550 // If support page is set, add link for help.
4551 if (!empty($CFG->supportpage)) {
4552 $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
4553 $link = \html_writer::tag('p', $link);
4554 $notifymsg .= $link;
4557 // If no change or reset is possible, add a notification for user.
4558 \core\notification::error($notifymsg);
4563 // Successful authentication.
4564 if ($user->id) {
4565 // User already exists in database.
4566 if (empty($user->auth)) {
4567 // For some reason auth isn't set yet.
4568 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4569 $user->auth = $auth;
4572 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4573 // the current hash algorithm while we have access to the user's password.
4574 update_internal_user_password($user, $password);
4576 if ($authplugin->is_synchronised_with_external()) {
4577 // Update user record from external DB.
4578 $user = update_user_record_by_id($user->id);
4580 } else {
4581 // The user is authenticated but user creation may be disabled.
4582 if (!empty($CFG->authpreventaccountcreation)) {
4583 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4585 // Trigger login failed event.
4586 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4587 'reason' => $failurereason)));
4588 $event->trigger();
4590 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4591 $_SERVER['HTTP_USER_AGENT']);
4592 return false;
4593 } else {
4594 $user = create_user_record($username, $password, $auth);
4598 $authplugin->sync_roles($user);
4600 foreach ($authsenabled as $hau) {
4601 $hauth = get_auth_plugin($hau);
4602 $hauth->user_authenticated_hook($user, $username, $password);
4605 if (empty($user->id)) {
4606 $failurereason = AUTH_LOGIN_NOUSER;
4607 // Trigger login failed event.
4608 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4609 'reason' => $failurereason)));
4610 $event->trigger();
4611 return false;
4614 if (!empty($user->suspended)) {
4615 // Just in case some auth plugin suspended account.
4616 $failurereason = AUTH_LOGIN_SUSPENDED;
4617 // Trigger login failed event.
4618 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4619 'other' => array('username' => $username, 'reason' => $failurereason)));
4620 $event->trigger();
4621 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4622 return false;
4625 login_attempt_valid($user);
4626 $failurereason = AUTH_LOGIN_OK;
4627 return $user;
4630 // Failed if all the plugins have failed.
4631 if (debugging('', DEBUG_ALL)) {
4632 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4635 if ($user->id) {
4636 login_attempt_failed($user);
4637 $failurereason = AUTH_LOGIN_FAILED;
4638 // Trigger login failed event.
4639 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4640 'other' => array('username' => $username, 'reason' => $failurereason)));
4641 $event->trigger();
4642 } else {
4643 $failurereason = AUTH_LOGIN_NOUSER;
4644 // Trigger login failed event.
4645 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4646 'reason' => $failurereason)));
4647 $event->trigger();
4650 return false;
4654 * Call to complete the user login process after authenticate_user_login()
4655 * has succeeded. It will setup the $USER variable and other required bits
4656 * and pieces.
4658 * NOTE:
4659 * - It will NOT log anything -- up to the caller to decide what to log.
4660 * - this function does not set any cookies any more!
4662 * @param stdClass $user
4663 * @return stdClass A {@link $USER} object - BC only, do not use
4665 function complete_user_login($user) {
4666 global $CFG, $DB, $USER, $SESSION;
4668 \core\session\manager::login_user($user);
4670 // Reload preferences from DB.
4671 unset($USER->preference);
4672 check_user_preferences_loaded($USER);
4674 // Update login times.
4675 update_user_login_times();
4677 // Extra session prefs init.
4678 set_login_session_preferences();
4680 // Trigger login event.
4681 $event = \core\event\user_loggedin::create(
4682 array(
4683 'userid' => $USER->id,
4684 'objectid' => $USER->id,
4685 'other' => array('username' => $USER->username),
4688 $event->trigger();
4690 // Queue migrating the messaging data, if we need to.
4691 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4692 // Check if there are any legacy messages to migrate.
4693 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4694 \core_message\task\migrate_message_data::queue_task($USER->id);
4695 } else {
4696 set_user_preference('core_message_migrate_data', true, $USER->id);
4700 if (isguestuser()) {
4701 // No need to continue when user is THE guest.
4702 return $USER;
4705 if (CLI_SCRIPT) {
4706 // We can redirect to password change URL only in browser.
4707 return $USER;
4710 // Select password change url.
4711 $userauth = get_auth_plugin($USER->auth);
4713 // Check whether the user should be changing password.
4714 if (get_user_preferences('auth_forcepasswordchange', false)) {
4715 if ($userauth->can_change_password()) {
4716 if ($changeurl = $userauth->change_password_url()) {
4717 redirect($changeurl);
4718 } else {
4719 require_once($CFG->dirroot . '/login/lib.php');
4720 $SESSION->wantsurl = core_login_get_return_url();
4721 redirect($CFG->wwwroot.'/login/change_password.php');
4723 } else {
4724 print_error('nopasswordchangeforced', 'auth');
4727 return $USER;
4731 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4733 * @param string $password String to check.
4734 * @return boolean True if the $password matches the format of an md5 sum.
4736 function password_is_legacy_hash($password) {
4737 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4741 * Compare password against hash stored in user object to determine if it is valid.
4743 * If necessary it also updates the stored hash to the current format.
4745 * @param stdClass $user (Password property may be updated).
4746 * @param string $password Plain text password.
4747 * @return bool True if password is valid.
4749 function validate_internal_user_password($user, $password) {
4750 global $CFG;
4752 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4753 // Internal password is not used at all, it can not validate.
4754 return false;
4757 // If hash isn't a legacy (md5) hash, validate using the library function.
4758 if (!password_is_legacy_hash($user->password)) {
4759 return password_verify($password, $user->password);
4762 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4763 // is valid we can then update it to the new algorithm.
4765 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4766 $validated = false;
4768 if ($user->password === md5($password.$sitesalt)
4769 or $user->password === md5($password)
4770 or $user->password === md5(addslashes($password).$sitesalt)
4771 or $user->password === md5(addslashes($password))) {
4772 // Note: we are intentionally using the addslashes() here because we
4773 // need to accept old password hashes of passwords with magic quotes.
4774 $validated = true;
4776 } else {
4777 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4778 $alt = 'passwordsaltalt'.$i;
4779 if (!empty($CFG->$alt)) {
4780 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4781 $validated = true;
4782 break;
4788 if ($validated) {
4789 // If the password matches the existing md5 hash, update to the
4790 // current hash algorithm while we have access to the user's password.
4791 update_internal_user_password($user, $password);
4794 return $validated;
4798 * Calculate hash for a plain text password.
4800 * @param string $password Plain text password to be hashed.
4801 * @param bool $fasthash If true, use a low cost factor when generating the hash
4802 * This is much faster to generate but makes the hash
4803 * less secure. It is used when lots of hashes need to
4804 * be generated quickly.
4805 * @return string The hashed password.
4807 * @throws moodle_exception If a problem occurs while generating the hash.
4809 function hash_internal_user_password($password, $fasthash = false) {
4810 global $CFG;
4812 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4813 $options = ($fasthash) ? array('cost' => 4) : array();
4815 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4817 if ($generatedhash === false || $generatedhash === null) {
4818 throw new moodle_exception('Failed to generate password hash.');
4821 return $generatedhash;
4825 * Update password hash in user object (if necessary).
4827 * The password is updated if:
4828 * 1. The password has changed (the hash of $user->password is different
4829 * to the hash of $password).
4830 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4831 * md5 algorithm).
4833 * Updating the password will modify the $user object and the database
4834 * record to use the current hashing algorithm.
4835 * It will remove Web Services user tokens too.
4837 * @param stdClass $user User object (password property may be updated).
4838 * @param string $password Plain text password.
4839 * @param bool $fasthash If true, use a low cost factor when generating the hash
4840 * This is much faster to generate but makes the hash
4841 * less secure. It is used when lots of hashes need to
4842 * be generated quickly.
4843 * @return bool Always returns true.
4845 function update_internal_user_password($user, $password, $fasthash = false) {
4846 global $CFG, $DB;
4848 // Figure out what the hashed password should be.
4849 if (!isset($user->auth)) {
4850 debugging('User record in update_internal_user_password() must include field auth',
4851 DEBUG_DEVELOPER);
4852 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4854 $authplugin = get_auth_plugin($user->auth);
4855 if ($authplugin->prevent_local_passwords()) {
4856 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4857 } else {
4858 $hashedpassword = hash_internal_user_password($password, $fasthash);
4861 $algorithmchanged = false;
4863 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4864 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4865 $passwordchanged = ($user->password !== $hashedpassword);
4867 } else if (isset($user->password)) {
4868 // If verification fails then it means the password has changed.
4869 $passwordchanged = !password_verify($password, $user->password);
4870 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4871 } else {
4872 // While creating new user, password in unset in $user object, to avoid
4873 // saving it with user_create()
4874 $passwordchanged = true;
4877 if ($passwordchanged || $algorithmchanged) {
4878 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4879 $user->password = $hashedpassword;
4881 // Trigger event.
4882 $user = $DB->get_record('user', array('id' => $user->id));
4883 \core\event\user_password_updated::create_from_user($user)->trigger();
4885 // Remove WS user tokens.
4886 if (!empty($CFG->passwordchangetokendeletion)) {
4887 require_once($CFG->dirroot.'/webservice/lib.php');
4888 webservice::delete_user_ws_tokens($user->id);
4892 return true;
4896 * Get a complete user record, which includes all the info in the user record.
4898 * Intended for setting as $USER session variable
4900 * @param string $field The user field to be checked for a given value.
4901 * @param string $value The value to match for $field.
4902 * @param int $mnethostid
4903 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4904 * found. Otherwise, it will just return false.
4905 * @return mixed False, or A {@link $USER} object.
4907 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4908 global $CFG, $DB;
4910 if (!$field || !$value) {
4911 return false;
4914 // Change the field to lowercase.
4915 $field = core_text::strtolower($field);
4917 // List of case insensitive fields.
4918 $caseinsensitivefields = ['email'];
4920 // Username input is forced to lowercase and should be case sensitive.
4921 if ($field == 'username') {
4922 $value = core_text::strtolower($value);
4925 // Build the WHERE clause for an SQL query.
4926 $params = array('fieldval' => $value);
4928 // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4929 // such as MySQL by pre-filtering users with accent-insensitive subselect.
4930 if (in_array($field, $caseinsensitivefields)) {
4931 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4932 $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4933 $params['fieldval2'] = $value;
4934 } else {
4935 $fieldselect = "$field = :fieldval";
4936 $idsubselect = '';
4938 $constraints = "$fieldselect AND deleted <> 1";
4940 // If we are loading user data based on anything other than id,
4941 // we must also restrict our search based on mnet host.
4942 if ($field != 'id') {
4943 if (empty($mnethostid)) {
4944 // If empty, we restrict to local users.
4945 $mnethostid = $CFG->mnet_localhost_id;
4948 if (!empty($mnethostid)) {
4949 $params['mnethostid'] = $mnethostid;
4950 $constraints .= " AND mnethostid = :mnethostid";
4953 if ($idsubselect) {
4954 $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4957 // Get all the basic user data.
4958 try {
4959 // Make sure that there's only a single record that matches our query.
4960 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4961 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4962 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4963 } catch (dml_exception $exception) {
4964 if ($throwexception) {
4965 throw $exception;
4966 } else {
4967 // Return false when no records or multiple records were found.
4968 return false;
4972 // Get various settings and preferences.
4974 // Preload preference cache.
4975 check_user_preferences_loaded($user);
4977 // Load course enrolment related stuff.
4978 $user->lastcourseaccess = array(); // During last session.
4979 $user->currentcourseaccess = array(); // During current session.
4980 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4981 foreach ($lastaccesses as $lastaccess) {
4982 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4986 $sql = "SELECT g.id, g.courseid
4987 FROM {groups} g, {groups_members} gm
4988 WHERE gm.groupid=g.id AND gm.userid=?";
4990 // This is a special hack to speedup calendar display.
4991 $user->groupmember = array();
4992 if (!isguestuser($user)) {
4993 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4994 foreach ($groups as $group) {
4995 if (!array_key_exists($group->courseid, $user->groupmember)) {
4996 $user->groupmember[$group->courseid] = array();
4998 $user->groupmember[$group->courseid][$group->id] = $group->id;
5003 // Add cohort theme.
5004 if (!empty($CFG->allowcohortthemes)) {
5005 require_once($CFG->dirroot . '/cohort/lib.php');
5006 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
5007 $user->cohorttheme = $cohorttheme;
5011 // Add the custom profile fields to the user record.
5012 $user->profile = array();
5013 if (!isguestuser($user)) {
5014 require_once($CFG->dirroot.'/user/profile/lib.php');
5015 profile_load_custom_fields($user);
5018 // Rewrite some variables if necessary.
5019 if (!empty($user->description)) {
5020 // No need to cart all of it around.
5021 $user->description = true;
5023 if (isguestuser($user)) {
5024 // Guest language always same as site.
5025 $user->lang = $CFG->lang;
5026 // Name always in current language.
5027 $user->firstname = get_string('guestuser');
5028 $user->lastname = ' ';
5031 return $user;
5035 * Validate a password against the configured password policy
5037 * @param string $password the password to be checked against the password policy
5038 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
5039 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
5041 * @return bool true if the password is valid according to the policy. false otherwise.
5043 function check_password_policy($password, &$errmsg, $user = null) {
5044 global $CFG;
5046 if (!empty($CFG->passwordpolicy)) {
5047 $errmsg = '';
5048 if (core_text::strlen($password) < $CFG->minpasswordlength) {
5049 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
5051 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
5052 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
5054 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
5055 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
5057 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
5058 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
5060 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
5061 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
5063 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
5064 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
5067 // Fire any additional password policy functions from plugins.
5068 // Plugin functions should output an error message string or empty string for success.
5069 $pluginsfunction = get_plugins_with_function('check_password_policy');
5070 foreach ($pluginsfunction as $plugintype => $plugins) {
5071 foreach ($plugins as $pluginfunction) {
5072 $pluginerr = $pluginfunction($password, $user);
5073 if ($pluginerr) {
5074 $errmsg .= '<div>'. $pluginerr .'</div>';
5080 if ($errmsg == '') {
5081 return true;
5082 } else {
5083 return false;
5089 * When logging in, this function is run to set certain preferences for the current SESSION.
5091 function set_login_session_preferences() {
5092 global $SESSION;
5094 $SESSION->justloggedin = true;
5096 unset($SESSION->lang);
5097 unset($SESSION->forcelang);
5098 unset($SESSION->load_navigation_admin);
5103 * Delete a course, including all related data from the database, and any associated files.
5105 * @param mixed $courseorid The id of the course or course object to delete.
5106 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5107 * @return bool true if all the removals succeeded. false if there were any failures. If this
5108 * method returns false, some of the removals will probably have succeeded, and others
5109 * failed, but you have no way of knowing which.
5111 function delete_course($courseorid, $showfeedback = true) {
5112 global $DB;
5114 if (is_object($courseorid)) {
5115 $courseid = $courseorid->id;
5116 $course = $courseorid;
5117 } else {
5118 $courseid = $courseorid;
5119 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5120 return false;
5123 $context = context_course::instance($courseid);
5125 // Frontpage course can not be deleted!!
5126 if ($courseid == SITEID) {
5127 return false;
5130 // Allow plugins to use this course before we completely delete it.
5131 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5132 foreach ($pluginsfunction as $plugintype => $plugins) {
5133 foreach ($plugins as $pluginfunction) {
5134 $pluginfunction($course);
5139 // Tell the search manager we are about to delete a course. This prevents us sending updates
5140 // for each individual context being deleted.
5141 \core_search\manager::course_deleting_start($courseid);
5143 $handler = core_course\customfield\course_handler::create();
5144 $handler->delete_instance($courseid);
5146 // Make the course completely empty.
5147 remove_course_contents($courseid, $showfeedback);
5149 // Delete the course and related context instance.
5150 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5152 $DB->delete_records("course", array("id" => $courseid));
5153 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5155 // Reset all course related caches here.
5156 if (class_exists('format_base', false)) {
5157 format_base::reset_course_cache($courseid);
5160 // Tell search that we have deleted the course so it can delete course data from the index.
5161 \core_search\manager::course_deleting_finish($courseid);
5163 // Trigger a course deleted event.
5164 $event = \core\event\course_deleted::create(array(
5165 'objectid' => $course->id,
5166 'context' => $context,
5167 'other' => array(
5168 'shortname' => $course->shortname,
5169 'fullname' => $course->fullname,
5170 'idnumber' => $course->idnumber
5173 $event->add_record_snapshot('course', $course);
5174 $event->trigger();
5176 return true;
5180 * Clear a course out completely, deleting all content but don't delete the course itself.
5182 * This function does not verify any permissions.
5184 * Please note this function also deletes all user enrolments,
5185 * enrolment instances and role assignments by default.
5187 * $options:
5188 * - 'keep_roles_and_enrolments' - false by default
5189 * - 'keep_groups_and_groupings' - false by default
5191 * @param int $courseid The id of the course that is being deleted
5192 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5193 * @param array $options extra options
5194 * @return bool true if all the removals succeeded. false if there were any failures. If this
5195 * method returns false, some of the removals will probably have succeeded, and others
5196 * failed, but you have no way of knowing which.
5198 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5199 global $CFG, $DB, $OUTPUT;
5201 require_once($CFG->libdir.'/badgeslib.php');
5202 require_once($CFG->libdir.'/completionlib.php');
5203 require_once($CFG->libdir.'/questionlib.php');
5204 require_once($CFG->libdir.'/gradelib.php');
5205 require_once($CFG->dirroot.'/group/lib.php');
5206 require_once($CFG->dirroot.'/comment/lib.php');
5207 require_once($CFG->dirroot.'/rating/lib.php');
5208 require_once($CFG->dirroot.'/notes/lib.php');
5210 // Handle course badges.
5211 badges_handle_course_deletion($courseid);
5213 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5214 $strdeleted = get_string('deleted').' - ';
5216 // Some crazy wishlist of stuff we should skip during purging of course content.
5217 $options = (array)$options;
5219 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5220 $coursecontext = context_course::instance($courseid);
5221 $fs = get_file_storage();
5223 // Delete course completion information, this has to be done before grades and enrols.
5224 $cc = new completion_info($course);
5225 $cc->clear_criteria();
5226 if ($showfeedback) {
5227 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5230 // Remove all data from gradebook - this needs to be done before course modules
5231 // because while deleting this information, the system may need to reference
5232 // the course modules that own the grades.
5233 remove_course_grades($courseid, $showfeedback);
5234 remove_grade_letters($coursecontext, $showfeedback);
5236 // Delete course blocks in any all child contexts,
5237 // they may depend on modules so delete them first.
5238 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5239 foreach ($childcontexts as $childcontext) {
5240 blocks_delete_all_for_context($childcontext->id);
5242 unset($childcontexts);
5243 blocks_delete_all_for_context($coursecontext->id);
5244 if ($showfeedback) {
5245 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5248 // Get the list of all modules that are properly installed.
5249 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5251 // Delete every instance of every module,
5252 // this has to be done before deleting of course level stuff.
5253 $locations = core_component::get_plugin_list('mod');
5254 foreach ($locations as $modname => $moddir) {
5255 if ($modname === 'NEWMODULE') {
5256 continue;
5258 if (array_key_exists($modname, $allmodules)) {
5259 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5260 FROM {".$modname."} m
5261 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5262 WHERE m.course = :courseid";
5263 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5264 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5266 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5267 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5269 if ($instances) {
5270 foreach ($instances as $cm) {
5271 if ($cm->id) {
5272 // Delete activity context questions and question categories.
5273 question_delete_activity($cm, $showfeedback);
5274 // Notify the competency subsystem.
5275 \core_competency\api::hook_course_module_deleted($cm);
5277 if (function_exists($moddelete)) {
5278 // This purges all module data in related tables, extra user prefs, settings, etc.
5279 $moddelete($cm->modinstance);
5280 } else {
5281 // NOTE: we should not allow installation of modules with missing delete support!
5282 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5283 $DB->delete_records($modname, array('id' => $cm->modinstance));
5286 if ($cm->id) {
5287 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5288 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5289 $DB->delete_records('course_modules', array('id' => $cm->id));
5293 if ($instances and $showfeedback) {
5294 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5296 } else {
5297 // Ooops, this module is not properly installed, force-delete it in the next block.
5301 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5303 // Delete completion defaults.
5304 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5306 // Remove all data from availability and completion tables that is associated
5307 // with course-modules belonging to this course. Note this is done even if the
5308 // features are not enabled now, in case they were enabled previously.
5309 $DB->delete_records_select('course_modules_completion',
5310 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5311 array($courseid));
5313 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5314 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5315 $allmodulesbyid = array_flip($allmodules);
5316 foreach ($cms as $cm) {
5317 if (array_key_exists($cm->module, $allmodulesbyid)) {
5318 try {
5319 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5320 } catch (Exception $e) {
5321 // Ignore weird or missing table problems.
5324 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5325 $DB->delete_records('course_modules', array('id' => $cm->id));
5328 if ($showfeedback) {
5329 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5332 // Delete questions and question categories.
5333 question_delete_course($course, $showfeedback);
5334 if ($showfeedback) {
5335 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5338 // Delete content bank contents.
5339 $cb = new \core_contentbank\contentbank();
5340 $cbdeleted = $cb->delete_contents($coursecontext);
5341 if ($showfeedback && $cbdeleted) {
5342 echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5345 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5346 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5347 foreach ($childcontexts as $childcontext) {
5348 $childcontext->delete();
5350 unset($childcontexts);
5352 // Remove all roles and enrolments by default.
5353 if (empty($options['keep_roles_and_enrolments'])) {
5354 // This hack is used in restore when deleting contents of existing course.
5355 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5356 enrol_course_delete($course);
5357 if ($showfeedback) {
5358 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5362 // Delete any groups, removing members and grouping/course links first.
5363 if (empty($options['keep_groups_and_groupings'])) {
5364 groups_delete_groupings($course->id, $showfeedback);
5365 groups_delete_groups($course->id, $showfeedback);
5368 // Filters be gone!
5369 filter_delete_all_for_context($coursecontext->id);
5371 // Notes, you shall not pass!
5372 note_delete_all($course->id);
5374 // Die comments!
5375 comment::delete_comments($coursecontext->id);
5377 // Ratings are history too.
5378 $delopt = new stdclass();
5379 $delopt->contextid = $coursecontext->id;
5380 $rm = new rating_manager();
5381 $rm->delete_ratings($delopt);
5383 // Delete course tags.
5384 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5386 // Notify the competency subsystem.
5387 \core_competency\api::hook_course_deleted($course);
5389 // Delete calendar events.
5390 $DB->delete_records('event', array('courseid' => $course->id));
5391 $fs->delete_area_files($coursecontext->id, 'calendar');
5393 // Delete all related records in other core tables that may have a courseid
5394 // This array stores the tables that need to be cleared, as
5395 // table_name => column_name that contains the course id.
5396 $tablestoclear = array(
5397 'backup_courses' => 'courseid', // Scheduled backup stuff.
5398 'user_lastaccess' => 'courseid', // User access info.
5400 foreach ($tablestoclear as $table => $col) {
5401 $DB->delete_records($table, array($col => $course->id));
5404 // Delete all course backup files.
5405 $fs->delete_area_files($coursecontext->id, 'backup');
5407 // Cleanup course record - remove links to deleted stuff.
5408 $oldcourse = new stdClass();
5409 $oldcourse->id = $course->id;
5410 $oldcourse->summary = '';
5411 $oldcourse->cacherev = 0;
5412 $oldcourse->legacyfiles = 0;
5413 if (!empty($options['keep_groups_and_groupings'])) {
5414 $oldcourse->defaultgroupingid = 0;
5416 $DB->update_record('course', $oldcourse);
5418 // Delete course sections.
5419 $DB->delete_records('course_sections', array('course' => $course->id));
5421 // Delete legacy, section and any other course files.
5422 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5424 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5425 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5426 // Easy, do not delete the context itself...
5427 $coursecontext->delete_content();
5428 } else {
5429 // Hack alert!!!!
5430 // We can not drop all context stuff because it would bork enrolments and roles,
5431 // there might be also files used by enrol plugins...
5434 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5435 // also some non-standard unsupported plugins may try to store something there.
5436 fulldelete($CFG->dataroot.'/'.$course->id);
5438 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5439 $cachemodinfo = cache::make('core', 'coursemodinfo');
5440 $cachemodinfo->delete($courseid);
5442 // Trigger a course content deleted event.
5443 $event = \core\event\course_content_deleted::create(array(
5444 'objectid' => $course->id,
5445 'context' => $coursecontext,
5446 'other' => array('shortname' => $course->shortname,
5447 'fullname' => $course->fullname,
5448 'options' => $options) // Passing this for legacy reasons.
5450 $event->add_record_snapshot('course', $course);
5451 $event->trigger();
5453 return true;
5457 * Change dates in module - used from course reset.
5459 * @param string $modname forum, assignment, etc
5460 * @param array $fields array of date fields from mod table
5461 * @param int $timeshift time difference
5462 * @param int $courseid
5463 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5464 * @return bool success
5466 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5467 global $CFG, $DB;
5468 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5470 $return = true;
5471 $params = array($timeshift, $courseid);
5472 foreach ($fields as $field) {
5473 $updatesql = "UPDATE {".$modname."}
5474 SET $field = $field + ?
5475 WHERE course=? AND $field<>0";
5476 if ($modid) {
5477 $updatesql .= ' AND id=?';
5478 $params[] = $modid;
5480 $return = $DB->execute($updatesql, $params) && $return;
5483 return $return;
5487 * This function will empty a course of user data.
5488 * It will retain the activities and the structure of the course.
5490 * @param object $data an object containing all the settings including courseid (without magic quotes)
5491 * @return array status array of array component, item, error
5493 function reset_course_userdata($data) {
5494 global $CFG, $DB;
5495 require_once($CFG->libdir.'/gradelib.php');
5496 require_once($CFG->libdir.'/completionlib.php');
5497 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5498 require_once($CFG->dirroot.'/group/lib.php');
5500 $data->courseid = $data->id;
5501 $context = context_course::instance($data->courseid);
5503 $eventparams = array(
5504 'context' => $context,
5505 'courseid' => $data->id,
5506 'other' => array(
5507 'reset_options' => (array) $data
5510 $event = \core\event\course_reset_started::create($eventparams);
5511 $event->trigger();
5513 // Calculate the time shift of dates.
5514 if (!empty($data->reset_start_date)) {
5515 // Time part of course startdate should be zero.
5516 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5517 } else {
5518 $data->timeshift = 0;
5521 // Result array: component, item, error.
5522 $status = array();
5524 // Start the resetting.
5525 $componentstr = get_string('general');
5527 // Move the course start time.
5528 if (!empty($data->reset_start_date) and $data->timeshift) {
5529 // Change course start data.
5530 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5531 // Update all course and group events - do not move activity events.
5532 $updatesql = "UPDATE {event}
5533 SET timestart = timestart + ?
5534 WHERE courseid=? AND instance=0";
5535 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5537 // Update any date activity restrictions.
5538 if ($CFG->enableavailability) {
5539 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5542 // Update completion expected dates.
5543 if ($CFG->enablecompletion) {
5544 $modinfo = get_fast_modinfo($data->courseid);
5545 $changed = false;
5546 foreach ($modinfo->get_cms() as $cm) {
5547 if ($cm->completion && !empty($cm->completionexpected)) {
5548 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5549 array('id' => $cm->id));
5550 $changed = true;
5554 // Clear course cache if changes made.
5555 if ($changed) {
5556 rebuild_course_cache($data->courseid, true);
5559 // Update course date completion criteria.
5560 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5563 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5566 if (!empty($data->reset_end_date)) {
5567 // If the user set a end date value respect it.
5568 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5569 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5570 // If there is a time shift apply it to the end date as well.
5571 $enddate = $data->reset_end_date_old + $data->timeshift;
5572 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5575 if (!empty($data->reset_events)) {
5576 $DB->delete_records('event', array('courseid' => $data->courseid));
5577 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5580 if (!empty($data->reset_notes)) {
5581 require_once($CFG->dirroot.'/notes/lib.php');
5582 note_delete_all($data->courseid);
5583 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5586 if (!empty($data->delete_blog_associations)) {
5587 require_once($CFG->dirroot.'/blog/lib.php');
5588 blog_remove_associations_for_course($data->courseid);
5589 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5592 if (!empty($data->reset_completion)) {
5593 // Delete course and activity completion information.
5594 $course = $DB->get_record('course', array('id' => $data->courseid));
5595 $cc = new completion_info($course);
5596 $cc->delete_all_completion_data();
5597 $status[] = array('component' => $componentstr,
5598 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5601 if (!empty($data->reset_competency_ratings)) {
5602 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5603 $status[] = array('component' => $componentstr,
5604 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5607 $componentstr = get_string('roles');
5609 if (!empty($data->reset_roles_overrides)) {
5610 $children = $context->get_child_contexts();
5611 foreach ($children as $child) {
5612 $child->delete_capabilities();
5614 $context->delete_capabilities();
5615 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5618 if (!empty($data->reset_roles_local)) {
5619 $children = $context->get_child_contexts();
5620 foreach ($children as $child) {
5621 role_unassign_all(array('contextid' => $child->id));
5623 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5626 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5627 $data->unenrolled = array();
5628 if (!empty($data->unenrol_users)) {
5629 $plugins = enrol_get_plugins(true);
5630 $instances = enrol_get_instances($data->courseid, true);
5631 foreach ($instances as $key => $instance) {
5632 if (!isset($plugins[$instance->enrol])) {
5633 unset($instances[$key]);
5634 continue;
5638 $usersroles = enrol_get_course_users_roles($data->courseid);
5639 foreach ($data->unenrol_users as $withroleid) {
5640 if ($withroleid) {
5641 $sql = "SELECT ue.*
5642 FROM {user_enrolments} ue
5643 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5644 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5645 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5646 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5648 } else {
5649 // Without any role assigned at course context.
5650 $sql = "SELECT ue.*
5651 FROM {user_enrolments} ue
5652 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5653 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5654 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5655 WHERE ra.id IS null";
5656 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5659 $rs = $DB->get_recordset_sql($sql, $params);
5660 foreach ($rs as $ue) {
5661 if (!isset($instances[$ue->enrolid])) {
5662 continue;
5664 $instance = $instances[$ue->enrolid];
5665 $plugin = $plugins[$instance->enrol];
5666 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5667 continue;
5670 if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5671 // If we don't remove all roles and user has more than one role, just remove this role.
5672 role_unassign($withroleid, $ue->userid, $context->id);
5674 unset($usersroles[$ue->userid][$withroleid]);
5675 } else {
5676 // If we remove all roles or user has only one role, unenrol user from course.
5677 $plugin->unenrol_user($instance, $ue->userid);
5679 $data->unenrolled[$ue->userid] = $ue->userid;
5681 $rs->close();
5684 if (!empty($data->unenrolled)) {
5685 $status[] = array(
5686 'component' => $componentstr,
5687 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5688 'error' => false
5692 $componentstr = get_string('groups');
5694 // Remove all group members.
5695 if (!empty($data->reset_groups_members)) {
5696 groups_delete_group_members($data->courseid);
5697 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5700 // Remove all groups.
5701 if (!empty($data->reset_groups_remove)) {
5702 groups_delete_groups($data->courseid, false);
5703 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5706 // Remove all grouping members.
5707 if (!empty($data->reset_groupings_members)) {
5708 groups_delete_groupings_groups($data->courseid, false);
5709 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5712 // Remove all groupings.
5713 if (!empty($data->reset_groupings_remove)) {
5714 groups_delete_groupings($data->courseid, false);
5715 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5718 // Look in every instance of every module for data to delete.
5719 $unsupportedmods = array();
5720 if ($allmods = $DB->get_records('modules') ) {
5721 foreach ($allmods as $mod) {
5722 $modname = $mod->name;
5723 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5724 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5725 if (file_exists($modfile)) {
5726 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5727 continue; // Skip mods with no instances.
5729 include_once($modfile);
5730 if (function_exists($moddeleteuserdata)) {
5731 $modstatus = $moddeleteuserdata($data);
5732 if (is_array($modstatus)) {
5733 $status = array_merge($status, $modstatus);
5734 } else {
5735 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5737 } else {
5738 $unsupportedmods[] = $mod;
5740 } else {
5741 debugging('Missing lib.php in '.$modname.' module!');
5743 // Update calendar events for all modules.
5744 course_module_bulk_update_calendar_events($modname, $data->courseid);
5748 // Mention unsupported mods.
5749 if (!empty($unsupportedmods)) {
5750 foreach ($unsupportedmods as $mod) {
5751 $status[] = array(
5752 'component' => get_string('modulenameplural', $mod->name),
5753 'item' => '',
5754 'error' => get_string('resetnotimplemented')
5759 $componentstr = get_string('gradebook', 'grades');
5760 // Reset gradebook,.
5761 if (!empty($data->reset_gradebook_items)) {
5762 remove_course_grades($data->courseid, false);
5763 grade_grab_course_grades($data->courseid);
5764 grade_regrade_final_grades($data->courseid);
5765 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5767 } else if (!empty($data->reset_gradebook_grades)) {
5768 grade_course_reset($data->courseid);
5769 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5771 // Reset comments.
5772 if (!empty($data->reset_comments)) {
5773 require_once($CFG->dirroot.'/comment/lib.php');
5774 comment::reset_course_page_comments($context);
5777 $event = \core\event\course_reset_ended::create($eventparams);
5778 $event->trigger();
5780 return $status;
5784 * Generate an email processing address.
5786 * @param int $modid
5787 * @param string $modargs
5788 * @return string Returns email processing address
5790 function generate_email_processing_address($modid, $modargs) {
5791 global $CFG;
5793 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5794 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5800 * @todo Finish documenting this function
5802 * @param string $modargs
5803 * @param string $body Currently unused
5805 function moodle_process_email($modargs, $body) {
5806 global $DB;
5808 // The first char should be an unencoded letter. We'll take this as an action.
5809 switch ($modargs[0]) {
5810 case 'B': { // Bounce.
5811 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5812 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5813 // Check the half md5 of their email.
5814 $md5check = substr(md5($user->email), 0, 16);
5815 if ($md5check == substr($modargs, -16)) {
5816 set_bounce_count($user);
5818 // Else maybe they've already changed it?
5821 break;
5822 // Maybe more later?
5826 // CORRESPONDENCE.
5829 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5831 * @param string $action 'get', 'buffer', 'close' or 'flush'
5832 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5834 function get_mailer($action='get') {
5835 global $CFG;
5837 /** @var moodle_phpmailer $mailer */
5838 static $mailer = null;
5839 static $counter = 0;
5841 if (!isset($CFG->smtpmaxbulk)) {
5842 $CFG->smtpmaxbulk = 1;
5845 if ($action == 'get') {
5846 $prevkeepalive = false;
5848 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5849 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5850 $counter++;
5851 // Reset the mailer.
5852 $mailer->Priority = 3;
5853 $mailer->CharSet = 'UTF-8'; // Our default.
5854 $mailer->ContentType = "text/plain";
5855 $mailer->Encoding = "8bit";
5856 $mailer->From = "root@localhost";
5857 $mailer->FromName = "Root User";
5858 $mailer->Sender = "";
5859 $mailer->Subject = "";
5860 $mailer->Body = "";
5861 $mailer->AltBody = "";
5862 $mailer->ConfirmReadingTo = "";
5864 $mailer->clearAllRecipients();
5865 $mailer->clearReplyTos();
5866 $mailer->clearAttachments();
5867 $mailer->clearCustomHeaders();
5868 return $mailer;
5871 $prevkeepalive = $mailer->SMTPKeepAlive;
5872 get_mailer('flush');
5875 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5876 $mailer = new moodle_phpmailer();
5878 $counter = 1;
5880 if ($CFG->smtphosts == 'qmail') {
5881 // Use Qmail system.
5882 $mailer->isQmail();
5884 } else if (empty($CFG->smtphosts)) {
5885 // Use PHP mail() = sendmail.
5886 $mailer->isMail();
5888 } else {
5889 // Use SMTP directly.
5890 $mailer->isSMTP();
5891 if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5892 $mailer->SMTPDebug = 3;
5894 // Specify main and backup servers.
5895 $mailer->Host = $CFG->smtphosts;
5896 // Specify secure connection protocol.
5897 $mailer->SMTPSecure = $CFG->smtpsecure;
5898 // Use previous keepalive.
5899 $mailer->SMTPKeepAlive = $prevkeepalive;
5901 if ($CFG->smtpuser) {
5902 // Use SMTP authentication.
5903 $mailer->SMTPAuth = true;
5904 $mailer->Username = $CFG->smtpuser;
5905 $mailer->Password = $CFG->smtppass;
5909 return $mailer;
5912 $nothing = null;
5914 // Keep smtp session open after sending.
5915 if ($action == 'buffer') {
5916 if (!empty($CFG->smtpmaxbulk)) {
5917 get_mailer('flush');
5918 $m = get_mailer();
5919 if ($m->Mailer == 'smtp') {
5920 $m->SMTPKeepAlive = true;
5923 return $nothing;
5926 // Close smtp session, but continue buffering.
5927 if ($action == 'flush') {
5928 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5929 if (!empty($mailer->SMTPDebug)) {
5930 echo '<pre>'."\n";
5932 $mailer->SmtpClose();
5933 if (!empty($mailer->SMTPDebug)) {
5934 echo '</pre>';
5937 return $nothing;
5940 // Close smtp session, do not buffer anymore.
5941 if ($action == 'close') {
5942 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5943 get_mailer('flush');
5944 $mailer->SMTPKeepAlive = false;
5946 $mailer = null; // Better force new instance.
5947 return $nothing;
5952 * A helper function to test for email diversion
5954 * @param string $email
5955 * @return bool Returns true if the email should be diverted
5957 function email_should_be_diverted($email) {
5958 global $CFG;
5960 if (empty($CFG->divertallemailsto)) {
5961 return false;
5964 if (empty($CFG->divertallemailsexcept)) {
5965 return true;
5968 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5969 foreach ($patterns as $pattern) {
5970 if (preg_match("/$pattern/", $email)) {
5971 return false;
5975 return true;
5979 * Generate a unique email Message-ID using the moodle domain and install path
5981 * @param string $localpart An optional unique message id prefix.
5982 * @return string The formatted ID ready for appending to the email headers.
5984 function generate_email_messageid($localpart = null) {
5985 global $CFG;
5987 $urlinfo = parse_url($CFG->wwwroot);
5988 $base = '@' . $urlinfo['host'];
5990 // If multiple moodles are on the same domain we want to tell them
5991 // apart so we add the install path to the local part. This means
5992 // that the id local part should never contain a / character so
5993 // we can correctly parse the id to reassemble the wwwroot.
5994 if (isset($urlinfo['path'])) {
5995 $base = $urlinfo['path'] . $base;
5998 if (empty($localpart)) {
5999 $localpart = uniqid('', true);
6002 // Because we may have an option /installpath suffix to the local part
6003 // of the id we need to escape any / chars which are in the $localpart.
6004 $localpart = str_replace('/', '%2F', $localpart);
6006 return '<' . $localpart . $base . '>';
6010 * Send an email to a specified user
6012 * @param stdClass $user A {@link $USER} object
6013 * @param stdClass $from A {@link $USER} object
6014 * @param string $subject plain text subject line of the email
6015 * @param string $messagetext plain text version of the message
6016 * @param string $messagehtml complete html version of the message (optional)
6017 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
6018 * the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
6019 * @param string $attachname the name of the file (extension indicates MIME)
6020 * @param bool $usetrueaddress determines whether $from email address should
6021 * be sent out. Will be overruled by user profile setting for maildisplay
6022 * @param string $replyto Email address to reply to
6023 * @param string $replytoname Name of reply to recipient
6024 * @param int $wordwrapwidth custom word wrap width, default 79
6025 * @return bool Returns true if mail was sent OK and false if there was an error.
6027 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
6028 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
6030 global $CFG, $PAGE, $SITE;
6032 if (empty($user) or empty($user->id)) {
6033 debugging('Can not send email to null user', DEBUG_DEVELOPER);
6034 return false;
6037 if (empty($user->email)) {
6038 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
6039 return false;
6042 if (!empty($user->deleted)) {
6043 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
6044 return false;
6047 if (defined('BEHAT_SITE_RUNNING')) {
6048 // Fake email sending in behat.
6049 return true;
6052 if (!empty($CFG->noemailever)) {
6053 // Hidden setting for development sites, set in config.php if needed.
6054 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
6055 return true;
6058 if (email_should_be_diverted($user->email)) {
6059 $subject = "[DIVERTED {$user->email}] $subject";
6060 $user = clone($user);
6061 $user->email = $CFG->divertallemailsto;
6064 // Skip mail to suspended users.
6065 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
6066 return true;
6069 if (!validate_email($user->email)) {
6070 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
6071 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
6072 return false;
6075 if (over_bounce_threshold($user)) {
6076 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
6077 return false;
6080 // TLD .invalid is specifically reserved for invalid domain names.
6081 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
6082 if (substr($user->email, -8) == '.invalid') {
6083 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
6084 return true; // This is not an error.
6087 // If the user is a remote mnet user, parse the email text for URL to the
6088 // wwwroot and modify the url to direct the user's browser to login at their
6089 // home site (identity provider - idp) before hitting the link itself.
6090 if (is_mnet_remote_user($user)) {
6091 require_once($CFG->dirroot.'/mnet/lib.php');
6093 $jumpurl = mnet_get_idp_jump_url($user);
6094 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
6096 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
6097 $callback,
6098 $messagetext);
6099 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
6100 $callback,
6101 $messagehtml);
6103 $mail = get_mailer();
6105 if (!empty($mail->SMTPDebug)) {
6106 echo '<pre>' . "\n";
6109 $temprecipients = array();
6110 $tempreplyto = array();
6112 // Make sure that we fall back onto some reasonable no-reply address.
6113 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
6114 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
6116 if (!validate_email($noreplyaddress)) {
6117 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6118 $noreplyaddress = $noreplyaddressdefault;
6121 // Make up an email address for handling bounces.
6122 if (!empty($CFG->handlebounces)) {
6123 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
6124 $mail->Sender = generate_email_processing_address(0, $modargs);
6125 } else {
6126 $mail->Sender = $noreplyaddress;
6129 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6130 if (!empty($replyto) && !validate_email($replyto)) {
6131 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6132 $replyto = $noreplyaddress;
6135 if (is_string($from)) { // So we can pass whatever we want if there is need.
6136 $mail->From = $noreplyaddress;
6137 $mail->FromName = $from;
6138 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6139 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6140 // in a course with the sender.
6141 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6142 if (!validate_email($from->email)) {
6143 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
6144 // Better not to use $noreplyaddress in this case.
6145 return false;
6147 $mail->From = $from->email;
6148 $fromdetails = new stdClass();
6149 $fromdetails->name = fullname($from);
6150 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6151 $fromdetails->siteshortname = format_string($SITE->shortname);
6152 $fromstring = $fromdetails->name;
6153 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
6154 $fromstring = get_string('emailvia', 'core', $fromdetails);
6156 $mail->FromName = $fromstring;
6157 if (empty($replyto)) {
6158 $tempreplyto[] = array($from->email, fullname($from));
6160 } else {
6161 $mail->From = $noreplyaddress;
6162 $fromdetails = new stdClass();
6163 $fromdetails->name = fullname($from);
6164 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6165 $fromdetails->siteshortname = format_string($SITE->shortname);
6166 $fromstring = $fromdetails->name;
6167 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
6168 $fromstring = get_string('emailvia', 'core', $fromdetails);
6170 $mail->FromName = $fromstring;
6171 if (empty($replyto)) {
6172 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6176 if (!empty($replyto)) {
6177 $tempreplyto[] = array($replyto, $replytoname);
6180 $temprecipients[] = array($user->email, fullname($user));
6182 // Set word wrap.
6183 $mail->WordWrap = $wordwrapwidth;
6185 if (!empty($from->customheaders)) {
6186 // Add custom headers.
6187 if (is_array($from->customheaders)) {
6188 foreach ($from->customheaders as $customheader) {
6189 $mail->addCustomHeader($customheader);
6191 } else {
6192 $mail->addCustomHeader($from->customheaders);
6196 // If the X-PHP-Originating-Script email header is on then also add an additional
6197 // header with details of where exactly in moodle the email was triggered from,
6198 // either a call to message_send() or to email_to_user().
6199 if (ini_get('mail.add_x_header')) {
6201 $stack = debug_backtrace(false);
6202 $origin = $stack[0];
6204 foreach ($stack as $depth => $call) {
6205 if ($call['function'] == 'message_send') {
6206 $origin = $call;
6210 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6211 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6212 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6215 if (!empty($from->priority)) {
6216 $mail->Priority = $from->priority;
6219 $renderer = $PAGE->get_renderer('core');
6220 $context = array(
6221 'sitefullname' => $SITE->fullname,
6222 'siteshortname' => $SITE->shortname,
6223 'sitewwwroot' => $CFG->wwwroot,
6224 'subject' => $subject,
6225 'prefix' => $CFG->emailsubjectprefix,
6226 'to' => $user->email,
6227 'toname' => fullname($user),
6228 'from' => $mail->From,
6229 'fromname' => $mail->FromName,
6231 if (!empty($tempreplyto[0])) {
6232 $context['replyto'] = $tempreplyto[0][0];
6233 $context['replytoname'] = $tempreplyto[0][1];
6235 if ($user->id > 0) {
6236 $context['touserid'] = $user->id;
6237 $context['tousername'] = $user->username;
6240 if (!empty($user->mailformat) && $user->mailformat == 1) {
6241 // Only process html templates if the user preferences allow html email.
6243 if (!$messagehtml) {
6244 // If no html has been given, BUT there is an html wrapping template then
6245 // auto convert the text to html and then wrap it.
6246 $messagehtml = trim(text_to_html($messagetext));
6248 $context['body'] = $messagehtml;
6249 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6252 $context['body'] = html_to_text(nl2br($messagetext));
6253 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6254 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6255 $messagetext = $renderer->render_from_template('core/email_text', $context);
6257 // Autogenerate a MessageID if it's missing.
6258 if (empty($mail->MessageID)) {
6259 $mail->MessageID = generate_email_messageid();
6262 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6263 // Don't ever send HTML to users who don't want it.
6264 $mail->isHTML(true);
6265 $mail->Encoding = 'quoted-printable';
6266 $mail->Body = $messagehtml;
6267 $mail->AltBody = "\n$messagetext\n";
6268 } else {
6269 $mail->IsHTML(false);
6270 $mail->Body = "\n$messagetext\n";
6273 if ($attachment && $attachname) {
6274 if (preg_match( "~\\.\\.~" , $attachment )) {
6275 // Security check for ".." in dir path.
6276 $supportuser = core_user::get_support_user();
6277 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6278 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6279 } else {
6280 require_once($CFG->libdir.'/filelib.php');
6281 $mimetype = mimeinfo('type', $attachname);
6283 $attachmentpath = $attachment;
6285 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6286 $attachpath = str_replace('\\', '/', $attachmentpath);
6288 // Add allowed paths to an array (also check if it's not empty).
6289 $allowedpaths = array_filter([
6290 $CFG->cachedir,
6291 $CFG->dataroot,
6292 $CFG->dirroot,
6293 $CFG->localcachedir,
6294 $CFG->tempdir
6296 // Set addpath to true.
6297 $addpath = true;
6298 // Check if attachment includes one of the allowed paths.
6299 foreach ($allowedpaths as $tmpvar) {
6300 // Make sure both variables are normalised before comparing.
6301 $temppath = str_replace('\\', '/', realpath($tmpvar));
6302 // Set addpath to false if the attachment includes one of the allowed paths.
6303 if (strpos($attachpath, $temppath) === 0) {
6304 $addpath = false;
6305 break;
6309 // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
6310 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6311 if ($addpath == true) {
6312 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
6315 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
6319 // Check if the email should be sent in an other charset then the default UTF-8.
6320 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6322 // Use the defined site mail charset or eventually the one preferred by the recipient.
6323 $charset = $CFG->sitemailcharset;
6324 if (!empty($CFG->allowusermailcharset)) {
6325 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6326 $charset = $useremailcharset;
6330 // Convert all the necessary strings if the charset is supported.
6331 $charsets = get_list_of_charsets();
6332 unset($charsets['UTF-8']);
6333 if (in_array($charset, $charsets)) {
6334 $mail->CharSet = $charset;
6335 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6336 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6337 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6338 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6340 foreach ($temprecipients as $key => $values) {
6341 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6343 foreach ($tempreplyto as $key => $values) {
6344 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6349 foreach ($temprecipients as $values) {
6350 $mail->addAddress($values[0], $values[1]);
6352 foreach ($tempreplyto as $values) {
6353 $mail->addReplyTo($values[0], $values[1]);
6356 if ($mail->send()) {
6357 set_send_count($user);
6358 if (!empty($mail->SMTPDebug)) {
6359 echo '</pre>';
6361 return true;
6362 } else {
6363 // Trigger event for failing to send email.
6364 $event = \core\event\email_failed::create(array(
6365 'context' => context_system::instance(),
6366 'userid' => $from->id,
6367 'relateduserid' => $user->id,
6368 'other' => array(
6369 'subject' => $subject,
6370 'message' => $messagetext,
6371 'errorinfo' => $mail->ErrorInfo
6374 $event->trigger();
6375 if (CLI_SCRIPT) {
6376 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6378 if (!empty($mail->SMTPDebug)) {
6379 echo '</pre>';
6381 return false;
6386 * Check to see if a user's real email address should be used for the "From" field.
6388 * @param object $from The user object for the user we are sending the email from.
6389 * @param object $user The user object that we are sending the email to.
6390 * @param array $unused No longer used.
6391 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6393 function can_send_from_real_email_address($from, $user, $unused = null) {
6394 global $CFG;
6395 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6396 return false;
6398 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6399 // Email is in the list of allowed domains for sending email,
6400 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6401 // in a course with the sender.
6402 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6403 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6404 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6405 && enrol_get_shared_courses($user, $from, false, true)))) {
6406 return true;
6408 return false;
6412 * Generate a signoff for emails based on support settings
6414 * @return string
6416 function generate_email_signoff() {
6417 global $CFG;
6419 $signoff = "\n";
6420 if (!empty($CFG->supportname)) {
6421 $signoff .= $CFG->supportname."\n";
6423 if (!empty($CFG->supportemail)) {
6424 $signoff .= $CFG->supportemail."\n";
6426 if (!empty($CFG->supportpage)) {
6427 $signoff .= $CFG->supportpage."\n";
6429 return $signoff;
6433 * Sets specified user's password and send the new password to the user via email.
6435 * @param stdClass $user A {@link $USER} object
6436 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6437 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6439 function setnew_password_and_mail($user, $fasthash = false) {
6440 global $CFG, $DB;
6442 // We try to send the mail in language the user understands,
6443 // unfortunately the filter_string() does not support alternative langs yet
6444 // so multilang will not work properly for site->fullname.
6445 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6447 $site = get_site();
6449 $supportuser = core_user::get_support_user();
6451 $newpassword = generate_password();
6453 update_internal_user_password($user, $newpassword, $fasthash);
6455 $a = new stdClass();
6456 $a->firstname = fullname($user, true);
6457 $a->sitename = format_string($site->fullname);
6458 $a->username = $user->username;
6459 $a->newpassword = $newpassword;
6460 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6461 $a->signoff = generate_email_signoff();
6463 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6465 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6467 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6468 return email_to_user($user, $supportuser, $subject, $message);
6473 * Resets specified user's password and send the new password to the user via email.
6475 * @param stdClass $user A {@link $USER} object
6476 * @return bool Returns true if mail was sent OK and false if there was an error.
6478 function reset_password_and_mail($user) {
6479 global $CFG;
6481 $site = get_site();
6482 $supportuser = core_user::get_support_user();
6484 $userauth = get_auth_plugin($user->auth);
6485 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6486 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6487 return false;
6490 $newpassword = generate_password();
6492 if (!$userauth->user_update_password($user, $newpassword)) {
6493 print_error("cannotsetpassword");
6496 $a = new stdClass();
6497 $a->firstname = $user->firstname;
6498 $a->lastname = $user->lastname;
6499 $a->sitename = format_string($site->fullname);
6500 $a->username = $user->username;
6501 $a->newpassword = $newpassword;
6502 $a->link = $CFG->wwwroot .'/login/change_password.php';
6503 $a->signoff = generate_email_signoff();
6505 $message = get_string('newpasswordtext', '', $a);
6507 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6509 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6511 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6512 return email_to_user($user, $supportuser, $subject, $message);
6516 * Send email to specified user with confirmation text and activation link.
6518 * @param stdClass $user A {@link $USER} object
6519 * @param string $confirmationurl user confirmation URL
6520 * @return bool Returns true if mail was sent OK and false if there was an error.
6522 function send_confirmation_email($user, $confirmationurl = null) {
6523 global $CFG;
6525 $site = get_site();
6526 $supportuser = core_user::get_support_user();
6528 $data = new stdClass();
6529 $data->firstname = fullname($user);
6530 $data->sitename = format_string($site->fullname);
6531 $data->admin = generate_email_signoff();
6533 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6535 if (empty($confirmationurl)) {
6536 $confirmationurl = '/login/confirm.php';
6539 $confirmationurl = new moodle_url($confirmationurl);
6540 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6541 $confirmationurl->remove_params('data');
6542 $confirmationpath = $confirmationurl->out(false);
6544 // We need to custom encode the username to include trailing dots in the link.
6545 // Because of this custom encoding we can't use moodle_url directly.
6546 // Determine if a query string is present in the confirmation url.
6547 $hasquerystring = strpos($confirmationpath, '?') !== false;
6548 // Perform normal url encoding of the username first.
6549 $username = urlencode($user->username);
6550 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6551 $username = str_replace('.', '%2E', $username);
6553 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6555 $message = get_string('emailconfirmation', '', $data);
6556 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6558 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6559 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6563 * Sends a password change confirmation email.
6565 * @param stdClass $user A {@link $USER} object
6566 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6567 * @return bool Returns true if mail was sent OK and false if there was an error.
6569 function send_password_change_confirmation_email($user, $resetrecord) {
6570 global $CFG;
6572 $site = get_site();
6573 $supportuser = core_user::get_support_user();
6574 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6576 $data = new stdClass();
6577 $data->firstname = $user->firstname;
6578 $data->lastname = $user->lastname;
6579 $data->username = $user->username;
6580 $data->sitename = format_string($site->fullname);
6581 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6582 $data->admin = generate_email_signoff();
6583 $data->resetminutes = $pwresetmins;
6585 $message = get_string('emailresetconfirmation', '', $data);
6586 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6588 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6589 return email_to_user($user, $supportuser, $subject, $message);
6594 * Sends an email containing information on how to change your password.
6596 * @param stdClass $user A {@link $USER} object
6597 * @return bool Returns true if mail was sent OK and false if there was an error.
6599 function send_password_change_info($user) {
6600 $site = get_site();
6601 $supportuser = core_user::get_support_user();
6603 $data = new stdClass();
6604 $data->firstname = $user->firstname;
6605 $data->lastname = $user->lastname;
6606 $data->username = $user->username;
6607 $data->sitename = format_string($site->fullname);
6608 $data->admin = generate_email_signoff();
6610 if (!is_enabled_auth($user->auth)) {
6611 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6612 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6613 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6614 return email_to_user($user, $supportuser, $subject, $message);
6617 $userauth = get_auth_plugin($user->auth);
6618 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6620 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6621 return email_to_user($user, $supportuser, $subject, $message);
6625 * Check that an email is allowed. It returns an error message if there was a problem.
6627 * @param string $email Content of email
6628 * @return string|false
6630 function email_is_not_allowed($email) {
6631 global $CFG;
6633 // Comparing lowercase domains.
6634 $email = strtolower($email);
6635 if (!empty($CFG->allowemailaddresses)) {
6636 $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6637 foreach ($allowed as $allowedpattern) {
6638 $allowedpattern = trim($allowedpattern);
6639 if (!$allowedpattern) {
6640 continue;
6642 if (strpos($allowedpattern, '.') === 0) {
6643 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6644 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6645 return false;
6648 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6649 return false;
6652 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6654 } else if (!empty($CFG->denyemailaddresses)) {
6655 $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6656 foreach ($denied as $deniedpattern) {
6657 $deniedpattern = trim($deniedpattern);
6658 if (!$deniedpattern) {
6659 continue;
6661 if (strpos($deniedpattern, '.') === 0) {
6662 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6663 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6664 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6667 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6668 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6673 return false;
6676 // FILE HANDLING.
6679 * Returns local file storage instance
6681 * @return file_storage
6683 function get_file_storage($reset = false) {
6684 global $CFG;
6686 static $fs = null;
6688 if ($reset) {
6689 $fs = null;
6690 return;
6693 if ($fs) {
6694 return $fs;
6697 require_once("$CFG->libdir/filelib.php");
6699 $fs = new file_storage();
6701 return $fs;
6705 * Returns local file storage instance
6707 * @return file_browser
6709 function get_file_browser() {
6710 global $CFG;
6712 static $fb = null;
6714 if ($fb) {
6715 return $fb;
6718 require_once("$CFG->libdir/filelib.php");
6720 $fb = new file_browser();
6722 return $fb;
6726 * Returns file packer
6728 * @param string $mimetype default application/zip
6729 * @return file_packer
6731 function get_file_packer($mimetype='application/zip') {
6732 global $CFG;
6734 static $fp = array();
6736 if (isset($fp[$mimetype])) {
6737 return $fp[$mimetype];
6740 switch ($mimetype) {
6741 case 'application/zip':
6742 case 'application/vnd.moodle.profiling':
6743 $classname = 'zip_packer';
6744 break;
6746 case 'application/x-gzip' :
6747 $classname = 'tgz_packer';
6748 break;
6750 case 'application/vnd.moodle.backup':
6751 $classname = 'mbz_packer';
6752 break;
6754 default:
6755 return false;
6758 require_once("$CFG->libdir/filestorage/$classname.php");
6759 $fp[$mimetype] = new $classname();
6761 return $fp[$mimetype];
6765 * Returns current name of file on disk if it exists.
6767 * @param string $newfile File to be verified
6768 * @return string Current name of file on disk if true
6770 function valid_uploaded_file($newfile) {
6771 if (empty($newfile)) {
6772 return '';
6774 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6775 return $newfile['tmp_name'];
6776 } else {
6777 return '';
6782 * Returns the maximum size for uploading files.
6784 * There are seven possible upload limits:
6785 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6786 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6787 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6788 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6789 * 5. by the Moodle admin in $CFG->maxbytes
6790 * 6. by the teacher in the current course $course->maxbytes
6791 * 7. by the teacher for the current module, eg $assignment->maxbytes
6793 * These last two are passed to this function as arguments (in bytes).
6794 * Anything defined as 0 is ignored.
6795 * The smallest of all the non-zero numbers is returned.
6797 * @todo Finish documenting this function
6799 * @param int $sitebytes Set maximum size
6800 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6801 * @param int $modulebytes Current module ->maxbytes (in bytes)
6802 * @param bool $unused This parameter has been deprecated and is not used any more.
6803 * @return int The maximum size for uploading files.
6805 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6807 if (! $filesize = ini_get('upload_max_filesize')) {
6808 $filesize = '5M';
6810 $minimumsize = get_real_size($filesize);
6812 if ($postsize = ini_get('post_max_size')) {
6813 $postsize = get_real_size($postsize);
6814 if ($postsize < $minimumsize) {
6815 $minimumsize = $postsize;
6819 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6820 $minimumsize = $sitebytes;
6823 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6824 $minimumsize = $coursebytes;
6827 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6828 $minimumsize = $modulebytes;
6831 return $minimumsize;
6835 * Returns the maximum size for uploading files for the current user
6837 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6839 * @param context $context The context in which to check user capabilities
6840 * @param int $sitebytes Set maximum size
6841 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6842 * @param int $modulebytes Current module ->maxbytes (in bytes)
6843 * @param stdClass $user The user
6844 * @param bool $unused This parameter has been deprecated and is not used any more.
6845 * @return int The maximum size for uploading files.
6847 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6848 $unused = false) {
6849 global $USER;
6851 if (empty($user)) {
6852 $user = $USER;
6855 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6856 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6859 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6863 * Returns an array of possible sizes in local language
6865 * Related to {@link get_max_upload_file_size()} - this function returns an
6866 * array of possible sizes in an array, translated to the
6867 * local language.
6869 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6871 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6872 * with the value set to 0. This option will be the first in the list.
6874 * @uses SORT_NUMERIC
6875 * @param int $sitebytes Set maximum size
6876 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6877 * @param int $modulebytes Current module ->maxbytes (in bytes)
6878 * @param int|array $custombytes custom upload size/s which will be added to list,
6879 * Only value/s smaller then maxsize will be added to list.
6880 * @return array
6882 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6883 global $CFG;
6885 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6886 return array();
6889 if ($sitebytes == 0) {
6890 // Will get the minimum of upload_max_filesize or post_max_size.
6891 $sitebytes = get_max_upload_file_size();
6894 $filesize = array();
6895 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6896 5242880, 10485760, 20971520, 52428800, 104857600,
6897 262144000, 524288000, 786432000, 1073741824,
6898 2147483648, 4294967296, 8589934592);
6900 // If custombytes is given and is valid then add it to the list.
6901 if (is_number($custombytes) and $custombytes > 0) {
6902 $custombytes = (int)$custombytes;
6903 if (!in_array($custombytes, $sizelist)) {
6904 $sizelist[] = $custombytes;
6906 } else if (is_array($custombytes)) {
6907 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6910 // Allow maxbytes to be selected if it falls outside the above boundaries.
6911 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6912 // Note: get_real_size() is used in order to prevent problems with invalid values.
6913 $sizelist[] = get_real_size($CFG->maxbytes);
6916 foreach ($sizelist as $sizebytes) {
6917 if ($sizebytes < $maxsize && $sizebytes > 0) {
6918 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6922 $limitlevel = '';
6923 $displaysize = '';
6924 if ($modulebytes &&
6925 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6926 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6927 $limitlevel = get_string('activity', 'core');
6928 $displaysize = display_size($modulebytes);
6929 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6931 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6932 $limitlevel = get_string('course', 'core');
6933 $displaysize = display_size($coursebytes);
6934 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6936 } else if ($sitebytes) {
6937 $limitlevel = get_string('site', 'core');
6938 $displaysize = display_size($sitebytes);
6939 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6942 krsort($filesize, SORT_NUMERIC);
6943 if ($limitlevel) {
6944 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6945 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6948 return $filesize;
6952 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6954 * If excludefiles is defined, then that file/directory is ignored
6955 * If getdirs is true, then (sub)directories are included in the output
6956 * If getfiles is true, then files are included in the output
6957 * (at least one of these must be true!)
6959 * @todo Finish documenting this function. Add examples of $excludefile usage.
6961 * @param string $rootdir A given root directory to start from
6962 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6963 * @param bool $descend If true then subdirectories are recursed as well
6964 * @param bool $getdirs If true then (sub)directories are included in the output
6965 * @param bool $getfiles If true then files are included in the output
6966 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6968 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6970 $dirs = array();
6972 if (!$getdirs and !$getfiles) { // Nothing to show.
6973 return $dirs;
6976 if (!is_dir($rootdir)) { // Must be a directory.
6977 return $dirs;
6980 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6981 return $dirs;
6984 if (!is_array($excludefiles)) {
6985 $excludefiles = array($excludefiles);
6988 while (false !== ($file = readdir($dir))) {
6989 $firstchar = substr($file, 0, 1);
6990 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6991 continue;
6993 $fullfile = $rootdir .'/'. $file;
6994 if (filetype($fullfile) == 'dir') {
6995 if ($getdirs) {
6996 $dirs[] = $file;
6998 if ($descend) {
6999 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
7000 foreach ($subdirs as $subdir) {
7001 $dirs[] = $file .'/'. $subdir;
7004 } else if ($getfiles) {
7005 $dirs[] = $file;
7008 closedir($dir);
7010 asort($dirs);
7012 return $dirs;
7017 * Adds up all the files in a directory and works out the size.
7019 * @param string $rootdir The directory to start from
7020 * @param string $excludefile A file to exclude when summing directory size
7021 * @return int The summed size of all files and subfiles within the root directory
7023 function get_directory_size($rootdir, $excludefile='') {
7024 global $CFG;
7026 // Do it this way if we can, it's much faster.
7027 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
7028 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
7029 $output = null;
7030 $return = null;
7031 exec($command, $output, $return);
7032 if (is_array($output)) {
7033 // We told it to return k.
7034 return get_real_size(intval($output[0]).'k');
7038 if (!is_dir($rootdir)) {
7039 // Must be a directory.
7040 return 0;
7043 if (!$dir = @opendir($rootdir)) {
7044 // Can't open it for some reason.
7045 return 0;
7048 $size = 0;
7050 while (false !== ($file = readdir($dir))) {
7051 $firstchar = substr($file, 0, 1);
7052 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
7053 continue;
7055 $fullfile = $rootdir .'/'. $file;
7056 if (filetype($fullfile) == 'dir') {
7057 $size += get_directory_size($fullfile, $excludefile);
7058 } else {
7059 $size += filesize($fullfile);
7062 closedir($dir);
7064 return $size;
7068 * Converts bytes into display form
7070 * @static string $gb Localized string for size in gigabytes
7071 * @static string $mb Localized string for size in megabytes
7072 * @static string $kb Localized string for size in kilobytes
7073 * @static string $b Localized string for size in bytes
7074 * @param int $size The size to convert to human readable form
7075 * @return string
7077 function display_size($size) {
7079 static $gb, $mb, $kb, $b;
7081 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
7082 return get_string('unlimited');
7085 if (empty($gb)) {
7086 $gb = get_string('sizegb');
7087 $mb = get_string('sizemb');
7088 $kb = get_string('sizekb');
7089 $b = get_string('sizeb');
7092 if ($size >= 1073741824) {
7093 $size = round($size / 1073741824 * 10) / 10 . $gb;
7094 } else if ($size >= 1048576) {
7095 $size = round($size / 1048576 * 10) / 10 . $mb;
7096 } else if ($size >= 1024) {
7097 $size = round($size / 1024 * 10) / 10 . $kb;
7098 } else {
7099 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
7101 return $size;
7105 * Cleans a given filename by removing suspicious or troublesome characters
7107 * @see clean_param()
7108 * @param string $string file name
7109 * @return string cleaned file name
7111 function clean_filename($string) {
7112 return clean_param($string, PARAM_FILE);
7115 // STRING TRANSLATION.
7118 * Returns the code for the current language
7120 * @category string
7121 * @return string
7123 function current_language() {
7124 global $CFG, $USER, $SESSION, $COURSE;
7126 if (!empty($SESSION->forcelang)) {
7127 // Allows overriding course-forced language (useful for admins to check
7128 // issues in courses whose language they don't understand).
7129 // Also used by some code to temporarily get language-related information in a
7130 // specific language (see force_current_language()).
7131 $return = $SESSION->forcelang;
7133 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
7134 // Course language can override all other settings for this page.
7135 $return = $COURSE->lang;
7137 } else if (!empty($SESSION->lang)) {
7138 // Session language can override other settings.
7139 $return = $SESSION->lang;
7141 } else if (!empty($USER->lang)) {
7142 $return = $USER->lang;
7144 } else if (isset($CFG->lang)) {
7145 $return = $CFG->lang;
7147 } else {
7148 $return = 'en';
7151 // Just in case this slipped in from somewhere by accident.
7152 $return = str_replace('_utf8', '', $return);
7154 return $return;
7158 * Returns parent language of current active language if defined
7160 * @category string
7161 * @param string $lang null means current language
7162 * @return string
7164 function get_parent_language($lang=null) {
7166 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7168 if ($parentlang === 'en') {
7169 $parentlang = '';
7172 return $parentlang;
7176 * Force the current language to get strings and dates localised in the given language.
7178 * After calling this function, all strings will be provided in the given language
7179 * until this function is called again, or equivalent code is run.
7181 * @param string $language
7182 * @return string previous $SESSION->forcelang value
7184 function force_current_language($language) {
7185 global $SESSION;
7186 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
7187 if ($language !== $sessionforcelang) {
7188 // Seting forcelang to null or an empty string disables it's effect.
7189 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
7190 $SESSION->forcelang = $language;
7191 moodle_setlocale();
7194 return $sessionforcelang;
7198 * Returns current string_manager instance.
7200 * The param $forcereload is needed for CLI installer only where the string_manager instance
7201 * must be replaced during the install.php script life time.
7203 * @category string
7204 * @param bool $forcereload shall the singleton be released and new instance created instead?
7205 * @return core_string_manager
7207 function get_string_manager($forcereload=false) {
7208 global $CFG;
7210 static $singleton = null;
7212 if ($forcereload) {
7213 $singleton = null;
7215 if ($singleton === null) {
7216 if (empty($CFG->early_install_lang)) {
7218 $transaliases = array();
7219 if (empty($CFG->langlist)) {
7220 $translist = array();
7221 } else {
7222 $translist = explode(',', $CFG->langlist);
7223 $translist = array_map('trim', $translist);
7224 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7225 foreach ($translist as $i => $value) {
7226 $parts = preg_split('/\s*\|\s*/', $value, 2);
7227 if (count($parts) == 2) {
7228 $transaliases[$parts[0]] = $parts[1];
7229 $translist[$i] = $parts[0];
7234 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7235 $classname = $CFG->config_php_settings['customstringmanager'];
7237 if (class_exists($classname)) {
7238 $implements = class_implements($classname);
7240 if (isset($implements['core_string_manager'])) {
7241 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7242 return $singleton;
7244 } else {
7245 debugging('Unable to instantiate custom string manager: class '.$classname.
7246 ' does not implement the core_string_manager interface.');
7249 } else {
7250 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7254 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7256 } else {
7257 $singleton = new core_string_manager_install();
7261 return $singleton;
7265 * Returns a localized string.
7267 * Returns the translated string specified by $identifier as
7268 * for $module. Uses the same format files as STphp.
7269 * $a is an object, string or number that can be used
7270 * within translation strings
7272 * eg 'hello {$a->firstname} {$a->lastname}'
7273 * or 'hello {$a}'
7275 * If you would like to directly echo the localized string use
7276 * the function {@link print_string()}
7278 * Example usage of this function involves finding the string you would
7279 * like a local equivalent of and using its identifier and module information
7280 * to retrieve it.<br/>
7281 * If you open moodle/lang/en/moodle.php and look near line 278
7282 * you will find a string to prompt a user for their word for 'course'
7283 * <code>
7284 * $string['course'] = 'Course';
7285 * </code>
7286 * So if you want to display the string 'Course'
7287 * in any language that supports it on your site
7288 * you just need to use the identifier 'course'
7289 * <code>
7290 * $mystring = '<strong>'. get_string('course') .'</strong>';
7291 * or
7292 * </code>
7293 * If the string you want is in another file you'd take a slightly
7294 * different approach. Looking in moodle/lang/en/calendar.php you find
7295 * around line 75:
7296 * <code>
7297 * $string['typecourse'] = 'Course event';
7298 * </code>
7299 * If you want to display the string "Course event" in any language
7300 * supported you would use the identifier 'typecourse' and the module 'calendar'
7301 * (because it is in the file calendar.php):
7302 * <code>
7303 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7304 * </code>
7306 * As a last resort, should the identifier fail to map to a string
7307 * the returned string will be [[ $identifier ]]
7309 * In Moodle 2.3 there is a new argument to this function $lazyload.
7310 * Setting $lazyload to true causes get_string to return a lang_string object
7311 * rather than the string itself. The fetching of the string is then put off until
7312 * the string object is first used. The object can be used by calling it's out
7313 * method or by casting the object to a string, either directly e.g.
7314 * (string)$stringobject
7315 * or indirectly by using the string within another string or echoing it out e.g.
7316 * echo $stringobject
7317 * return "<p>{$stringobject}</p>";
7318 * It is worth noting that using $lazyload and attempting to use the string as an
7319 * array key will cause a fatal error as objects cannot be used as array keys.
7320 * But you should never do that anyway!
7321 * For more information {@link lang_string}
7323 * @category string
7324 * @param string $identifier The key identifier for the localized string
7325 * @param string $component The module where the key identifier is stored,
7326 * usually expressed as the filename in the language pack without the
7327 * .php on the end but can also be written as mod/forum or grade/export/xls.
7328 * If none is specified then moodle.php is used.
7329 * @param string|object|array $a An object, string or number that can be used
7330 * within translation strings
7331 * @param bool $lazyload If set to true a string object is returned instead of
7332 * the string itself. The string then isn't calculated until it is first used.
7333 * @return string The localized string.
7334 * @throws coding_exception
7336 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7337 global $CFG;
7339 // If the lazy load argument has been supplied return a lang_string object
7340 // instead.
7341 // We need to make sure it is true (and a bool) as you will see below there
7342 // used to be a forth argument at one point.
7343 if ($lazyload === true) {
7344 return new lang_string($identifier, $component, $a);
7347 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7348 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7351 // There is now a forth argument again, this time it is a boolean however so
7352 // we can still check for the old extralocations parameter.
7353 if (!is_bool($lazyload) && !empty($lazyload)) {
7354 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7357 if (strpos($component, '/') !== false) {
7358 debugging('The module name you passed to get_string is the deprecated format ' .
7359 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7360 $componentpath = explode('/', $component);
7362 switch ($componentpath[0]) {
7363 case 'mod':
7364 $component = $componentpath[1];
7365 break;
7366 case 'blocks':
7367 case 'block':
7368 $component = 'block_'.$componentpath[1];
7369 break;
7370 case 'enrol':
7371 $component = 'enrol_'.$componentpath[1];
7372 break;
7373 case 'format':
7374 $component = 'format_'.$componentpath[1];
7375 break;
7376 case 'grade':
7377 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7378 break;
7382 $result = get_string_manager()->get_string($identifier, $component, $a);
7384 // Debugging feature lets you display string identifier and component.
7385 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7386 $result .= ' {' . $identifier . '/' . $component . '}';
7388 return $result;
7392 * Converts an array of strings to their localized value.
7394 * @param array $array An array of strings
7395 * @param string $component The language module that these strings can be found in.
7396 * @return stdClass translated strings.
7398 function get_strings($array, $component = '') {
7399 $string = new stdClass;
7400 foreach ($array as $item) {
7401 $string->$item = get_string($item, $component);
7403 return $string;
7407 * Prints out a translated string.
7409 * Prints out a translated string using the return value from the {@link get_string()} function.
7411 * Example usage of this function when the string is in the moodle.php file:<br/>
7412 * <code>
7413 * echo '<strong>';
7414 * print_string('course');
7415 * echo '</strong>';
7416 * </code>
7418 * Example usage of this function when the string is not in the moodle.php file:<br/>
7419 * <code>
7420 * echo '<h1>';
7421 * print_string('typecourse', 'calendar');
7422 * echo '</h1>';
7423 * </code>
7425 * @category string
7426 * @param string $identifier The key identifier for the localized string
7427 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7428 * @param string|object|array $a An object, string or number that can be used within translation strings
7430 function print_string($identifier, $component = '', $a = null) {
7431 echo get_string($identifier, $component, $a);
7435 * Returns a list of charset codes
7437 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7438 * (checking that such charset is supported by the texlib library!)
7440 * @return array And associative array with contents in the form of charset => charset
7442 function get_list_of_charsets() {
7444 $charsets = array(
7445 'EUC-JP' => 'EUC-JP',
7446 'ISO-2022-JP'=> 'ISO-2022-JP',
7447 'ISO-8859-1' => 'ISO-8859-1',
7448 'SHIFT-JIS' => 'SHIFT-JIS',
7449 'GB2312' => 'GB2312',
7450 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7451 'UTF-8' => 'UTF-8');
7453 asort($charsets);
7455 return $charsets;
7459 * Returns a list of valid and compatible themes
7461 * @return array
7463 function get_list_of_themes() {
7464 global $CFG;
7466 $themes = array();
7468 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7469 $themelist = explode(',', $CFG->themelist);
7470 } else {
7471 $themelist = array_keys(core_component::get_plugin_list("theme"));
7474 foreach ($themelist as $key => $themename) {
7475 $theme = theme_config::load($themename);
7476 $themes[$themename] = $theme;
7479 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7481 return $themes;
7485 * Factory function for emoticon_manager
7487 * @return emoticon_manager singleton
7489 function get_emoticon_manager() {
7490 static $singleton = null;
7492 if (is_null($singleton)) {
7493 $singleton = new emoticon_manager();
7496 return $singleton;
7500 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7502 * Whenever this manager mentiones 'emoticon object', the following data
7503 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7504 * altidentifier and altcomponent
7506 * @see admin_setting_emoticons
7508 * @copyright 2010 David Mudrak
7509 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7511 class emoticon_manager {
7514 * Returns the currently enabled emoticons
7516 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7517 * @return array of emoticon objects
7519 public function get_emoticons($selectable = false) {
7520 global $CFG;
7521 $notselectable = ['martin', 'egg'];
7523 if (empty($CFG->emoticons)) {
7524 return array();
7527 $emoticons = $this->decode_stored_config($CFG->emoticons);
7529 if (!is_array($emoticons)) {
7530 // Something is wrong with the format of stored setting.
7531 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7532 return array();
7534 if ($selectable) {
7535 foreach ($emoticons as $index => $emote) {
7536 if (in_array($emote->altidentifier, $notselectable)) {
7537 // Skip this one.
7538 unset($emoticons[$index]);
7543 return $emoticons;
7547 * Converts emoticon object into renderable pix_emoticon object
7549 * @param stdClass $emoticon emoticon object
7550 * @param array $attributes explicit HTML attributes to set
7551 * @return pix_emoticon
7553 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7554 $stringmanager = get_string_manager();
7555 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7556 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7557 } else {
7558 $alt = s($emoticon->text);
7560 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7564 * Encodes the array of emoticon objects into a string storable in config table
7566 * @see self::decode_stored_config()
7567 * @param array $emoticons array of emtocion objects
7568 * @return string
7570 public function encode_stored_config(array $emoticons) {
7571 return json_encode($emoticons);
7575 * Decodes the string into an array of emoticon objects
7577 * @see self::encode_stored_config()
7578 * @param string $encoded
7579 * @return string|null
7581 public function decode_stored_config($encoded) {
7582 $decoded = json_decode($encoded);
7583 if (!is_array($decoded)) {
7584 return null;
7586 return $decoded;
7590 * Returns default set of emoticons supported by Moodle
7592 * @return array of sdtClasses
7594 public function default_emoticons() {
7595 return array(
7596 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7597 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7598 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7599 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7600 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7601 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7602 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7603 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7604 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7605 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7606 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7607 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7608 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7609 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7610 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7611 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7612 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7613 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7614 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7615 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7616 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7617 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7618 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7619 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7620 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7621 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7622 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7623 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7624 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7625 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7630 * Helper method preparing the stdClass with the emoticon properties
7632 * @param string|array $text or array of strings
7633 * @param string $imagename to be used by {@link pix_emoticon}
7634 * @param string $altidentifier alternative string identifier, null for no alt
7635 * @param string $altcomponent where the alternative string is defined
7636 * @param string $imagecomponent to be used by {@link pix_emoticon}
7637 * @return stdClass
7639 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7640 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7641 return (object)array(
7642 'text' => $text,
7643 'imagename' => $imagename,
7644 'imagecomponent' => $imagecomponent,
7645 'altidentifier' => $altidentifier,
7646 'altcomponent' => $altcomponent,
7651 // ENCRYPTION.
7654 * rc4encrypt
7656 * @param string $data Data to encrypt.
7657 * @return string The now encrypted data.
7659 function rc4encrypt($data) {
7660 return endecrypt(get_site_identifier(), $data, '');
7664 * rc4decrypt
7666 * @param string $data Data to decrypt.
7667 * @return string The now decrypted data.
7669 function rc4decrypt($data) {
7670 return endecrypt(get_site_identifier(), $data, 'de');
7674 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7676 * @todo Finish documenting this function
7678 * @param string $pwd The password to use when encrypting or decrypting
7679 * @param string $data The data to be decrypted/encrypted
7680 * @param string $case Either 'de' for decrypt or '' for encrypt
7681 * @return string
7683 function endecrypt ($pwd, $data, $case) {
7685 if ($case == 'de') {
7686 $data = urldecode($data);
7689 $key[] = '';
7690 $box[] = '';
7691 $pwdlength = strlen($pwd);
7693 for ($i = 0; $i <= 255; $i++) {
7694 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7695 $box[$i] = $i;
7698 $x = 0;
7700 for ($i = 0; $i <= 255; $i++) {
7701 $x = ($x + $box[$i] + $key[$i]) % 256;
7702 $tempswap = $box[$i];
7703 $box[$i] = $box[$x];
7704 $box[$x] = $tempswap;
7707 $cipher = '';
7709 $a = 0;
7710 $j = 0;
7712 for ($i = 0; $i < strlen($data); $i++) {
7713 $a = ($a + 1) % 256;
7714 $j = ($j + $box[$a]) % 256;
7715 $temp = $box[$a];
7716 $box[$a] = $box[$j];
7717 $box[$j] = $temp;
7718 $k = $box[(($box[$a] + $box[$j]) % 256)];
7719 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7720 $cipher .= chr($cipherby);
7723 if ($case == 'de') {
7724 $cipher = urldecode(urlencode($cipher));
7725 } else {
7726 $cipher = urlencode($cipher);
7729 return $cipher;
7732 // ENVIRONMENT CHECKING.
7735 * This method validates a plug name. It is much faster than calling clean_param.
7737 * @param string $name a string that might be a plugin name.
7738 * @return bool if this string is a valid plugin name.
7740 function is_valid_plugin_name($name) {
7741 // This does not work for 'mod', bad luck, use any other type.
7742 return core_component::is_valid_plugin_name('tool', $name);
7746 * Get a list of all the plugins of a given type that define a certain API function
7747 * in a certain file. The plugin component names and function names are returned.
7749 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7750 * @param string $function the part of the name of the function after the
7751 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7752 * names like report_courselist_hook.
7753 * @param string $file the name of file within the plugin that defines the
7754 * function. Defaults to lib.php.
7755 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7756 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7758 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7759 global $CFG;
7761 // We don't include here as all plugin types files would be included.
7762 $plugins = get_plugins_with_function($function, $file, false);
7764 if (empty($plugins[$plugintype])) {
7765 return array();
7768 $allplugins = core_component::get_plugin_list($plugintype);
7770 // Reformat the array and include the files.
7771 $pluginfunctions = array();
7772 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7774 // Check that it has not been removed and the file is still available.
7775 if (!empty($allplugins[$pluginname])) {
7777 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7778 if (file_exists($filepath)) {
7779 include_once($filepath);
7780 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7785 return $pluginfunctions;
7789 * Get a list of all the plugins that define a certain API function in a certain file.
7791 * @param string $function the part of the name of the function after the
7792 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7793 * names like report_courselist_hook.
7794 * @param string $file the name of file within the plugin that defines the
7795 * function. Defaults to lib.php.
7796 * @param bool $include Whether to include the files that contain the functions or not.
7797 * @return array with [plugintype][plugin] = functionname
7799 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7800 global $CFG;
7802 if (during_initial_install() || isset($CFG->upgraderunning)) {
7803 // API functions _must not_ be called during an installation or upgrade.
7804 return [];
7807 $cache = \cache::make('core', 'plugin_functions');
7809 // Including both although I doubt that we will find two functions definitions with the same name.
7810 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7811 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7812 $pluginfunctions = $cache->get($key);
7814 // Use the plugin manager to check that plugins are currently installed.
7815 $pluginmanager = \core_plugin_manager::instance();
7817 if ($pluginfunctions !== false) {
7819 // Checking that the files are still available.
7820 foreach ($pluginfunctions as $plugintype => $plugins) {
7822 $allplugins = \core_component::get_plugin_list($plugintype);
7823 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7824 foreach ($plugins as $plugin => $function) {
7825 if (!isset($installedplugins[$plugin])) {
7826 // Plugin code is still present on disk but it is not installed.
7827 unset($pluginfunctions[$plugintype][$plugin]);
7828 continue;
7831 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7832 if (empty($allplugins[$plugin])) {
7833 unset($pluginfunctions[$plugintype][$plugin]);
7834 continue;
7837 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7838 if ($include && $fileexists) {
7839 // Include the files if it was requested.
7840 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7841 } else if (!$fileexists) {
7842 // If the file is not available any more it should not be returned.
7843 unset($pluginfunctions[$plugintype][$plugin]);
7847 return $pluginfunctions;
7850 $pluginfunctions = array();
7852 // To fill the cached. Also, everything should continue working with cache disabled.
7853 $plugintypes = \core_component::get_plugin_types();
7854 foreach ($plugintypes as $plugintype => $unused) {
7856 // We need to include files here.
7857 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7858 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7859 foreach ($pluginswithfile as $plugin => $notused) {
7861 if (!isset($installedplugins[$plugin])) {
7862 continue;
7865 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7867 $pluginfunction = false;
7868 if (function_exists($fullfunction)) {
7869 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7870 $pluginfunction = $fullfunction;
7872 } else if ($plugintype === 'mod') {
7873 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7874 $shortfunction = $plugin . '_' . $function;
7875 if (function_exists($shortfunction)) {
7876 $pluginfunction = $shortfunction;
7880 if ($pluginfunction) {
7881 if (empty($pluginfunctions[$plugintype])) {
7882 $pluginfunctions[$plugintype] = array();
7884 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7889 $cache->set($key, $pluginfunctions);
7891 return $pluginfunctions;
7896 * Lists plugin-like directories within specified directory
7898 * This function was originally used for standard Moodle plugins, please use
7899 * new core_component::get_plugin_list() now.
7901 * This function is used for general directory listing and backwards compatility.
7903 * @param string $directory relative directory from root
7904 * @param string $exclude dir name to exclude from the list (defaults to none)
7905 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7906 * @return array Sorted array of directory names found under the requested parameters
7908 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7909 global $CFG;
7911 $plugins = array();
7913 if (empty($basedir)) {
7914 $basedir = $CFG->dirroot .'/'. $directory;
7916 } else {
7917 $basedir = $basedir .'/'. $directory;
7920 if ($CFG->debugdeveloper and empty($exclude)) {
7921 // Make sure devs do not use this to list normal plugins,
7922 // this is intended for general directories that are not plugins!
7924 $subtypes = core_component::get_plugin_types();
7925 if (in_array($basedir, $subtypes)) {
7926 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7928 unset($subtypes);
7931 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7932 if (!$dirhandle = opendir($basedir)) {
7933 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7934 return array();
7936 while (false !== ($dir = readdir($dirhandle))) {
7937 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7938 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7939 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7940 continue;
7942 if (filetype($basedir .'/'. $dir) != 'dir') {
7943 continue;
7945 $plugins[] = $dir;
7947 closedir($dirhandle);
7949 if ($plugins) {
7950 asort($plugins);
7952 return $plugins;
7956 * Invoke plugin's callback functions
7958 * @param string $type plugin type e.g. 'mod'
7959 * @param string $name plugin name
7960 * @param string $feature feature name
7961 * @param string $action feature's action
7962 * @param array $params parameters of callback function, should be an array
7963 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7964 * @return mixed
7966 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7968 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7969 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7973 * Invoke component's callback functions
7975 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7976 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7977 * @param array $params parameters of callback function
7978 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7979 * @return mixed
7981 function component_callback($component, $function, array $params = array(), $default = null) {
7983 $functionname = component_callback_exists($component, $function);
7985 if ($functionname) {
7986 // Function exists, so just return function result.
7987 $ret = call_user_func_array($functionname, $params);
7988 if (is_null($ret)) {
7989 return $default;
7990 } else {
7991 return $ret;
7994 return $default;
7998 * Determine if a component callback exists and return the function name to call. Note that this
7999 * function will include the required library files so that the functioname returned can be
8000 * called directly.
8002 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8003 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8004 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
8005 * @throws coding_exception if invalid component specfied
8007 function component_callback_exists($component, $function) {
8008 global $CFG; // This is needed for the inclusions.
8010 $cleancomponent = clean_param($component, PARAM_COMPONENT);
8011 if (empty($cleancomponent)) {
8012 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8014 $component = $cleancomponent;
8016 list($type, $name) = core_component::normalize_component($component);
8017 $component = $type . '_' . $name;
8019 $oldfunction = $name.'_'.$function;
8020 $function = $component.'_'.$function;
8022 $dir = core_component::get_component_directory($component);
8023 if (empty($dir)) {
8024 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8027 // Load library and look for function.
8028 if (file_exists($dir.'/lib.php')) {
8029 require_once($dir.'/lib.php');
8032 if (!function_exists($function) and function_exists($oldfunction)) {
8033 if ($type !== 'mod' and $type !== 'core') {
8034 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
8036 $function = $oldfunction;
8039 if (function_exists($function)) {
8040 return $function;
8042 return false;
8046 * Call the specified callback method on the provided class.
8048 * If the callback returns null, then the default value is returned instead.
8049 * If the class does not exist, then the default value is returned.
8051 * @param string $classname The name of the class to call upon.
8052 * @param string $methodname The name of the staticically defined method on the class.
8053 * @param array $params The arguments to pass into the method.
8054 * @param mixed $default The default value.
8055 * @return mixed The return value.
8057 function component_class_callback($classname, $methodname, array $params, $default = null) {
8058 if (!class_exists($classname)) {
8059 return $default;
8062 if (!method_exists($classname, $methodname)) {
8063 return $default;
8066 $fullfunction = $classname . '::' . $methodname;
8067 $result = call_user_func_array($fullfunction, $params);
8069 if (null === $result) {
8070 return $default;
8071 } else {
8072 return $result;
8077 * Checks whether a plugin supports a specified feature.
8079 * @param string $type Plugin type e.g. 'mod'
8080 * @param string $name Plugin name e.g. 'forum'
8081 * @param string $feature Feature code (FEATURE_xx constant)
8082 * @param mixed $default default value if feature support unknown
8083 * @return mixed Feature result (false if not supported, null if feature is unknown,
8084 * otherwise usually true but may have other feature-specific value such as array)
8085 * @throws coding_exception
8087 function plugin_supports($type, $name, $feature, $default = null) {
8088 global $CFG;
8090 if ($type === 'mod' and $name === 'NEWMODULE') {
8091 // Somebody forgot to rename the module template.
8092 return false;
8095 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8096 if (empty($component)) {
8097 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8100 $function = null;
8102 if ($type === 'mod') {
8103 // We need this special case because we support subplugins in modules,
8104 // otherwise it would end up in infinite loop.
8105 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8106 include_once("$CFG->dirroot/mod/$name/lib.php");
8107 $function = $component.'_supports';
8108 if (!function_exists($function)) {
8109 // Legacy non-frankenstyle function name.
8110 $function = $name.'_supports';
8114 } else {
8115 if (!$path = core_component::get_plugin_directory($type, $name)) {
8116 // Non existent plugin type.
8117 return false;
8119 if (file_exists("$path/lib.php")) {
8120 include_once("$path/lib.php");
8121 $function = $component.'_supports';
8125 if ($function and function_exists($function)) {
8126 $supports = $function($feature);
8127 if (is_null($supports)) {
8128 // Plugin does not know - use default.
8129 return $default;
8130 } else {
8131 return $supports;
8135 // Plugin does not care, so use default.
8136 return $default;
8140 * Returns true if the current version of PHP is greater that the specified one.
8142 * @todo Check PHP version being required here is it too low?
8144 * @param string $version The version of php being tested.
8145 * @return bool
8147 function check_php_version($version='5.2.4') {
8148 return (version_compare(phpversion(), $version) >= 0);
8152 * Determine if moodle installation requires update.
8154 * Checks version numbers of main code and all plugins to see
8155 * if there are any mismatches.
8157 * @return bool
8159 function moodle_needs_upgrading() {
8160 global $CFG;
8162 if (empty($CFG->version)) {
8163 return true;
8166 // There is no need to purge plugininfo caches here because
8167 // these caches are not used during upgrade and they are purged after
8168 // every upgrade.
8170 if (empty($CFG->allversionshash)) {
8171 return true;
8174 $hash = core_component::get_all_versions_hash();
8176 return ($hash !== $CFG->allversionshash);
8180 * Returns the major version of this site
8182 * Moodle version numbers consist of three numbers separated by a dot, for
8183 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8184 * called major version. This function extracts the major version from either
8185 * $CFG->release (default) or eventually from the $release variable defined in
8186 * the main version.php.
8188 * @param bool $fromdisk should the version if source code files be used
8189 * @return string|false the major version like '2.3', false if could not be determined
8191 function moodle_major_version($fromdisk = false) {
8192 global $CFG;
8194 if ($fromdisk) {
8195 $release = null;
8196 require($CFG->dirroot.'/version.php');
8197 if (empty($release)) {
8198 return false;
8201 } else {
8202 if (empty($CFG->release)) {
8203 return false;
8205 $release = $CFG->release;
8208 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8209 return $matches[0];
8210 } else {
8211 return false;
8215 // MISCELLANEOUS.
8218 * Gets the system locale
8220 * @return string Retuns the current locale.
8222 function moodle_getlocale() {
8223 global $CFG;
8225 // Fetch the correct locale based on ostype.
8226 if ($CFG->ostype == 'WINDOWS') {
8227 $stringtofetch = 'localewin';
8228 } else {
8229 $stringtofetch = 'locale';
8232 if (!empty($CFG->locale)) { // Override locale for all language packs.
8233 return $CFG->locale;
8236 return get_string($stringtofetch, 'langconfig');
8240 * Sets the system locale
8242 * @category string
8243 * @param string $locale Can be used to force a locale
8245 function moodle_setlocale($locale='') {
8246 global $CFG;
8248 static $currentlocale = ''; // Last locale caching.
8250 $oldlocale = $currentlocale;
8252 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8253 if (!empty($locale)) {
8254 $currentlocale = $locale;
8255 } else {
8256 $currentlocale = moodle_getlocale();
8259 // Do nothing if locale already set up.
8260 if ($oldlocale == $currentlocale) {
8261 return;
8264 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8265 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8266 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8268 // Get current values.
8269 $monetary= setlocale (LC_MONETARY, 0);
8270 $numeric = setlocale (LC_NUMERIC, 0);
8271 $ctype = setlocale (LC_CTYPE, 0);
8272 if ($CFG->ostype != 'WINDOWS') {
8273 $messages= setlocale (LC_MESSAGES, 0);
8275 // Set locale to all.
8276 $result = setlocale (LC_ALL, $currentlocale);
8277 // If setting of locale fails try the other utf8 or utf-8 variant,
8278 // some operating systems support both (Debian), others just one (OSX).
8279 if ($result === false) {
8280 if (stripos($currentlocale, '.UTF-8') !== false) {
8281 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8282 setlocale (LC_ALL, $newlocale);
8283 } else if (stripos($currentlocale, '.UTF8') !== false) {
8284 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8285 setlocale (LC_ALL, $newlocale);
8288 // Set old values.
8289 setlocale (LC_MONETARY, $monetary);
8290 setlocale (LC_NUMERIC, $numeric);
8291 if ($CFG->ostype != 'WINDOWS') {
8292 setlocale (LC_MESSAGES, $messages);
8294 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8295 // To workaround a well-known PHP problem with Turkish letter Ii.
8296 setlocale (LC_CTYPE, $ctype);
8301 * Count words in a string.
8303 * Words are defined as things between whitespace.
8305 * @category string
8306 * @param string $string The text to be searched for words.
8307 * @return int The count of words in the specified string
8309 function count_words($string) {
8310 $string = strip_tags($string);
8311 // Decode HTML entities.
8312 $string = html_entity_decode($string);
8313 // Replace underscores (which are classed as word characters) with spaces.
8314 $string = preg_replace('/_/u', ' ', $string);
8315 // Remove any characters that shouldn't be treated as word boundaries.
8316 $string = preg_replace('/[\'"’-]/u', '', $string);
8317 // Remove dots and commas from within numbers only.
8318 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
8320 return count(preg_split('/\w\b/u', $string)) - 1;
8324 * Count letters in a string.
8326 * Letters are defined as chars not in tags and different from whitespace.
8328 * @category string
8329 * @param string $string The text to be searched for letters.
8330 * @return int The count of letters in the specified text.
8332 function count_letters($string) {
8333 $string = strip_tags($string); // Tags are out now.
8334 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8336 return core_text::strlen($string);
8340 * Generate and return a random string of the specified length.
8342 * @param int $length The length of the string to be created.
8343 * @return string
8345 function random_string($length=15) {
8346 $randombytes = random_bytes_emulate($length);
8347 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8348 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8349 $pool .= '0123456789';
8350 $poollen = strlen($pool);
8351 $string = '';
8352 for ($i = 0; $i < $length; $i++) {
8353 $rand = ord($randombytes[$i]);
8354 $string .= substr($pool, ($rand%($poollen)), 1);
8356 return $string;
8360 * Generate a complex random string (useful for md5 salts)
8362 * This function is based on the above {@link random_string()} however it uses a
8363 * larger pool of characters and generates a string between 24 and 32 characters
8365 * @param int $length Optional if set generates a string to exactly this length
8366 * @return string
8368 function complex_random_string($length=null) {
8369 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8370 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8371 $poollen = strlen($pool);
8372 if ($length===null) {
8373 $length = floor(rand(24, 32));
8375 $randombytes = random_bytes_emulate($length);
8376 $string = '';
8377 for ($i = 0; $i < $length; $i++) {
8378 $rand = ord($randombytes[$i]);
8379 $string .= $pool[($rand%$poollen)];
8381 return $string;
8385 * Try to generates cryptographically secure pseudo-random bytes.
8387 * Note this is achieved by fallbacking between:
8388 * - PHP 7 random_bytes().
8389 * - OpenSSL openssl_random_pseudo_bytes().
8390 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8392 * @param int $length requested length in bytes
8393 * @return string binary data
8395 function random_bytes_emulate($length) {
8396 global $CFG;
8397 if ($length <= 0) {
8398 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8399 return '';
8401 if (function_exists('random_bytes')) {
8402 // Use PHP 7 goodness.
8403 $hash = @random_bytes($length);
8404 if ($hash !== false) {
8405 return $hash;
8408 if (function_exists('openssl_random_pseudo_bytes')) {
8409 // If you have the openssl extension enabled.
8410 $hash = openssl_random_pseudo_bytes($length);
8411 if ($hash !== false) {
8412 return $hash;
8416 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8417 $staticdata = serialize($CFG) . serialize($_SERVER);
8418 $hash = '';
8419 do {
8420 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8421 } while (strlen($hash) < $length);
8423 return substr($hash, 0, $length);
8427 * Given some text (which may contain HTML) and an ideal length,
8428 * this function truncates the text neatly on a word boundary if possible
8430 * @category string
8431 * @param string $text text to be shortened
8432 * @param int $ideal ideal string length
8433 * @param boolean $exact if false, $text will not be cut mid-word
8434 * @param string $ending The string to append if the passed string is truncated
8435 * @return string $truncate shortened string
8437 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8438 // If the plain text is shorter than the maximum length, return the whole text.
8439 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8440 return $text;
8443 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8444 // and only tag in its 'line'.
8445 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8447 $totallength = core_text::strlen($ending);
8448 $truncate = '';
8450 // This array stores information about open and close tags and their position
8451 // in the truncated string. Each item in the array is an object with fields
8452 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8453 // (byte position in truncated text).
8454 $tagdetails = array();
8456 foreach ($lines as $linematchings) {
8457 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8458 if (!empty($linematchings[1])) {
8459 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8460 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8461 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8462 // Record closing tag.
8463 $tagdetails[] = (object) array(
8464 'open' => false,
8465 'tag' => core_text::strtolower($tagmatchings[1]),
8466 'pos' => core_text::strlen($truncate),
8469 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8470 // Record opening tag.
8471 $tagdetails[] = (object) array(
8472 'open' => true,
8473 'tag' => core_text::strtolower($tagmatchings[1]),
8474 'pos' => core_text::strlen($truncate),
8476 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8477 $tagdetails[] = (object) array(
8478 'open' => true,
8479 'tag' => core_text::strtolower('if'),
8480 'pos' => core_text::strlen($truncate),
8482 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8483 $tagdetails[] = (object) array(
8484 'open' => false,
8485 'tag' => core_text::strtolower('if'),
8486 'pos' => core_text::strlen($truncate),
8490 // Add html-tag to $truncate'd text.
8491 $truncate .= $linematchings[1];
8494 // Calculate the length of the plain text part of the line; handle entities as one character.
8495 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8496 if ($totallength + $contentlength > $ideal) {
8497 // The number of characters which are left.
8498 $left = $ideal - $totallength;
8499 $entitieslength = 0;
8500 // Search for html entities.
8501 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)) {
8502 // Calculate the real length of all entities in the legal range.
8503 foreach ($entities[0] as $entity) {
8504 if ($entity[1]+1-$entitieslength <= $left) {
8505 $left--;
8506 $entitieslength += core_text::strlen($entity[0]);
8507 } else {
8508 // No more characters left.
8509 break;
8513 $breakpos = $left + $entitieslength;
8515 // If the words shouldn't be cut in the middle...
8516 if (!$exact) {
8517 // Search the last occurence of a space.
8518 for (; $breakpos > 0; $breakpos--) {
8519 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8520 if ($char === '.' or $char === ' ') {
8521 $breakpos += 1;
8522 break;
8523 } else if (strlen($char) > 2) {
8524 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8525 $breakpos += 1;
8526 break;
8531 if ($breakpos == 0) {
8532 // This deals with the test_shorten_text_no_spaces case.
8533 $breakpos = $left + $entitieslength;
8534 } else if ($breakpos > $left + $entitieslength) {
8535 // This deals with the previous for loop breaking on the first char.
8536 $breakpos = $left + $entitieslength;
8539 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8540 // Maximum length is reached, so get off the loop.
8541 break;
8542 } else {
8543 $truncate .= $linematchings[2];
8544 $totallength += $contentlength;
8547 // If the maximum length is reached, get off the loop.
8548 if ($totallength >= $ideal) {
8549 break;
8553 // Add the defined ending to the text.
8554 $truncate .= $ending;
8556 // Now calculate the list of open html tags based on the truncate position.
8557 $opentags = array();
8558 foreach ($tagdetails as $taginfo) {
8559 if ($taginfo->open) {
8560 // Add tag to the beginning of $opentags list.
8561 array_unshift($opentags, $taginfo->tag);
8562 } else {
8563 // Can have multiple exact same open tags, close the last one.
8564 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8565 if ($pos !== false) {
8566 unset($opentags[$pos]);
8571 // Close all unclosed html-tags.
8572 foreach ($opentags as $tag) {
8573 if ($tag === 'if') {
8574 $truncate .= '<!--<![endif]-->';
8575 } else {
8576 $truncate .= '</' . $tag . '>';
8580 return $truncate;
8584 * Shortens a given filename by removing characters positioned after the ideal string length.
8585 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8586 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8588 * @param string $filename file name
8589 * @param int $length ideal string length
8590 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8591 * @return string $shortened shortened file name
8593 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8594 $shortened = $filename;
8595 // Extract a part of the filename if it's char size exceeds the ideal string length.
8596 if (core_text::strlen($filename) > $length) {
8597 // Exclude extension if present in filename.
8598 $mimetypes = get_mimetypes_array();
8599 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8600 if ($extension && !empty($mimetypes[$extension])) {
8601 $basename = pathinfo($filename, PATHINFO_FILENAME);
8602 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8603 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8604 $shortened .= '.' . $extension;
8605 } else {
8606 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8607 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8610 return $shortened;
8614 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8616 * @param array $path The paths to reduce the length.
8617 * @param int $length Ideal string length
8618 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8619 * @return array $result Shortened paths in array.
8621 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8622 $result = null;
8624 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8625 $carry[] = shorten_filename($singlepath, $length, $includehash);
8626 return $carry;
8627 }, []);
8629 return $result;
8633 * Given dates in seconds, how many weeks is the date from startdate
8634 * The first week is 1, the second 2 etc ...
8636 * @param int $startdate Timestamp for the start date
8637 * @param int $thedate Timestamp for the end date
8638 * @return string
8640 function getweek ($startdate, $thedate) {
8641 if ($thedate < $startdate) {
8642 return 0;
8645 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8649 * Returns a randomly generated password of length $maxlen. inspired by
8651 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8652 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8654 * @param int $maxlen The maximum size of the password being generated.
8655 * @return string
8657 function generate_password($maxlen=10) {
8658 global $CFG;
8660 if (empty($CFG->passwordpolicy)) {
8661 $fillers = PASSWORD_DIGITS;
8662 $wordlist = file($CFG->wordlist);
8663 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8664 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8665 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8666 $password = $word1 . $filler1 . $word2;
8667 } else {
8668 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8669 $digits = $CFG->minpassworddigits;
8670 $lower = $CFG->minpasswordlower;
8671 $upper = $CFG->minpasswordupper;
8672 $nonalphanum = $CFG->minpasswordnonalphanum;
8673 $total = $lower + $upper + $digits + $nonalphanum;
8674 // Var minlength should be the greater one of the two ( $minlen and $total ).
8675 $minlen = $minlen < $total ? $total : $minlen;
8676 // Var maxlen can never be smaller than minlen.
8677 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8678 $additional = $maxlen - $total;
8680 // Make sure we have enough characters to fulfill
8681 // complexity requirements.
8682 $passworddigits = PASSWORD_DIGITS;
8683 while ($digits > strlen($passworddigits)) {
8684 $passworddigits .= PASSWORD_DIGITS;
8686 $passwordlower = PASSWORD_LOWER;
8687 while ($lower > strlen($passwordlower)) {
8688 $passwordlower .= PASSWORD_LOWER;
8690 $passwordupper = PASSWORD_UPPER;
8691 while ($upper > strlen($passwordupper)) {
8692 $passwordupper .= PASSWORD_UPPER;
8694 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8695 while ($nonalphanum > strlen($passwordnonalphanum)) {
8696 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8699 // Now mix and shuffle it all.
8700 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8701 substr(str_shuffle ($passwordupper), 0, $upper) .
8702 substr(str_shuffle ($passworddigits), 0, $digits) .
8703 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8704 substr(str_shuffle ($passwordlower .
8705 $passwordupper .
8706 $passworddigits .
8707 $passwordnonalphanum), 0 , $additional));
8710 return substr ($password, 0, $maxlen);
8714 * Given a float, prints it nicely.
8715 * Localized floats must not be used in calculations!
8717 * The stripzeros feature is intended for making numbers look nicer in small
8718 * areas where it is not necessary to indicate the degree of accuracy by showing
8719 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8720 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8722 * @param float $float The float to print
8723 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8724 * @param bool $localized use localized decimal separator
8725 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8726 * the decimal point are always striped if $decimalpoints is -1.
8727 * @return string locale float
8729 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8730 if (is_null($float)) {
8731 return '';
8733 if ($localized) {
8734 $separator = get_string('decsep', 'langconfig');
8735 } else {
8736 $separator = '.';
8738 if ($decimalpoints == -1) {
8739 // The following counts the number of decimals.
8740 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8741 $floatval = floatval($float);
8742 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
8745 $result = number_format($float, $decimalpoints, $separator, '');
8746 if ($stripzeros) {
8747 // Remove zeros and final dot if not needed.
8748 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8750 return $result;
8754 * Converts locale specific floating point/comma number back to standard PHP float value
8755 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8757 * @param string $localefloat locale aware float representation
8758 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8759 * @return mixed float|bool - false or the parsed float.
8761 function unformat_float($localefloat, $strict = false) {
8762 $localefloat = trim($localefloat);
8764 if ($localefloat == '') {
8765 return null;
8768 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8769 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8771 if ($strict && !is_numeric($localefloat)) {
8772 return false;
8775 return (float)$localefloat;
8779 * Given a simple array, this shuffles it up just like shuffle()
8780 * Unlike PHP's shuffle() this function works on any machine.
8782 * @param array $array The array to be rearranged
8783 * @return array
8785 function swapshuffle($array) {
8787 $last = count($array) - 1;
8788 for ($i = 0; $i <= $last; $i++) {
8789 $from = rand(0, $last);
8790 $curr = $array[$i];
8791 $array[$i] = $array[$from];
8792 $array[$from] = $curr;
8794 return $array;
8798 * Like {@link swapshuffle()}, but works on associative arrays
8800 * @param array $array The associative array to be rearranged
8801 * @return array
8803 function swapshuffle_assoc($array) {
8805 $newarray = array();
8806 $newkeys = swapshuffle(array_keys($array));
8808 foreach ($newkeys as $newkey) {
8809 $newarray[$newkey] = $array[$newkey];
8811 return $newarray;
8815 * Given an arbitrary array, and a number of draws,
8816 * this function returns an array with that amount
8817 * of items. The indexes are retained.
8819 * @todo Finish documenting this function
8821 * @param array $array
8822 * @param int $draws
8823 * @return array
8825 function draw_rand_array($array, $draws) {
8827 $return = array();
8829 $last = count($array);
8831 if ($draws > $last) {
8832 $draws = $last;
8835 while ($draws > 0) {
8836 $last--;
8838 $keys = array_keys($array);
8839 $rand = rand(0, $last);
8841 $return[$keys[$rand]] = $array[$keys[$rand]];
8842 unset($array[$keys[$rand]]);
8844 $draws--;
8847 return $return;
8851 * Calculate the difference between two microtimes
8853 * @param string $a The first Microtime
8854 * @param string $b The second Microtime
8855 * @return string
8857 function microtime_diff($a, $b) {
8858 list($adec, $asec) = explode(' ', $a);
8859 list($bdec, $bsec) = explode(' ', $b);
8860 return $bsec - $asec + $bdec - $adec;
8864 * Given a list (eg a,b,c,d,e) this function returns
8865 * an array of 1->a, 2->b, 3->c etc
8867 * @param string $list The string to explode into array bits
8868 * @param string $separator The separator used within the list string
8869 * @return array The now assembled array
8871 function make_menu_from_list($list, $separator=',') {
8873 $array = array_reverse(explode($separator, $list), true);
8874 foreach ($array as $key => $item) {
8875 $outarray[$key+1] = trim($item);
8877 return $outarray;
8881 * Creates an array that represents all the current grades that
8882 * can be chosen using the given grading type.
8884 * Negative numbers
8885 * are scales, zero is no grade, and positive numbers are maximum
8886 * grades.
8888 * @todo Finish documenting this function or better deprecated this completely!
8890 * @param int $gradingtype
8891 * @return array
8893 function make_grades_menu($gradingtype) {
8894 global $DB;
8896 $grades = array();
8897 if ($gradingtype < 0) {
8898 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8899 return make_menu_from_list($scale->scale);
8901 } else if ($gradingtype > 0) {
8902 for ($i=$gradingtype; $i>=0; $i--) {
8903 $grades[$i] = $i .' / '. $gradingtype;
8905 return $grades;
8907 return $grades;
8911 * make_unique_id_code
8913 * @todo Finish documenting this function
8915 * @uses $_SERVER
8916 * @param string $extra Extra string to append to the end of the code
8917 * @return string
8919 function make_unique_id_code($extra = '') {
8921 $hostname = 'unknownhost';
8922 if (!empty($_SERVER['HTTP_HOST'])) {
8923 $hostname = $_SERVER['HTTP_HOST'];
8924 } else if (!empty($_ENV['HTTP_HOST'])) {
8925 $hostname = $_ENV['HTTP_HOST'];
8926 } else if (!empty($_SERVER['SERVER_NAME'])) {
8927 $hostname = $_SERVER['SERVER_NAME'];
8928 } else if (!empty($_ENV['SERVER_NAME'])) {
8929 $hostname = $_ENV['SERVER_NAME'];
8932 $date = gmdate("ymdHis");
8934 $random = random_string(6);
8936 if ($extra) {
8937 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8938 } else {
8939 return $hostname .'+'. $date .'+'. $random;
8945 * Function to check the passed address is within the passed subnet
8947 * The parameter is a comma separated string of subnet definitions.
8948 * Subnet strings can be in one of three formats:
8949 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8950 * 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)
8951 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8952 * Code for type 1 modified from user posted comments by mediator at
8953 * {@link http://au.php.net/manual/en/function.ip2long.php}
8955 * @param string $addr The address you are checking
8956 * @param string $subnetstr The string of subnet addresses
8957 * @return bool
8959 function address_in_subnet($addr, $subnetstr) {
8961 if ($addr == '0.0.0.0') {
8962 return false;
8964 $subnets = explode(',', $subnetstr);
8965 $found = false;
8966 $addr = trim($addr);
8967 $addr = cleanremoteaddr($addr, false); // Normalise.
8968 if ($addr === null) {
8969 return false;
8971 $addrparts = explode(':', $addr);
8973 $ipv6 = strpos($addr, ':');
8975 foreach ($subnets as $subnet) {
8976 $subnet = trim($subnet);
8977 if ($subnet === '') {
8978 continue;
8981 if (strpos($subnet, '/') !== false) {
8982 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8983 list($ip, $mask) = explode('/', $subnet);
8984 $mask = trim($mask);
8985 if (!is_number($mask)) {
8986 continue; // Incorect mask number, eh?
8988 $ip = cleanremoteaddr($ip, false); // Normalise.
8989 if ($ip === null) {
8990 continue;
8992 if (strpos($ip, ':') !== false) {
8993 // IPv6.
8994 if (!$ipv6) {
8995 continue;
8997 if ($mask > 128 or $mask < 0) {
8998 continue; // Nonsense.
9000 if ($mask == 0) {
9001 return true; // Any address.
9003 if ($mask == 128) {
9004 if ($ip === $addr) {
9005 return true;
9007 continue;
9009 $ipparts = explode(':', $ip);
9010 $modulo = $mask % 16;
9011 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9012 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9013 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9014 if ($modulo == 0) {
9015 return true;
9017 $pos = ($mask-$modulo)/16;
9018 $ipnet = hexdec($ipparts[$pos]);
9019 $addrnet = hexdec($addrparts[$pos]);
9020 $mask = 0xffff << (16 - $modulo);
9021 if (($addrnet & $mask) == ($ipnet & $mask)) {
9022 return true;
9026 } else {
9027 // IPv4.
9028 if ($ipv6) {
9029 continue;
9031 if ($mask > 32 or $mask < 0) {
9032 continue; // Nonsense.
9034 if ($mask == 0) {
9035 return true;
9037 if ($mask == 32) {
9038 if ($ip === $addr) {
9039 return true;
9041 continue;
9043 $mask = 0xffffffff << (32 - $mask);
9044 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9045 return true;
9049 } else if (strpos($subnet, '-') !== false) {
9050 // 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.
9051 $parts = explode('-', $subnet);
9052 if (count($parts) != 2) {
9053 continue;
9056 if (strpos($subnet, ':') !== false) {
9057 // IPv6.
9058 if (!$ipv6) {
9059 continue;
9061 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9062 if ($ipstart === null) {
9063 continue;
9065 $ipparts = explode(':', $ipstart);
9066 $start = hexdec(array_pop($ipparts));
9067 $ipparts[] = trim($parts[1]);
9068 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9069 if ($ipend === null) {
9070 continue;
9072 $ipparts[7] = '';
9073 $ipnet = implode(':', $ipparts);
9074 if (strpos($addr, $ipnet) !== 0) {
9075 continue;
9077 $ipparts = explode(':', $ipend);
9078 $end = hexdec($ipparts[7]);
9080 $addrend = hexdec($addrparts[7]);
9082 if (($addrend >= $start) and ($addrend <= $end)) {
9083 return true;
9086 } else {
9087 // IPv4.
9088 if ($ipv6) {
9089 continue;
9091 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9092 if ($ipstart === null) {
9093 continue;
9095 $ipparts = explode('.', $ipstart);
9096 $ipparts[3] = trim($parts[1]);
9097 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9098 if ($ipend === null) {
9099 continue;
9102 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9103 return true;
9107 } else {
9108 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9109 if (strpos($subnet, ':') !== false) {
9110 // IPv6.
9111 if (!$ipv6) {
9112 continue;
9114 $parts = explode(':', $subnet);
9115 $count = count($parts);
9116 if ($parts[$count-1] === '') {
9117 unset($parts[$count-1]); // Trim trailing :'s.
9118 $count--;
9119 $subnet = implode('.', $parts);
9121 $isip = cleanremoteaddr($subnet, false); // Normalise.
9122 if ($isip !== null) {
9123 if ($isip === $addr) {
9124 return true;
9126 continue;
9127 } else if ($count > 8) {
9128 continue;
9130 $zeros = array_fill(0, 8-$count, '0');
9131 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9132 if (address_in_subnet($addr, $subnet)) {
9133 return true;
9136 } else {
9137 // IPv4.
9138 if ($ipv6) {
9139 continue;
9141 $parts = explode('.', $subnet);
9142 $count = count($parts);
9143 if ($parts[$count-1] === '') {
9144 unset($parts[$count-1]); // Trim trailing .
9145 $count--;
9146 $subnet = implode('.', $parts);
9148 if ($count == 4) {
9149 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9150 if ($subnet === $addr) {
9151 return true;
9153 continue;
9154 } else if ($count > 4) {
9155 continue;
9157 $zeros = array_fill(0, 4-$count, '0');
9158 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9159 if (address_in_subnet($addr, $subnet)) {
9160 return true;
9166 return false;
9170 * For outputting debugging info
9172 * @param string $string The string to write
9173 * @param string $eol The end of line char(s) to use
9174 * @param string $sleep Period to make the application sleep
9175 * This ensures any messages have time to display before redirect
9177 function mtrace($string, $eol="\n", $sleep=0) {
9178 global $CFG;
9180 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
9181 $fn = $CFG->mtrace_wrapper;
9182 $fn($string, $eol);
9183 return;
9184 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
9185 // We must explicitly call the add_line function here.
9186 // Uses of fwrite to STDOUT are not picked up by ob_start.
9187 if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
9188 fwrite(STDOUT, $output);
9190 } else {
9191 echo $string . $eol;
9194 // Flush again.
9195 flush();
9197 // Delay to keep message on user's screen in case of subsequent redirect.
9198 if ($sleep) {
9199 sleep($sleep);
9204 * Replace 1 or more slashes or backslashes to 1 slash
9206 * @param string $path The path to strip
9207 * @return string the path with double slashes removed
9209 function cleardoubleslashes ($path) {
9210 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9214 * Is the current ip in a given list?
9216 * @param string $list
9217 * @return bool
9219 function remoteip_in_list($list) {
9220 $clientip = getremoteaddr(null);
9222 if (!$clientip) {
9223 // Ensure access on cli.
9224 return true;
9226 return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
9230 * Returns most reliable client address
9232 * @param string $default If an address can't be determined, then return this
9233 * @return string The remote IP address
9235 function getremoteaddr($default='0.0.0.0') {
9236 global $CFG;
9238 if (empty($CFG->getremoteaddrconf)) {
9239 // This will happen, for example, before just after the upgrade, as the
9240 // user is redirected to the admin screen.
9241 $variablestoskip = 0;
9242 } else {
9243 $variablestoskip = $CFG->getremoteaddrconf;
9245 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9246 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9247 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9248 return $address ? $address : $default;
9251 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9252 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9253 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9255 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9256 global $CFG;
9257 return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
9260 // Multiple proxies can append values to this header including an
9261 // untrusted original request header so we must only trust the last ip.
9262 $address = end($forwardedaddresses);
9264 if (substr_count($address, ":") > 1) {
9265 // Remove port and brackets from IPv6.
9266 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9267 $address = $matches[1];
9269 } else {
9270 // Remove port from IPv4.
9271 if (substr_count($address, ":") == 1) {
9272 $parts = explode(":", $address);
9273 $address = $parts[0];
9277 $address = cleanremoteaddr($address);
9278 return $address ? $address : $default;
9281 if (!empty($_SERVER['REMOTE_ADDR'])) {
9282 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9283 return $address ? $address : $default;
9284 } else {
9285 return $default;
9290 * Cleans an ip address. Internal addresses are now allowed.
9291 * (Originally local addresses were not allowed.)
9293 * @param string $addr IPv4 or IPv6 address
9294 * @param bool $compress use IPv6 address compression
9295 * @return string normalised ip address string, null if error
9297 function cleanremoteaddr($addr, $compress=false) {
9298 $addr = trim($addr);
9300 if (strpos($addr, ':') !== false) {
9301 // Can be only IPv6.
9302 $parts = explode(':', $addr);
9303 $count = count($parts);
9305 if (strpos($parts[$count-1], '.') !== false) {
9306 // Legacy ipv4 notation.
9307 $last = array_pop($parts);
9308 $ipv4 = cleanremoteaddr($last, true);
9309 if ($ipv4 === null) {
9310 return null;
9312 $bits = explode('.', $ipv4);
9313 $parts[] = dechex($bits[0]).dechex($bits[1]);
9314 $parts[] = dechex($bits[2]).dechex($bits[3]);
9315 $count = count($parts);
9316 $addr = implode(':', $parts);
9319 if ($count < 3 or $count > 8) {
9320 return null; // Severly malformed.
9323 if ($count != 8) {
9324 if (strpos($addr, '::') === false) {
9325 return null; // Malformed.
9327 // Uncompress.
9328 $insertat = array_search('', $parts, true);
9329 $missing = array_fill(0, 1 + 8 - $count, '0');
9330 array_splice($parts, $insertat, 1, $missing);
9331 foreach ($parts as $key => $part) {
9332 if ($part === '') {
9333 $parts[$key] = '0';
9338 $adr = implode(':', $parts);
9339 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9340 return null; // Incorrect format - sorry.
9343 // Normalise 0s and case.
9344 $parts = array_map('hexdec', $parts);
9345 $parts = array_map('dechex', $parts);
9347 $result = implode(':', $parts);
9349 if (!$compress) {
9350 return $result;
9353 if ($result === '0:0:0:0:0:0:0:0') {
9354 return '::'; // All addresses.
9357 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9358 if ($compressed !== $result) {
9359 return $compressed;
9362 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9363 if ($compressed !== $result) {
9364 return $compressed;
9367 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9368 if ($compressed !== $result) {
9369 return $compressed;
9372 return $result;
9375 // First get all things that look like IPv4 addresses.
9376 $parts = array();
9377 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9378 return null;
9380 unset($parts[0]);
9382 foreach ($parts as $key => $match) {
9383 if ($match > 255) {
9384 return null;
9386 $parts[$key] = (int)$match; // Normalise 0s.
9389 return implode('.', $parts);
9394 * Is IP address a public address?
9396 * @param string $ip The ip to check
9397 * @return bool true if the ip is public
9399 function ip_is_public($ip) {
9400 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9404 * This function will make a complete copy of anything it's given,
9405 * regardless of whether it's an object or not.
9407 * @param mixed $thing Something you want cloned
9408 * @return mixed What ever it is you passed it
9410 function fullclone($thing) {
9411 return unserialize(serialize($thing));
9415 * Used to make sure that $min <= $value <= $max
9417 * Make sure that value is between min, and max
9419 * @param int $min The minimum value
9420 * @param int $value The value to check
9421 * @param int $max The maximum value
9422 * @return int
9424 function bounded_number($min, $value, $max) {
9425 if ($value < $min) {
9426 return $min;
9428 if ($value > $max) {
9429 return $max;
9431 return $value;
9435 * Check if there is a nested array within the passed array
9437 * @param array $array
9438 * @return bool true if there is a nested array false otherwise
9440 function array_is_nested($array) {
9441 foreach ($array as $value) {
9442 if (is_array($value)) {
9443 return true;
9446 return false;
9450 * get_performance_info() pairs up with init_performance_info()
9451 * loaded in setup.php. Returns an array with 'html' and 'txt'
9452 * values ready for use, and each of the individual stats provided
9453 * separately as well.
9455 * @return array
9457 function get_performance_info() {
9458 global $CFG, $PERF, $DB, $PAGE;
9460 $info = array();
9461 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9463 $info['html'] = '';
9464 if (!empty($CFG->themedesignermode)) {
9465 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9466 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9468 $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
9470 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9472 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9473 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9475 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9476 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9478 if (function_exists('memory_get_usage')) {
9479 $info['memory_total'] = memory_get_usage();
9480 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9481 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9482 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9483 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9486 if (function_exists('memory_get_peak_usage')) {
9487 $info['memory_peak'] = memory_get_peak_usage();
9488 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9489 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9492 $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9493 $inc = get_included_files();
9494 $info['includecount'] = count($inc);
9495 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9496 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9498 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9499 // We can not track more performance before installation or before PAGE init, sorry.
9500 return $info;
9503 $filtermanager = filter_manager::instance();
9504 if (method_exists($filtermanager, 'get_performance_summary')) {
9505 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9506 $info = array_merge($filterinfo, $info);
9507 foreach ($filterinfo as $key => $value) {
9508 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9509 $info['txt'] .= "$key: $value ";
9513 $stringmanager = get_string_manager();
9514 if (method_exists($stringmanager, 'get_performance_summary')) {
9515 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9516 $info = array_merge($filterinfo, $info);
9517 foreach ($filterinfo as $key => $value) {
9518 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9519 $info['txt'] .= "$key: $value ";
9523 if (!empty($PERF->logwrites)) {
9524 $info['logwrites'] = $PERF->logwrites;
9525 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9526 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9529 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9530 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9531 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9533 if ($DB->want_read_slave()) {
9534 $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9535 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9536 $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9539 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9540 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9541 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9543 if (function_exists('posix_times')) {
9544 $ptimes = posix_times();
9545 if (is_array($ptimes)) {
9546 foreach ($ptimes as $key => $val) {
9547 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9549 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9550 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9551 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9555 // Grab the load average for the last minute.
9556 // /proc will only work under some linux configurations
9557 // while uptime is there under MacOSX/Darwin and other unices.
9558 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9559 list($serverload) = explode(' ', $loadavg[0]);
9560 unset($loadavg);
9561 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9562 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9563 $serverload = $matches[1];
9564 } else {
9565 trigger_error('Could not parse uptime output!');
9568 if (!empty($serverload)) {
9569 $info['serverload'] = $serverload;
9570 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9571 $info['txt'] .= "serverload: {$info['serverload']} ";
9574 // Display size of session if session started.
9575 if ($si = \core\session\manager::get_performance_info()) {
9576 $info['sessionsize'] = $si['size'];
9577 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9578 $info['txt'] .= $si['txt'];
9581 $info['html'] .= '</ul>';
9582 $html = '';
9583 if ($stats = cache_helper::get_stats()) {
9585 $table = new html_table();
9586 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9587 $table->head = ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S'];
9588 $table->data = [];
9589 $table->align = ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right'];
9591 $text = 'Caches used (hits/misses/sets): ';
9592 $hits = 0;
9593 $misses = 0;
9594 $sets = 0;
9595 $maxstores = 0;
9597 // We want to align static caches into their own column.
9598 $hasstatic = false;
9599 foreach ($stats as $definition => $details) {
9600 $numstores = count($details['stores']);
9601 $first = key($details['stores']);
9602 if ($first !== cache_store::STATIC_ACCEL) {
9603 $numstores++; // Add a blank space for the missing static store.
9605 $maxstores = max($maxstores, $numstores);
9608 $storec = 0;
9610 while ($storec++ < ($maxstores - 2)) {
9611 if ($storec == ($maxstores - 2)) {
9612 $table->head[] = get_string('mappingfinal', 'cache');
9613 } else {
9614 $table->head[] = "Store $storec";
9616 $table->align[] = 'left';
9617 $table->align[] = 'right';
9618 $table->align[] = 'right';
9619 $table->align[] = 'right';
9620 $table->head[] = 'H';
9621 $table->head[] = 'M';
9622 $table->head[] = 'S';
9625 ksort($stats);
9627 foreach ($stats as $definition => $details) {
9628 switch ($details['mode']) {
9629 case cache_store::MODE_APPLICATION:
9630 $modeclass = 'application';
9631 $mode = ' <span title="application cache">App</span>';
9632 break;
9633 case cache_store::MODE_SESSION:
9634 $modeclass = 'session';
9635 $mode = ' <span title="session cache">Ses</span>';
9636 break;
9637 case cache_store::MODE_REQUEST:
9638 $modeclass = 'request';
9639 $mode = ' <span title="request cache">Req</span>';
9640 break;
9642 $row = [$mode, $definition];
9644 $text .= "$definition {";
9646 $storec = 0;
9647 foreach ($details['stores'] as $store => $data) {
9649 if ($storec == 0 && $store !== cache_store::STATIC_ACCEL) {
9650 $row[] = '';
9651 $row[] = '';
9652 $row[] = '';
9653 $storec++;
9656 $hits += $data['hits'];
9657 $misses += $data['misses'];
9658 $sets += $data['sets'];
9659 if ($data['hits'] == 0 and $data['misses'] > 0) {
9660 $cachestoreclass = 'nohits bg-danger';
9661 } else if ($data['hits'] < $data['misses']) {
9662 $cachestoreclass = 'lowhits bg-warning text-dark';
9663 } else {
9664 $cachestoreclass = 'hihits';
9666 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9667 $cell = new html_table_cell($store);
9668 $cell->attributes = ['class' => $cachestoreclass];
9669 $row[] = $cell;
9670 $cell = new html_table_cell($data['hits']);
9671 $cell->attributes = ['class' => $cachestoreclass];
9672 $row[] = $cell;
9673 $cell = new html_table_cell($data['misses']);
9674 $cell->attributes = ['class' => $cachestoreclass];
9675 $row[] = $cell;
9677 if ($store !== cache_store::STATIC_ACCEL) {
9678 // The static cache is never set.
9679 $cell = new html_table_cell($data['sets']);
9680 $cell->attributes = ['class' => $cachestoreclass];
9681 $row[] = $cell;
9683 $storec++;
9685 while ($storec++ < $maxstores) {
9686 $row[] = '';
9687 $row[] = '';
9688 $row[] = '';
9689 $row[] = '';
9691 $text .= '} ';
9693 $table->data[] = $row;
9696 $html .= html_writer::table($table);
9698 // Now lets also show sub totals for each cache store.
9699 $storetotals = [];
9700 $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0];
9701 foreach ($stats as $definition => $details) {
9702 foreach ($details['stores'] as $store => $data) {
9703 if (!array_key_exists($store, $storetotals)) {
9704 $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0];
9706 $storetotals[$store]['class'] = $data['class'];
9707 $storetotals[$store]['hits'] += $data['hits'];
9708 $storetotals[$store]['misses'] += $data['misses'];
9709 $storetotals[$store]['sets'] += $data['sets'];
9710 $storetotal['hits'] += $data['hits'];
9711 $storetotal['misses'] += $data['misses'];
9712 $storetotal['sets'] += $data['sets'];
9716 $table = new html_table();
9717 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9718 $table->head = [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S'];
9719 $table->data = [];
9720 $table->align = ['left', 'left', 'right', 'right', 'right'];
9722 ksort($storetotals);
9724 foreach ($storetotals as $store => $data) {
9725 $row = [];
9726 if ($data['hits'] == 0 and $data['misses'] > 0) {
9727 $cachestoreclass = 'nohits bg-danger';
9728 } else if ($data['hits'] < $data['misses']) {
9729 $cachestoreclass = 'lowhits bg-warning text-dark';
9730 } else {
9731 $cachestoreclass = 'hihits';
9733 $cell = new html_table_cell($store);
9734 $cell->attributes = ['class' => $cachestoreclass];
9735 $row[] = $cell;
9736 $cell = new html_table_cell($data['class']);
9737 $cell->attributes = ['class' => $cachestoreclass];
9738 $row[] = $cell;
9739 $cell = new html_table_cell($data['hits']);
9740 $cell->attributes = ['class' => $cachestoreclass];
9741 $row[] = $cell;
9742 $cell = new html_table_cell($data['misses']);
9743 $cell->attributes = ['class' => $cachestoreclass];
9744 $row[] = $cell;
9745 $cell = new html_table_cell($data['sets']);
9746 $cell->attributes = ['class' => $cachestoreclass];
9747 $row[] = $cell;
9748 $table->data[] = $row;
9750 $row = [
9751 get_string('total'),
9753 $storetotal['hits'],
9754 $storetotal['misses'],
9755 $storetotal['sets'],
9757 $table->data[] = $row;
9759 $html .= html_writer::table($table);
9761 $info['cachesused'] = "$hits / $misses / $sets";
9762 $info['html'] .= $html;
9763 $info['txt'] .= $text.'. ';
9764 } else {
9765 $info['cachesused'] = '0 / 0 / 0';
9766 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9767 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9770 $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto mt-3">'.$info['html'].'</div>';
9771 return $info;
9775 * Delete directory or only its content
9777 * @param string $dir directory path
9778 * @param bool $contentonly
9779 * @return bool success, true also if dir does not exist
9781 function remove_dir($dir, $contentonly=false) {
9782 if (!file_exists($dir)) {
9783 // Nothing to do.
9784 return true;
9786 if (!$handle = opendir($dir)) {
9787 return false;
9789 $result = true;
9790 while (false!==($item = readdir($handle))) {
9791 if ($item != '.' && $item != '..') {
9792 if (is_dir($dir.'/'.$item)) {
9793 $result = remove_dir($dir.'/'.$item) && $result;
9794 } else {
9795 $result = unlink($dir.'/'.$item) && $result;
9799 closedir($handle);
9800 if ($contentonly) {
9801 clearstatcache(); // Make sure file stat cache is properly invalidated.
9802 return $result;
9804 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9805 clearstatcache(); // Make sure file stat cache is properly invalidated.
9806 return $result;
9810 * Detect if an object or a class contains a given property
9811 * will take an actual object or the name of a class
9813 * @param mix $obj Name of class or real object to test
9814 * @param string $property name of property to find
9815 * @return bool true if property exists
9817 function object_property_exists( $obj, $property ) {
9818 if (is_string( $obj )) {
9819 $properties = get_class_vars( $obj );
9820 } else {
9821 $properties = get_object_vars( $obj );
9823 return array_key_exists( $property, $properties );
9827 * Converts an object into an associative array
9829 * This function converts an object into an associative array by iterating
9830 * over its public properties. Because this function uses the foreach
9831 * construct, Iterators are respected. It works recursively on arrays of objects.
9832 * Arrays and simple values are returned as is.
9834 * If class has magic properties, it can implement IteratorAggregate
9835 * and return all available properties in getIterator()
9837 * @param mixed $var
9838 * @return array
9840 function convert_to_array($var) {
9841 $result = array();
9843 // Loop over elements/properties.
9844 foreach ($var as $key => $value) {
9845 // Recursively convert objects.
9846 if (is_object($value) || is_array($value)) {
9847 $result[$key] = convert_to_array($value);
9848 } else {
9849 // Simple values are untouched.
9850 $result[$key] = $value;
9853 return $result;
9857 * Detect a custom script replacement in the data directory that will
9858 * replace an existing moodle script
9860 * @return string|bool full path name if a custom script exists, false if no custom script exists
9862 function custom_script_path() {
9863 global $CFG, $SCRIPT;
9865 if ($SCRIPT === null) {
9866 // Probably some weird external script.
9867 return false;
9870 $scriptpath = $CFG->customscripts . $SCRIPT;
9872 // Check the custom script exists.
9873 if (file_exists($scriptpath) and is_file($scriptpath)) {
9874 return $scriptpath;
9875 } else {
9876 return false;
9881 * Returns whether or not the user object is a remote MNET user. This function
9882 * is in moodlelib because it does not rely on loading any of the MNET code.
9884 * @param object $user A valid user object
9885 * @return bool True if the user is from a remote Moodle.
9887 function is_mnet_remote_user($user) {
9888 global $CFG;
9890 if (!isset($CFG->mnet_localhost_id)) {
9891 include_once($CFG->dirroot . '/mnet/lib.php');
9892 $env = new mnet_environment();
9893 $env->init();
9894 unset($env);
9897 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9901 * This function will search for browser prefereed languages, setting Moodle
9902 * to use the best one available if $SESSION->lang is undefined
9904 function setup_lang_from_browser() {
9905 global $CFG, $SESSION, $USER;
9907 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9908 // Lang is defined in session or user profile, nothing to do.
9909 return;
9912 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9913 return;
9916 // Extract and clean langs from headers.
9917 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9918 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9919 $rawlangs = explode(',', $rawlangs); // Convert to array.
9920 $langs = array();
9922 $order = 1.0;
9923 foreach ($rawlangs as $lang) {
9924 if (strpos($lang, ';') === false) {
9925 $langs[(string)$order] = $lang;
9926 $order = $order-0.01;
9927 } else {
9928 $parts = explode(';', $lang);
9929 $pos = strpos($parts[1], '=');
9930 $langs[substr($parts[1], $pos+1)] = $parts[0];
9933 krsort($langs, SORT_NUMERIC);
9935 // Look for such langs under standard locations.
9936 foreach ($langs as $lang) {
9937 // Clean it properly for include.
9938 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9939 if (get_string_manager()->translation_exists($lang, false)) {
9940 // Lang exists, set it in session.
9941 $SESSION->lang = $lang;
9942 // We have finished. Go out.
9943 break;
9946 return;
9950 * Check if $url matches anything in proxybypass list
9952 * Any errors just result in the proxy being used (least bad)
9954 * @param string $url url to check
9955 * @return boolean true if we should bypass the proxy
9957 function is_proxybypass( $url ) {
9958 global $CFG;
9960 // Sanity check.
9961 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9962 return false;
9965 // Get the host part out of the url.
9966 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9967 return false;
9970 // Get the possible bypass hosts into an array.
9971 $matches = explode( ',', $CFG->proxybypass );
9973 // Check for a match.
9974 // (IPs need to match the left hand side and hosts the right of the url,
9975 // but we can recklessly check both as there can't be a false +ve).
9976 foreach ($matches as $match) {
9977 $match = trim($match);
9979 // Try for IP match (Left side).
9980 $lhs = substr($host, 0, strlen($match));
9981 if (strcasecmp($match, $lhs)==0) {
9982 return true;
9985 // Try for host match (Right side).
9986 $rhs = substr($host, -strlen($match));
9987 if (strcasecmp($match, $rhs)==0) {
9988 return true;
9992 // Nothing matched.
9993 return false;
9997 * Check if the passed navigation is of the new style
9999 * @param mixed $navigation
10000 * @return bool true for yes false for no
10002 function is_newnav($navigation) {
10003 if (is_array($navigation) && !empty($navigation['newnav'])) {
10004 return true;
10005 } else {
10006 return false;
10011 * Checks whether the given variable name is defined as a variable within the given object.
10013 * This will NOT work with stdClass objects, which have no class variables.
10015 * @param string $var The variable name
10016 * @param object $object The object to check
10017 * @return boolean
10019 function in_object_vars($var, $object) {
10020 $classvars = get_class_vars(get_class($object));
10021 $classvars = array_keys($classvars);
10022 return in_array($var, $classvars);
10026 * Returns an array without repeated objects.
10027 * This function is similar to array_unique, but for arrays that have objects as values
10029 * @param array $array
10030 * @param bool $keepkeyassoc
10031 * @return array
10033 function object_array_unique($array, $keepkeyassoc = true) {
10034 $duplicatekeys = array();
10035 $tmp = array();
10037 foreach ($array as $key => $val) {
10038 // Convert objects to arrays, in_array() does not support objects.
10039 if (is_object($val)) {
10040 $val = (array)$val;
10043 if (!in_array($val, $tmp)) {
10044 $tmp[] = $val;
10045 } else {
10046 $duplicatekeys[] = $key;
10050 foreach ($duplicatekeys as $key) {
10051 unset($array[$key]);
10054 return $keepkeyassoc ? $array : array_values($array);
10058 * Is a userid the primary administrator?
10060 * @param int $userid int id of user to check
10061 * @return boolean
10063 function is_primary_admin($userid) {
10064 $primaryadmin = get_admin();
10066 if ($userid == $primaryadmin->id) {
10067 return true;
10068 } else {
10069 return false;
10074 * Returns the site identifier
10076 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10078 function get_site_identifier() {
10079 global $CFG;
10080 // Check to see if it is missing. If so, initialise it.
10081 if (empty($CFG->siteidentifier)) {
10082 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10084 // Return it.
10085 return $CFG->siteidentifier;
10089 * Check whether the given password has no more than the specified
10090 * number of consecutive identical characters.
10092 * @param string $password password to be checked against the password policy
10093 * @param integer $maxchars maximum number of consecutive identical characters
10094 * @return bool
10096 function check_consecutive_identical_characters($password, $maxchars) {
10098 if ($maxchars < 1) {
10099 return true; // Zero 0 is to disable this check.
10101 if (strlen($password) <= $maxchars) {
10102 return true; // Too short to fail this test.
10105 $previouschar = '';
10106 $consecutivecount = 1;
10107 foreach (str_split($password) as $char) {
10108 if ($char != $previouschar) {
10109 $consecutivecount = 1;
10110 } else {
10111 $consecutivecount++;
10112 if ($consecutivecount > $maxchars) {
10113 return false; // Check failed already.
10117 $previouschar = $char;
10120 return true;
10124 * Helper function to do partial function binding.
10125 * so we can use it for preg_replace_callback, for example
10126 * this works with php functions, user functions, static methods and class methods
10127 * it returns you a callback that you can pass on like so:
10129 * $callback = partial('somefunction', $arg1, $arg2);
10130 * or
10131 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10132 * or even
10133 * $obj = new someclass();
10134 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10136 * and then the arguments that are passed through at calltime are appended to the argument list.
10138 * @param mixed $function a php callback
10139 * @param mixed $arg1,... $argv arguments to partially bind with
10140 * @return array Array callback
10142 function partial() {
10143 if (!class_exists('partial')) {
10145 * Used to manage function binding.
10146 * @copyright 2009 Penny Leach
10147 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10149 class partial{
10150 /** @var array */
10151 public $values = array();
10152 /** @var string The function to call as a callback. */
10153 public $func;
10155 * Constructor
10156 * @param string $func
10157 * @param array $args
10159 public function __construct($func, $args) {
10160 $this->values = $args;
10161 $this->func = $func;
10164 * Calls the callback function.
10165 * @return mixed
10167 public function method() {
10168 $args = func_get_args();
10169 return call_user_func_array($this->func, array_merge($this->values, $args));
10173 $args = func_get_args();
10174 $func = array_shift($args);
10175 $p = new partial($func, $args);
10176 return array($p, 'method');
10180 * helper function to load up and initialise the mnet environment
10181 * this must be called before you use mnet functions.
10183 * @return mnet_environment the equivalent of old $MNET global
10185 function get_mnet_environment() {
10186 global $CFG;
10187 require_once($CFG->dirroot . '/mnet/lib.php');
10188 static $instance = null;
10189 if (empty($instance)) {
10190 $instance = new mnet_environment();
10191 $instance->init();
10193 return $instance;
10197 * during xmlrpc server code execution, any code wishing to access
10198 * information about the remote peer must use this to get it.
10200 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10202 function get_mnet_remote_client() {
10203 if (!defined('MNET_SERVER')) {
10204 debugging(get_string('notinxmlrpcserver', 'mnet'));
10205 return false;
10207 global $MNET_REMOTE_CLIENT;
10208 if (isset($MNET_REMOTE_CLIENT)) {
10209 return $MNET_REMOTE_CLIENT;
10211 return false;
10215 * during the xmlrpc server code execution, this will be called
10216 * to setup the object returned by {@link get_mnet_remote_client}
10218 * @param mnet_remote_client $client the client to set up
10219 * @throws moodle_exception
10221 function set_mnet_remote_client($client) {
10222 if (!defined('MNET_SERVER')) {
10223 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10225 global $MNET_REMOTE_CLIENT;
10226 $MNET_REMOTE_CLIENT = $client;
10230 * return the jump url for a given remote user
10231 * this is used for rewriting forum post links in emails, etc
10233 * @param stdclass $user the user to get the idp url for
10235 function mnet_get_idp_jump_url($user) {
10236 global $CFG;
10238 static $mnetjumps = array();
10239 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10240 $idp = mnet_get_peer_host($user->mnethostid);
10241 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10242 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10244 return $mnetjumps[$user->mnethostid];
10248 * Gets the homepage to use for the current user
10250 * @return int One of HOMEPAGE_*
10252 function get_home_page() {
10253 global $CFG;
10255 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10256 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10257 return HOMEPAGE_MY;
10258 } else {
10259 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
10262 return HOMEPAGE_SITE;
10266 * Gets the name of a course to be displayed when showing a list of courses.
10267 * By default this is just $course->fullname but user can configure it. The
10268 * result of this function should be passed through print_string.
10269 * @param stdClass|core_course_list_element $course Moodle course object
10270 * @return string Display name of course (either fullname or short + fullname)
10272 function get_course_display_name_for_list($course) {
10273 global $CFG;
10274 if (!empty($CFG->courselistshortnames)) {
10275 if (!($course instanceof stdClass)) {
10276 $course = (object)convert_to_array($course);
10278 return get_string('courseextendednamedisplay', '', $course);
10279 } else {
10280 return $course->fullname;
10285 * Safe analogue of unserialize() that can only parse arrays
10287 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10288 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10289 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10291 * @param string $expression
10292 * @return array|bool either parsed array or false if parsing was impossible.
10294 function unserialize_array($expression) {
10295 $subs = [];
10296 // Find nested arrays, parse them and store in $subs , substitute with special string.
10297 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10298 $key = '--SUB' . count($subs) . '--';
10299 $subs[$key] = unserialize_array($matches[2]);
10300 if ($subs[$key] === false) {
10301 return false;
10303 $expression = str_replace($matches[2], $key . ';', $expression);
10306 // Check the expression is an array.
10307 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10308 return false;
10310 // Get the size and elements of an array (key;value;key;value;....).
10311 $parts = explode(';', $matches1[2]);
10312 $size = intval($matches1[1]);
10313 if (count($parts) < $size * 2 + 1) {
10314 return false;
10316 // Analyze each part and make sure it is an integer or string or a substitute.
10317 $value = [];
10318 for ($i = 0; $i < $size * 2; $i++) {
10319 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10320 $parts[$i] = (int)$matches2[1];
10321 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10322 $parts[$i] = $matches3[2];
10323 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10324 $parts[$i] = $subs[$parts[$i]];
10325 } else {
10326 return false;
10329 // Combine keys and values.
10330 for ($i = 0; $i < $size * 2; $i += 2) {
10331 $value[$parts[$i]] = $parts[$i+1];
10333 return $value;
10337 * The lang_string class
10339 * This special class is used to create an object representation of a string request.
10340 * It is special because processing doesn't occur until the object is first used.
10341 * The class was created especially to aid performance in areas where strings were
10342 * required to be generated but were not necessarily used.
10343 * As an example the admin tree when generated uses over 1500 strings, of which
10344 * normally only 1/3 are ever actually printed at any time.
10345 * The performance advantage is achieved by not actually processing strings that
10346 * arn't being used, as such reducing the processing required for the page.
10348 * How to use the lang_string class?
10349 * There are two methods of using the lang_string class, first through the
10350 * forth argument of the get_string function, and secondly directly.
10351 * The following are examples of both.
10352 * 1. Through get_string calls e.g.
10353 * $string = get_string($identifier, $component, $a, true);
10354 * $string = get_string('yes', 'moodle', null, true);
10355 * 2. Direct instantiation
10356 * $string = new lang_string($identifier, $component, $a, $lang);
10357 * $string = new lang_string('yes');
10359 * How do I use a lang_string object?
10360 * The lang_string object makes use of a magic __toString method so that you
10361 * are able to use the object exactly as you would use a string in most cases.
10362 * This means you are able to collect it into a variable and then directly
10363 * echo it, or concatenate it into another string, or similar.
10364 * The other thing you can do is manually get the string by calling the
10365 * lang_strings out method e.g.
10366 * $string = new lang_string('yes');
10367 * $string->out();
10368 * Also worth noting is that the out method can take one argument, $lang which
10369 * allows the developer to change the language on the fly.
10371 * When should I use a lang_string object?
10372 * The lang_string object is designed to be used in any situation where a
10373 * string may not be needed, but needs to be generated.
10374 * The admin tree is a good example of where lang_string objects should be
10375 * used.
10376 * A more practical example would be any class that requries strings that may
10377 * not be printed (after all classes get renderer by renderers and who knows
10378 * what they will do ;))
10380 * When should I not use a lang_string object?
10381 * Don't use lang_strings when you are going to use a string immediately.
10382 * There is no need as it will be processed immediately and there will be no
10383 * advantage, and in fact perhaps a negative hit as a class has to be
10384 * instantiated for a lang_string object, however get_string won't require
10385 * that.
10387 * Limitations:
10388 * 1. You cannot use a lang_string object as an array offset. Doing so will
10389 * result in PHP throwing an error. (You can use it as an object property!)
10391 * @package core
10392 * @category string
10393 * @copyright 2011 Sam Hemelryk
10394 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10396 class lang_string {
10398 /** @var string The strings identifier */
10399 protected $identifier;
10400 /** @var string The strings component. Default '' */
10401 protected $component = '';
10402 /** @var array|stdClass Any arguments required for the string. Default null */
10403 protected $a = null;
10404 /** @var string The language to use when processing the string. Default null */
10405 protected $lang = null;
10407 /** @var string The processed string (once processed) */
10408 protected $string = null;
10411 * A special boolean. If set to true then the object has been woken up and
10412 * cannot be regenerated. If this is set then $this->string MUST be used.
10413 * @var bool
10415 protected $forcedstring = false;
10418 * Constructs a lang_string object
10420 * This function should do as little processing as possible to ensure the best
10421 * performance for strings that won't be used.
10423 * @param string $identifier The strings identifier
10424 * @param string $component The strings component
10425 * @param stdClass|array $a Any arguments the string requires
10426 * @param string $lang The language to use when processing the string.
10427 * @throws coding_exception
10429 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10430 if (empty($component)) {
10431 $component = 'moodle';
10434 $this->identifier = $identifier;
10435 $this->component = $component;
10436 $this->lang = $lang;
10438 // We MUST duplicate $a to ensure that it if it changes by reference those
10439 // changes are not carried across.
10440 // To do this we always ensure $a or its properties/values are strings
10441 // and that any properties/values that arn't convertable are forgotten.
10442 if (!empty($a)) {
10443 if (is_scalar($a)) {
10444 $this->a = $a;
10445 } else if ($a instanceof lang_string) {
10446 $this->a = $a->out();
10447 } else if (is_object($a) or is_array($a)) {
10448 $a = (array)$a;
10449 $this->a = array();
10450 foreach ($a as $key => $value) {
10451 // Make sure conversion errors don't get displayed (results in '').
10452 if (is_array($value)) {
10453 $this->a[$key] = '';
10454 } else if (is_object($value)) {
10455 if (method_exists($value, '__toString')) {
10456 $this->a[$key] = $value->__toString();
10457 } else {
10458 $this->a[$key] = '';
10460 } else {
10461 $this->a[$key] = (string)$value;
10467 if (debugging(false, DEBUG_DEVELOPER)) {
10468 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10469 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10471 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10472 throw new coding_exception('Invalid string compontent. Please check your string definition');
10474 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10475 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10481 * Processes the string.
10483 * This function actually processes the string, stores it in the string property
10484 * and then returns it.
10485 * You will notice that this function is VERY similar to the get_string method.
10486 * That is because it is pretty much doing the same thing.
10487 * However as this function is an upgrade it isn't as tolerant to backwards
10488 * compatibility.
10490 * @return string
10491 * @throws coding_exception
10493 protected function get_string() {
10494 global $CFG;
10496 // Check if we need to process the string.
10497 if ($this->string === null) {
10498 // Check the quality of the identifier.
10499 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10500 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);
10503 // Process the string.
10504 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10505 // Debugging feature lets you display string identifier and component.
10506 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10507 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10510 // Return the string.
10511 return $this->string;
10515 * Returns the string
10517 * @param string $lang The langauge to use when processing the string
10518 * @return string
10520 public function out($lang = null) {
10521 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10522 if ($this->forcedstring) {
10523 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10524 return $this->get_string();
10526 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10527 return $translatedstring->out();
10529 return $this->get_string();
10533 * Magic __toString method for printing a string
10535 * @return string
10537 public function __toString() {
10538 return $this->get_string();
10542 * Magic __set_state method used for var_export
10544 * @return string
10546 public function __set_state() {
10547 return $this->get_string();
10551 * Prepares the lang_string for sleep and stores only the forcedstring and
10552 * string properties... the string cannot be regenerated so we need to ensure
10553 * it is generated for this.
10555 * @return string
10557 public function __sleep() {
10558 $this->get_string();
10559 $this->forcedstring = true;
10560 return array('forcedstring', 'string', 'lang');
10564 * Returns the identifier.
10566 * @return string
10568 public function get_identifier() {
10569 return $this->identifier;
10573 * Returns the component.
10575 * @return string
10577 public function get_component() {
10578 return $this->component;
10583 * Get human readable name describing the given callable.
10585 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10586 * It does not check if the callable actually exists.
10588 * @param callable|string|array $callable
10589 * @return string|bool Human readable name of callable, or false if not a valid callable.
10591 function get_callable_name($callable) {
10593 if (!is_callable($callable, true, $name)) {
10594 return false;
10596 } else {
10597 return $name;
10602 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10603 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10604 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10605 * such as site registration when $CFG->wwwroot is not publicly accessible.
10606 * Good thing is there is no false negative.
10607 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10609 * @return bool
10611 function site_is_public() {
10612 global $CFG;
10614 // Return early if site admin has forced this setting.
10615 if (isset($CFG->site_is_public)) {
10616 return (bool)$CFG->site_is_public;
10619 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10621 if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10622 $ispublic = false;
10623 } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10624 $ispublic = false;
10625 } else if (($address = \core\ip_utils::get_ip_address($host)) && !ip_is_public($address)) {
10626 $ispublic = false;
10627 } else {
10628 $ispublic = true;
10631 return $ispublic;