NOBUG: Fixed SVG browser compatibility
[moodle.git] / lib / moodlelib.php
blob894b00527a6913063e810c726505a7f1ef1bd2f8
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 (English ascii letters [a-zA-Z]) 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 0-9 and English ascii letters [a-zA-Z] only.
88 define('PARAM_ALPHANUM', 'alphanum');
90 /**
91 * PARAM_ALPHANUMEXT - expected numbers 0-9, letters (English ascii letters [a-zA-Z]) and _- only.
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
210 * and other references to Moodle code files.
212 * This is NOT intended to be used for absolute paths or any user uploaded files.
214 define('PARAM_SAFEPATH', 'safepath');
217 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
219 define('PARAM_SEQUENCE', 'sequence');
222 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
224 define('PARAM_TAG', 'tag');
227 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
229 define('PARAM_TAGLIST', 'taglist');
232 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
234 define('PARAM_TEXT', 'text');
237 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
239 define('PARAM_THEME', 'theme');
242 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
243 * http://localhost.localdomain/ is ok.
245 define('PARAM_URL', 'url');
248 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
249 * accounts, do NOT use when syncing with external systems!!
251 define('PARAM_USERNAME', 'username');
254 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
256 define('PARAM_STRINGID', 'stringid');
258 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
260 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
261 * It was one of the first types, that is why it is abused so much ;-)
262 * @deprecated since 2.0
264 define('PARAM_CLEAN', 'clean');
267 * PARAM_INTEGER - deprecated alias for PARAM_INT
268 * @deprecated since 2.0
270 define('PARAM_INTEGER', 'int');
273 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
274 * @deprecated since 2.0
276 define('PARAM_NUMBER', 'float');
279 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
280 * NOTE: originally alias for PARAM_APLHA
281 * @deprecated since 2.0
283 define('PARAM_ACTION', 'alphanumext');
286 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
287 * NOTE: originally alias for PARAM_APLHA
288 * @deprecated since 2.0
290 define('PARAM_FORMAT', 'alphanumext');
293 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
294 * @deprecated since 2.0
296 define('PARAM_MULTILANG', 'text');
299 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
300 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
301 * America/Port-au-Prince)
303 define('PARAM_TIMEZONE', 'timezone');
306 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
308 define('PARAM_CLEANFILE', 'file');
311 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
312 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
313 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
314 * NOTE: numbers and underscores are strongly discouraged in plugin names!
316 define('PARAM_COMPONENT', 'component');
319 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
320 * It is usually used together with context id and component.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
323 define('PARAM_AREA', 'area');
326 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
327 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
328 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
330 define('PARAM_PLUGIN', 'plugin');
333 // Web Services.
336 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
338 define('VALUE_REQUIRED', 1);
341 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
343 define('VALUE_OPTIONAL', 2);
346 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
348 define('VALUE_DEFAULT', 0);
351 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
353 define('NULL_NOT_ALLOWED', false);
356 * NULL_ALLOWED - the parameter can be set to null in the database
358 define('NULL_ALLOWED', true);
360 // Page types.
363 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
365 define('PAGE_COURSE_VIEW', 'course-view');
367 /** Get remote addr constant */
368 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
369 /** Get remote addr constant */
370 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
372 * GETREMOTEADDR_SKIP_DEFAULT defines the default behavior remote IP address validation.
374 define('GETREMOTEADDR_SKIP_DEFAULT', GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR|GETREMOTEADDR_SKIP_HTTP_CLIENT_IP);
376 // Blog access level constant declaration.
377 define ('BLOG_USER_LEVEL', 1);
378 define ('BLOG_GROUP_LEVEL', 2);
379 define ('BLOG_COURSE_LEVEL', 3);
380 define ('BLOG_SITE_LEVEL', 4);
381 define ('BLOG_GLOBAL_LEVEL', 5);
384 // Tag constants.
386 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
387 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
388 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
390 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
392 define('TAG_MAX_LENGTH', 50);
394 // Password policy constants.
395 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
396 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
397 define ('PASSWORD_DIGITS', '0123456789');
398 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
400 // Feature constants.
401 // Used for plugin_supports() to report features that are, or are not, supported by a module.
403 /** True if module can provide a grade */
404 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
405 /** True if module supports outcomes */
406 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
407 /** True if module supports advanced grading methods */
408 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
409 /** True if module controls the grade visibility over the gradebook */
410 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
411 /** True if module supports plagiarism plugins */
412 define('FEATURE_PLAGIARISM', 'plagiarism');
414 /** True if module has code to track whether somebody viewed it */
415 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
416 /** True if module has custom completion rules */
417 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
419 /** True if module has no 'view' page (like label) */
420 define('FEATURE_NO_VIEW_LINK', 'viewlink');
421 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
422 define('FEATURE_IDNUMBER', 'idnumber');
423 /** True if module supports groups */
424 define('FEATURE_GROUPS', 'groups');
425 /** True if module supports groupings */
426 define('FEATURE_GROUPINGS', 'groupings');
428 * True if module supports groupmembersonly (which no longer exists)
429 * @deprecated Since Moodle 2.8
431 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
433 /** Type of module */
434 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
435 /** True if module supports intro editor */
436 define('FEATURE_MOD_INTRO', 'mod_intro');
437 /** True if module has default completion */
438 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
440 define('FEATURE_COMMENT', 'comment');
442 define('FEATURE_RATE', 'rate');
443 /** True if module supports backup/restore of moodle2 format */
444 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
446 /** True if module can show description on course main page */
447 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
449 /** True if module uses the question bank */
450 define('FEATURE_USES_QUESTIONS', 'usesquestions');
453 * Maximum filename char size
455 define('MAX_FILENAME_SIZE', 100);
457 /** Unspecified module archetype */
458 define('MOD_ARCHETYPE_OTHER', 0);
459 /** Resource-like type module */
460 define('MOD_ARCHETYPE_RESOURCE', 1);
461 /** Assignment module archetype */
462 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
463 /** System (not user-addable) module archetype */
464 define('MOD_ARCHETYPE_SYSTEM', 3);
466 /** Type of module */
467 define('FEATURE_MOD_PURPOSE', 'mod_purpose');
468 /** Module purpose administration */
469 define('MOD_PURPOSE_ADMINISTRATION', 'administration');
470 /** Module purpose assessment */
471 define('MOD_PURPOSE_ASSESSMENT', 'assessment');
472 /** Module purpose communication */
473 define('MOD_PURPOSE_COLLABORATION', 'collaboration');
474 /** Module purpose communication */
475 define('MOD_PURPOSE_COMMUNICATION', 'communication');
476 /** Module purpose content */
477 define('MOD_PURPOSE_CONTENT', 'content');
478 /** Module purpose interface */
479 define('MOD_PURPOSE_INTERFACE', 'interface');
480 /** Module purpose other */
481 define('MOD_PURPOSE_OTHER', 'other');
484 * Security token used for allowing access
485 * from external application such as web services.
486 * Scripts do not use any session, performance is relatively
487 * low because we need to load access info in each request.
488 * Scripts are executed in parallel.
490 define('EXTERNAL_TOKEN_PERMANENT', 0);
493 * Security token used for allowing access
494 * of embedded applications, the code is executed in the
495 * active user session. Token is invalidated after user logs out.
496 * Scripts are executed serially - normal session locking is used.
498 define('EXTERNAL_TOKEN_EMBEDDED', 1);
501 * The home page should be the site home
503 define('HOMEPAGE_SITE', 0);
505 * The home page should be the users my page
507 define('HOMEPAGE_MY', 1);
509 * The home page can be chosen by the user
511 define('HOMEPAGE_USER', 2);
513 * The home page should be the users my courses page
515 define('HOMEPAGE_MYCOURSES', 3);
518 * URL of the Moodle sites registration portal.
520 defined('HUB_MOODLEORGHUBURL') || define('HUB_MOODLEORGHUBURL', 'https://stats.moodle.org');
523 * URL of the statistic server public key.
525 defined('HUB_STATSPUBLICKEY') || define('HUB_STATSPUBLICKEY', 'https://moodle.org/static/statspubkey.pem');
528 * Moodle mobile app service name
530 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
533 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
535 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
538 * Course display settings: display all sections on one page.
540 define('COURSE_DISPLAY_SINGLEPAGE', 0);
542 * Course display settings: split pages into a page per section.
544 define('COURSE_DISPLAY_MULTIPAGE', 1);
547 * Authentication constant: String used in password field when password is not stored.
549 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
552 * Email from header to never include via information.
554 define('EMAIL_VIA_NEVER', 0);
557 * Email from header to always include via information.
559 define('EMAIL_VIA_ALWAYS', 1);
562 * Email from header to only include via information if the address is no-reply.
564 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
567 * Contact site support form/link disabled.
569 define('CONTACT_SUPPORT_DISABLED', 0);
572 * Contact site support form/link only available to authenticated users.
574 define('CONTACT_SUPPORT_AUTHENTICATED', 1);
577 * Contact site support form/link available to anyone visiting the site.
579 define('CONTACT_SUPPORT_ANYONE', 2);
581 // PARAMETER HANDLING.
584 * Returns a particular value for the named variable, taken from
585 * POST or GET. If the parameter doesn't exist then an error is
586 * thrown because we require this variable.
588 * This function should be used to initialise all required values
589 * in a script that are based on parameters. Usually it will be
590 * used like this:
591 * $id = required_param('id', PARAM_INT);
593 * Please note the $type parameter is now required and the value can not be array.
595 * @param string $parname the name of the page parameter we want
596 * @param string $type expected type of parameter
597 * @return mixed
598 * @throws coding_exception
600 function required_param($parname, $type) {
601 if (func_num_args() != 2 or empty($parname) or empty($type)) {
602 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
604 // POST has precedence.
605 if (isset($_POST[$parname])) {
606 $param = $_POST[$parname];
607 } else if (isset($_GET[$parname])) {
608 $param = $_GET[$parname];
609 } else {
610 throw new \moodle_exception('missingparam', '', '', $parname);
613 if (is_array($param)) {
614 debugging('Invalid array parameter detected in required_param(): '.$parname);
615 // TODO: switch to fatal error in Moodle 2.3.
616 return required_param_array($parname, $type);
619 return clean_param($param, $type);
623 * Returns a particular array value for the named variable, taken from
624 * POST or GET. If the parameter doesn't exist then an error is
625 * thrown because we require this variable.
627 * This function should be used to initialise all required values
628 * in a script that are based on parameters. Usually it will be
629 * used like this:
630 * $ids = required_param_array('ids', PARAM_INT);
632 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
634 * @param string $parname the name of the page parameter we want
635 * @param string $type expected type of parameter
636 * @return array
637 * @throws coding_exception
639 function required_param_array($parname, $type) {
640 if (func_num_args() != 2 or empty($parname) or empty($type)) {
641 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
643 // POST has precedence.
644 if (isset($_POST[$parname])) {
645 $param = $_POST[$parname];
646 } else if (isset($_GET[$parname])) {
647 $param = $_GET[$parname];
648 } else {
649 throw new \moodle_exception('missingparam', '', '', $parname);
651 if (!is_array($param)) {
652 throw new \moodle_exception('missingparam', '', '', $parname);
655 $result = array();
656 foreach ($param as $key => $value) {
657 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
658 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
659 continue;
661 $result[$key] = clean_param($value, $type);
664 return $result;
668 * Returns a particular value for the named variable, taken from
669 * POST or GET, otherwise returning a given default.
671 * This function should be used to initialise all optional values
672 * in a script that are based on parameters. Usually it will be
673 * used like this:
674 * $name = optional_param('name', 'Fred', PARAM_TEXT);
676 * Please note the $type parameter is now required and the value can not be array.
678 * @param string $parname the name of the page parameter we want
679 * @param mixed $default the default value to return if nothing is found
680 * @param string $type expected type of parameter
681 * @return mixed
682 * @throws coding_exception
684 function optional_param($parname, $default, $type) {
685 if (func_num_args() != 3 or empty($parname) or empty($type)) {
686 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
689 // POST has precedence.
690 if (isset($_POST[$parname])) {
691 $param = $_POST[$parname];
692 } else if (isset($_GET[$parname])) {
693 $param = $_GET[$parname];
694 } else {
695 return $default;
698 if (is_array($param)) {
699 debugging('Invalid array parameter detected in required_param(): '.$parname);
700 // TODO: switch to $default in Moodle 2.3.
701 return optional_param_array($parname, $default, $type);
704 return clean_param($param, $type);
708 * Returns a particular array value for the named variable, taken from
709 * POST or GET, otherwise returning a given default.
711 * This function should be used to initialise all optional values
712 * in a script that are based on parameters. Usually it will be
713 * used like this:
714 * $ids = optional_param('id', array(), PARAM_INT);
716 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
718 * @param string $parname the name of the page parameter we want
719 * @param mixed $default the default value to return if nothing is found
720 * @param string $type expected type of parameter
721 * @return array
722 * @throws coding_exception
724 function optional_param_array($parname, $default, $type) {
725 if (func_num_args() != 3 or empty($parname) or empty($type)) {
726 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
729 // POST has precedence.
730 if (isset($_POST[$parname])) {
731 $param = $_POST[$parname];
732 } else if (isset($_GET[$parname])) {
733 $param = $_GET[$parname];
734 } else {
735 return $default;
737 if (!is_array($param)) {
738 debugging('optional_param_array() expects array parameters only: '.$parname);
739 return $default;
742 $result = array();
743 foreach ($param as $key => $value) {
744 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
745 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
746 continue;
748 $result[$key] = clean_param($value, $type);
751 return $result;
755 * Strict validation of parameter values, the values are only converted
756 * to requested PHP type. Internally it is using clean_param, the values
757 * before and after cleaning must be equal - otherwise
758 * an invalid_parameter_exception is thrown.
759 * Objects and classes are not accepted.
761 * @param mixed $param
762 * @param string $type PARAM_ constant
763 * @param bool $allownull are nulls valid value?
764 * @param string $debuginfo optional debug information
765 * @return mixed the $param value converted to PHP type
766 * @throws invalid_parameter_exception if $param is not of given type
768 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
769 if (is_null($param)) {
770 if ($allownull == NULL_ALLOWED) {
771 return null;
772 } else {
773 throw new invalid_parameter_exception($debuginfo);
776 if (is_array($param) or is_object($param)) {
777 throw new invalid_parameter_exception($debuginfo);
780 $cleaned = clean_param($param, $type);
782 if ($type == PARAM_FLOAT) {
783 // Do not detect precision loss here.
784 if (is_float($param) or is_int($param)) {
785 // These always fit.
786 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
787 throw new invalid_parameter_exception($debuginfo);
789 } else if ((string)$param !== (string)$cleaned) {
790 // Conversion to string is usually lossless.
791 throw new invalid_parameter_exception($debuginfo);
794 return $cleaned;
798 * Makes sure array contains only the allowed types, this function does not validate array key names!
800 * <code>
801 * $options = clean_param($options, PARAM_INT);
802 * </code>
804 * @param array|null $param the variable array we are cleaning
805 * @param string $type expected format of param after cleaning.
806 * @param bool $recursive clean recursive arrays
807 * @return array
808 * @throws coding_exception
810 function clean_param_array(?array $param, $type, $recursive = false) {
811 // Convert null to empty array.
812 $param = (array)$param;
813 foreach ($param as $key => $value) {
814 if (is_array($value)) {
815 if ($recursive) {
816 $param[$key] = clean_param_array($value, $type, true);
817 } else {
818 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
820 } else {
821 $param[$key] = clean_param($value, $type);
824 return $param;
828 * Used by {@link optional_param()} and {@link required_param()} to
829 * clean the variables and/or cast to specific types, based on
830 * an options field.
831 * <code>
832 * $course->format = clean_param($course->format, PARAM_ALPHA);
833 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
834 * </code>
836 * @param mixed $param the variable we are cleaning
837 * @param string $type expected format of param after cleaning.
838 * @return mixed
839 * @throws coding_exception
841 function clean_param($param, $type) {
842 global $CFG;
844 if (is_array($param)) {
845 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
846 } else if (is_object($param)) {
847 if (method_exists($param, '__toString')) {
848 $param = $param->__toString();
849 } else {
850 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
854 switch ($type) {
855 case PARAM_RAW:
856 // No cleaning at all.
857 $param = fix_utf8($param);
858 return $param;
860 case PARAM_RAW_TRIMMED:
861 // No cleaning, but strip leading and trailing whitespace.
862 $param = (string)fix_utf8($param);
863 return trim($param);
865 case PARAM_CLEAN:
866 // General HTML cleaning, try to use more specific type if possible this is deprecated!
867 // Please use more specific type instead.
868 if (is_numeric($param)) {
869 return $param;
871 $param = fix_utf8($param);
872 // Sweep for scripts, etc.
873 return clean_text($param);
875 case PARAM_CLEANHTML:
876 // Clean html fragment.
877 $param = (string)fix_utf8($param);
878 // Sweep for scripts, etc.
879 $param = clean_text($param, FORMAT_HTML);
880 return trim($param);
882 case PARAM_INT:
883 // Convert to integer.
884 return (int)$param;
886 case PARAM_FLOAT:
887 // Convert to float.
888 return (float)$param;
890 case PARAM_LOCALISEDFLOAT:
891 // Convert to float.
892 return unformat_float($param, true);
894 case PARAM_ALPHA:
895 // Remove everything not `a-z`.
896 return preg_replace('/[^a-zA-Z]/i', '', (string)$param);
898 case PARAM_ALPHAEXT:
899 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
900 return preg_replace('/[^a-zA-Z_-]/i', '', (string)$param);
902 case PARAM_ALPHANUM:
903 // Remove everything not `a-zA-Z0-9`.
904 return preg_replace('/[^A-Za-z0-9]/i', '', (string)$param);
906 case PARAM_ALPHANUMEXT:
907 // Remove everything not `a-zA-Z0-9_-`.
908 return preg_replace('/[^A-Za-z0-9_-]/i', '', (string)$param);
910 case PARAM_SEQUENCE:
911 // Remove everything not `0-9,`.
912 return preg_replace('/[^0-9,]/i', '', (string)$param);
914 case PARAM_BOOL:
915 // Convert to 1 or 0.
916 $tempstr = strtolower((string)$param);
917 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
918 $param = 1;
919 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
920 $param = 0;
921 } else {
922 $param = empty($param) ? 0 : 1;
924 return $param;
926 case PARAM_NOTAGS:
927 // Strip all tags.
928 $param = fix_utf8($param);
929 return strip_tags((string)$param);
931 case PARAM_TEXT:
932 // Leave only tags needed for multilang.
933 $param = fix_utf8($param);
934 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
935 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
936 do {
937 if (strpos((string)$param, '</lang>') !== false) {
938 // Old and future mutilang syntax.
939 $param = strip_tags($param, '<lang>');
940 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
941 break;
943 $open = false;
944 foreach ($matches[0] as $match) {
945 if ($match === '</lang>') {
946 if ($open) {
947 $open = false;
948 continue;
949 } else {
950 break 2;
953 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
954 break 2;
955 } else {
956 $open = true;
959 if ($open) {
960 break;
962 return $param;
964 } else if (strpos((string)$param, '</span>') !== false) {
965 // Current problematic multilang syntax.
966 $param = strip_tags($param, '<span>');
967 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
968 break;
970 $open = false;
971 foreach ($matches[0] as $match) {
972 if ($match === '</span>') {
973 if ($open) {
974 $open = false;
975 continue;
976 } else {
977 break 2;
980 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
981 break 2;
982 } else {
983 $open = true;
986 if ($open) {
987 break;
989 return $param;
991 } while (false);
992 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
993 return strip_tags((string)$param);
995 case PARAM_COMPONENT:
996 // We do not want any guessing here, either the name is correct or not
997 // please note only normalised component names are accepted.
998 $param = (string)$param;
999 if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
1000 return '';
1002 if (strpos($param, '__') !== false) {
1003 return '';
1005 if (strpos($param, 'mod_') === 0) {
1006 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
1007 if (substr_count($param, '_') != 1) {
1008 return '';
1011 return $param;
1013 case PARAM_PLUGIN:
1014 case PARAM_AREA:
1015 // We do not want any guessing here, either the name is correct or not.
1016 if (!is_valid_plugin_name($param)) {
1017 return '';
1019 return $param;
1021 case PARAM_SAFEDIR:
1022 // Remove everything not a-zA-Z0-9_- .
1023 return preg_replace('/[^a-zA-Z0-9_-]/i', '', (string)$param);
1025 case PARAM_SAFEPATH:
1026 // Remove everything not a-zA-Z0-9/_- .
1027 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', (string)$param);
1029 case PARAM_FILE:
1030 // Strip all suspicious characters from filename.
1031 $param = (string)fix_utf8($param);
1032 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
1033 if ($param === '.' || $param === '..') {
1034 $param = '';
1036 return $param;
1038 case PARAM_PATH:
1039 // Strip all suspicious characters from file path.
1040 $param = (string)fix_utf8($param);
1041 $param = str_replace('\\', '/', $param);
1043 // Explode the path and clean each element using the PARAM_FILE rules.
1044 $breadcrumb = explode('/', $param);
1045 foreach ($breadcrumb as $key => $crumb) {
1046 if ($crumb === '.' && $key === 0) {
1047 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1048 } else {
1049 $crumb = clean_param($crumb, PARAM_FILE);
1051 $breadcrumb[$key] = $crumb;
1053 $param = implode('/', $breadcrumb);
1055 // Remove multiple current path (./././) and multiple slashes (///).
1056 $param = preg_replace('~//+~', '/', $param);
1057 $param = preg_replace('~/(\./)+~', '/', $param);
1058 return $param;
1060 case PARAM_HOST:
1061 // Allow FQDN or IPv4 dotted quad.
1062 $param = preg_replace('/[^\.\d\w-]/', '', (string)$param );
1063 // Match ipv4 dotted quad.
1064 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1065 // Confirm values are ok.
1066 if ( $match[0] > 255
1067 || $match[1] > 255
1068 || $match[3] > 255
1069 || $match[4] > 255 ) {
1070 // Hmmm, what kind of dotted quad is this?
1071 $param = '';
1073 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1074 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1075 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1077 // All is ok - $param is respected.
1078 } else {
1079 // All is not ok...
1080 $param='';
1082 return $param;
1084 case PARAM_URL:
1085 // Allow safe urls.
1086 $param = (string)fix_utf8($param);
1087 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1088 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1089 // All is ok, param is respected.
1090 } else {
1091 // Not really ok.
1092 $param ='';
1094 return $param;
1096 case PARAM_LOCALURL:
1097 // Allow http absolute, root relative and relative URLs within wwwroot.
1098 $param = clean_param($param, PARAM_URL);
1099 if (!empty($param)) {
1101 if ($param === $CFG->wwwroot) {
1102 // Exact match;
1103 } else if (preg_match(':^/:', $param)) {
1104 // Root-relative, ok!
1105 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1106 // Absolute, and matches our wwwroot.
1107 } else {
1109 // Relative - let's make sure there are no tricks.
1110 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?') && !preg_match('/javascript:/i', $param)) {
1111 // Looks ok.
1112 } else {
1113 $param = '';
1117 return $param;
1119 case PARAM_PEM:
1120 $param = trim((string)$param);
1121 // PEM formatted strings may contain letters/numbers and the symbols:
1122 // forward slash: /
1123 // plus sign: +
1124 // equal sign: =
1125 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1126 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1127 list($wholething, $body) = $matches;
1128 unset($wholething, $matches);
1129 $b64 = clean_param($body, PARAM_BASE64);
1130 if (!empty($b64)) {
1131 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1132 } else {
1133 return '';
1136 return '';
1138 case PARAM_BASE64:
1139 if (!empty($param)) {
1140 // PEM formatted strings may contain letters/numbers and the symbols
1141 // forward slash: /
1142 // plus sign: +
1143 // equal sign: =.
1144 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1145 return '';
1147 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1148 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1149 // than (or equal to) 64 characters long.
1150 for ($i=0, $j=count($lines); $i < $j; $i++) {
1151 if ($i + 1 == $j) {
1152 if (64 < strlen($lines[$i])) {
1153 return '';
1155 continue;
1158 if (64 != strlen($lines[$i])) {
1159 return '';
1162 return implode("\n", $lines);
1163 } else {
1164 return '';
1167 case PARAM_TAG:
1168 $param = (string)fix_utf8($param);
1169 // Please note it is not safe to use the tag name directly anywhere,
1170 // it must be processed with s(), urlencode() before embedding anywhere.
1171 // Remove some nasties.
1172 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1173 // Convert many whitespace chars into one.
1174 $param = preg_replace('/\s+/u', ' ', $param);
1175 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1176 return $param;
1178 case PARAM_TAGLIST:
1179 $param = (string)fix_utf8($param);
1180 $tags = explode(',', $param);
1181 $result = array();
1182 foreach ($tags as $tag) {
1183 $res = clean_param($tag, PARAM_TAG);
1184 if ($res !== '') {
1185 $result[] = $res;
1188 if ($result) {
1189 return implode(',', $result);
1190 } else {
1191 return '';
1194 case PARAM_CAPABILITY:
1195 if (get_capability_info($param)) {
1196 return $param;
1197 } else {
1198 return '';
1201 case PARAM_PERMISSION:
1202 $param = (int)$param;
1203 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1204 return $param;
1205 } else {
1206 return CAP_INHERIT;
1209 case PARAM_AUTH:
1210 $param = clean_param($param, PARAM_PLUGIN);
1211 if (empty($param)) {
1212 return '';
1213 } else if (exists_auth_plugin($param)) {
1214 return $param;
1215 } else {
1216 return '';
1219 case PARAM_LANG:
1220 $param = clean_param($param, PARAM_SAFEDIR);
1221 if (get_string_manager()->translation_exists($param)) {
1222 return $param;
1223 } else {
1224 // Specified language is not installed or param malformed.
1225 return '';
1228 case PARAM_THEME:
1229 $param = clean_param($param, PARAM_PLUGIN);
1230 if (empty($param)) {
1231 return '';
1232 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1233 return $param;
1234 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1235 return $param;
1236 } else {
1237 // Specified theme is not installed.
1238 return '';
1241 case PARAM_USERNAME:
1242 $param = (string)fix_utf8($param);
1243 $param = trim($param);
1244 // Convert uppercase to lowercase MDL-16919.
1245 $param = core_text::strtolower($param);
1246 if (empty($CFG->extendedusernamechars)) {
1247 $param = str_replace(" " , "", $param);
1248 // Regular expression, eliminate all chars EXCEPT:
1249 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1250 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1252 return $param;
1254 case PARAM_EMAIL:
1255 $param = fix_utf8($param);
1256 if (validate_email($param ?? '')) {
1257 return $param;
1258 } else {
1259 return '';
1262 case PARAM_STRINGID:
1263 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', (string)$param)) {
1264 return $param;
1265 } else {
1266 return '';
1269 case PARAM_TIMEZONE:
1270 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1271 $param = (string)fix_utf8($param);
1272 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1273 if (preg_match($timezonepattern, $param)) {
1274 return $param;
1275 } else {
1276 return '';
1279 default:
1280 // Doh! throw error, switched parameters in optional_param or another serious problem.
1281 throw new \moodle_exception("unknownparamtype", '', '', $type);
1286 * Whether the PARAM_* type is compatible in RTL.
1288 * Being compatible with RTL means that the data they contain can flow
1289 * from right-to-left or left-to-right without compromising the user experience.
1291 * Take URLs for example, they are not RTL compatible as they should always
1292 * flow from the left to the right. This also applies to numbers, email addresses,
1293 * configuration snippets, base64 strings, etc...
1295 * This function tries to best guess which parameters can contain localised strings.
1297 * @param string $paramtype Constant PARAM_*.
1298 * @return bool
1300 function is_rtl_compatible($paramtype) {
1301 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1305 * Makes sure the data is using valid utf8, invalid characters are discarded.
1307 * Note: this function is not intended for full objects with methods and private properties.
1309 * @param mixed $value
1310 * @return mixed with proper utf-8 encoding
1312 function fix_utf8($value) {
1313 if (is_null($value) or $value === '') {
1314 return $value;
1316 } else if (is_string($value)) {
1317 if ((string)(int)$value === $value) {
1318 // Shortcut.
1319 return $value;
1322 // Remove null bytes or invalid Unicode sequences from value.
1323 $value = str_replace(["\0", "\xef\xbf\xbe", "\xef\xbf\xbf"], '', $value);
1325 // Note: this duplicates min_fix_utf8() intentionally.
1326 static $buggyiconv = null;
1327 if ($buggyiconv === null) {
1328 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1331 if ($buggyiconv) {
1332 if (function_exists('mb_convert_encoding')) {
1333 $subst = mb_substitute_character();
1334 mb_substitute_character('none');
1335 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1336 mb_substitute_character($subst);
1338 } else {
1339 // Warn admins on admin/index.php page.
1340 $result = $value;
1343 } else {
1344 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1347 return $result;
1349 } else if (is_array($value)) {
1350 foreach ($value as $k => $v) {
1351 $value[$k] = fix_utf8($v);
1353 return $value;
1355 } else if (is_object($value)) {
1356 // Do not modify original.
1357 $value = clone($value);
1358 foreach ($value as $k => $v) {
1359 $value->$k = fix_utf8($v);
1361 return $value;
1363 } else {
1364 // This is some other type, no utf-8 here.
1365 return $value;
1370 * Return true if given value is integer or string with integer value
1372 * @param mixed $value String or Int
1373 * @return bool true if number, false if not
1375 function is_number($value) {
1376 if (is_int($value)) {
1377 return true;
1378 } else if (is_string($value)) {
1379 return ((string)(int)$value) === $value;
1380 } else {
1381 return false;
1386 * Returns host part from url.
1388 * @param string $url full url
1389 * @return string host, null if not found
1391 function get_host_from_url($url) {
1392 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1393 if ($matches) {
1394 return $matches[1];
1396 return null;
1400 * Tests whether anything was returned by text editor
1402 * This function is useful for testing whether something you got back from
1403 * the HTML editor actually contains anything. Sometimes the HTML editor
1404 * appear to be empty, but actually you get back a <br> tag or something.
1406 * @param string $string a string containing HTML.
1407 * @return boolean does the string contain any actual content - that is text,
1408 * images, objects, etc.
1410 function html_is_blank($string) {
1411 return trim(strip_tags((string)$string, '<img><object><applet><input><select><textarea><hr>')) == '';
1415 * Set a key in global configuration
1417 * Set a key/value pair in both this session's {@link $CFG} global variable
1418 * and in the 'config' database table for future sessions.
1420 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1421 * In that case it doesn't affect $CFG.
1423 * A NULL value will delete the entry.
1425 * NOTE: this function is called from lib/db/upgrade.php
1427 * @param string $name the key to set
1428 * @param string $value the value to set (without magic quotes)
1429 * @param string $plugin (optional) the plugin scope, default null
1430 * @return bool true or exception
1432 function set_config($name, $value, $plugin = null) {
1433 global $CFG, $DB;
1435 // Redirect to appropriate handler when value is null.
1436 if ($value === null) {
1437 return unset_config($name, $plugin);
1440 // Set variables determining conditions and where to store the new config.
1441 // Plugin config goes to {config_plugins}, core config goes to {config}.
1442 $iscore = empty($plugin);
1443 if ($iscore) {
1444 // If it's for core config.
1445 $table = 'config';
1446 $conditions = ['name' => $name];
1447 $invalidatecachekey = 'core';
1448 } else {
1449 // If it's a plugin.
1450 $table = 'config_plugins';
1451 $conditions = ['name' => $name, 'plugin' => $plugin];
1452 $invalidatecachekey = $plugin;
1455 // DB handling - checks for existing config, updating or inserting only if necessary.
1456 $invalidatecache = true;
1457 $inserted = false;
1458 $record = $DB->get_record($table, $conditions, 'id, value');
1459 if ($record === false) {
1460 // Inserts a new config record.
1461 $config = new stdClass();
1462 $config->name = $name;
1463 $config->value = $value;
1464 if (!$iscore) {
1465 $config->plugin = $plugin;
1467 $inserted = $DB->insert_record($table, $config, false);
1468 } else if ($invalidatecache = ($record->value !== $value)) {
1469 // Record exists - Check and only set new value if it has changed.
1470 $DB->set_field($table, 'value', $value, ['id' => $record->id]);
1473 if ($iscore && !isset($CFG->config_php_settings[$name])) {
1474 // So it's defined for this invocation at least.
1475 // Settings from db are always strings.
1476 $CFG->$name = (string) $value;
1479 // When setting config during a Behat test (in the CLI script, not in the web browser
1480 // requests), remember which ones are set so that we can clear them later.
1481 if ($iscore && $inserted && defined('BEHAT_TEST')) {
1482 $CFG->behat_cli_added_config[$name] = true;
1485 // Update siteidentifier cache, if required.
1486 if ($iscore && $name === 'siteidentifier') {
1487 cache_helper::update_site_identifier($value);
1490 // Invalidate cache, if required.
1491 if ($invalidatecache) {
1492 cache_helper::invalidate_by_definition('core', 'config', [], $invalidatecachekey);
1495 return true;
1499 * Get configuration values from the global config table
1500 * or the config_plugins table.
1502 * If called with one parameter, it will load all the config
1503 * variables for one plugin, and return them as an object.
1505 * If called with 2 parameters it will return a string single
1506 * value or false if the value is not found.
1508 * NOTE: this function is called from lib/db/upgrade.php
1510 * @param string $plugin full component name
1511 * @param string $name default null
1512 * @return mixed hash-like object or single value, return false no config found
1513 * @throws dml_exception
1515 function get_config($plugin, $name = null) {
1516 global $CFG, $DB;
1518 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1519 $forced =& $CFG->config_php_settings;
1520 $iscore = true;
1521 $plugin = 'core';
1522 } else {
1523 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1524 $forced =& $CFG->forced_plugin_settings[$plugin];
1525 } else {
1526 $forced = array();
1528 $iscore = false;
1531 if (!isset($CFG->siteidentifier)) {
1532 try {
1533 // This may throw an exception during installation, which is how we detect the
1534 // need to install the database. For more details see {@see initialise_cfg()}.
1535 $CFG->siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1536 } catch (dml_exception $ex) {
1537 // Set siteidentifier to false. We don't want to trip this continually.
1538 $siteidentifier = false;
1539 throw $ex;
1543 if (!empty($name)) {
1544 if (array_key_exists($name, $forced)) {
1545 return (string)$forced[$name];
1546 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1547 return $CFG->siteidentifier;
1551 $cache = cache::make('core', 'config');
1552 $result = $cache->get($plugin);
1553 if ($result === false) {
1554 // The user is after a recordset.
1555 if (!$iscore) {
1556 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1557 } else {
1558 // This part is not really used any more, but anyway...
1559 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1561 $cache->set($plugin, $result);
1564 if (!empty($name)) {
1565 if (array_key_exists($name, $result)) {
1566 return $result[$name];
1568 return false;
1571 if ($plugin === 'core') {
1572 $result['siteidentifier'] = $CFG->siteidentifier;
1575 foreach ($forced as $key => $value) {
1576 if (is_null($value) or is_array($value) or is_object($value)) {
1577 // We do not want any extra mess here, just real settings that could be saved in db.
1578 unset($result[$key]);
1579 } else {
1580 // Convert to string as if it went through the DB.
1581 $result[$key] = (string)$value;
1585 return (object)$result;
1589 * Removes a key from global configuration.
1591 * NOTE: this function is called from lib/db/upgrade.php
1593 * @param string $name the key to set
1594 * @param string $plugin (optional) the plugin scope
1595 * @return boolean whether the operation succeeded.
1597 function unset_config($name, $plugin=null) {
1598 global $CFG, $DB;
1600 if (empty($plugin)) {
1601 unset($CFG->$name);
1602 $DB->delete_records('config', array('name' => $name));
1603 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1604 } else {
1605 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1606 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1609 return true;
1613 * Remove all the config variables for a given plugin.
1615 * NOTE: this function is called from lib/db/upgrade.php
1617 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1618 * @return boolean whether the operation succeeded.
1620 function unset_all_config_for_plugin($plugin) {
1621 global $DB;
1622 // Delete from the obvious config_plugins first.
1623 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1624 // Next delete any suspect settings from config.
1625 $like = $DB->sql_like('name', '?', true, true, false, '|');
1626 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1627 $DB->delete_records_select('config', $like, $params);
1628 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1629 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1631 return true;
1635 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1637 * All users are verified if they still have the necessary capability.
1639 * @param string $value the value of the config setting.
1640 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1641 * @param bool $includeadmins include administrators.
1642 * @return array of user objects.
1644 function get_users_from_config($value, $capability, $includeadmins = true) {
1645 if (empty($value) or $value === '$@NONE@$') {
1646 return array();
1649 // We have to make sure that users still have the necessary capability,
1650 // it should be faster to fetch them all first and then test if they are present
1651 // instead of validating them one-by-one.
1652 $users = get_users_by_capability(context_system::instance(), $capability);
1653 if ($includeadmins) {
1654 $admins = get_admins();
1655 foreach ($admins as $admin) {
1656 $users[$admin->id] = $admin;
1660 if ($value === '$@ALL@$') {
1661 return $users;
1664 $result = array(); // Result in correct order.
1665 $allowed = explode(',', $value);
1666 foreach ($allowed as $uid) {
1667 if (isset($users[$uid])) {
1668 $user = $users[$uid];
1669 $result[$user->id] = $user;
1673 return $result;
1678 * Invalidates browser caches and cached data in temp.
1680 * @return void
1682 function purge_all_caches() {
1683 purge_caches();
1687 * Selectively invalidate different types of cache.
1689 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1690 * areas alone or in combination.
1692 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1693 * 'muc' Purge MUC caches?
1694 * 'theme' Purge theme cache?
1695 * 'lang' Purge language string cache?
1696 * 'js' Purge javascript cache?
1697 * 'filter' Purge text filter cache?
1698 * 'other' Purge all other caches?
1700 function purge_caches($options = []) {
1701 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1702 if (empty(array_filter($options))) {
1703 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1704 } else {
1705 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1707 if ($options['muc']) {
1708 cache_helper::purge_all();
1710 if ($options['theme']) {
1711 theme_reset_all_caches();
1713 if ($options['lang']) {
1714 get_string_manager()->reset_caches();
1716 if ($options['js']) {
1717 js_reset_all_caches();
1719 if ($options['template']) {
1720 template_reset_all_caches();
1722 if ($options['filter']) {
1723 reset_text_filters_cache();
1725 if ($options['other']) {
1726 purge_other_caches();
1731 * Purge all non-MUC caches not otherwise purged in purge_caches.
1733 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1734 * {@link phpunit_util::reset_dataroot()}
1736 function purge_other_caches() {
1737 global $DB, $CFG;
1738 if (class_exists('core_plugin_manager')) {
1739 core_plugin_manager::reset_caches();
1742 // Bump up cacherev field for all courses.
1743 try {
1744 increment_revision_number('course', 'cacherev', '');
1745 } catch (moodle_exception $e) {
1746 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1749 $DB->reset_caches();
1751 // Purge all other caches: rss, simplepie, etc.
1752 clearstatcache();
1753 remove_dir($CFG->cachedir.'', true);
1755 // Make sure cache dir is writable, throws exception if not.
1756 make_cache_directory('');
1758 // This is the only place where we purge local caches, we are only adding files there.
1759 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1760 remove_dir($CFG->localcachedir, true);
1761 set_config('localcachedirpurged', time());
1762 make_localcache_directory('', true);
1763 \core\task\manager::clear_static_caches();
1767 * Get volatile flags
1769 * @param string $type
1770 * @param int $changedsince default null
1771 * @return array records array
1773 function get_cache_flags($type, $changedsince = null) {
1774 global $DB;
1776 $params = array('type' => $type, 'expiry' => time());
1777 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1778 if ($changedsince !== null) {
1779 $params['changedsince'] = $changedsince;
1780 $sqlwhere .= " AND timemodified > :changedsince";
1782 $cf = array();
1783 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1784 foreach ($flags as $flag) {
1785 $cf[$flag->name] = $flag->value;
1788 return $cf;
1792 * Get volatile flags
1794 * @param string $type
1795 * @param string $name
1796 * @param int $changedsince default null
1797 * @return string|false The cache flag value or false
1799 function get_cache_flag($type, $name, $changedsince=null) {
1800 global $DB;
1802 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1804 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1805 if ($changedsince !== null) {
1806 $params['changedsince'] = $changedsince;
1807 $sqlwhere .= " AND timemodified > :changedsince";
1810 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1814 * Set a volatile flag
1816 * @param string $type the "type" namespace for the key
1817 * @param string $name the key to set
1818 * @param string $value the value to set (without magic quotes) - null will remove the flag
1819 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1820 * @return bool Always returns true
1822 function set_cache_flag($type, $name, $value, $expiry = null) {
1823 global $DB;
1825 $timemodified = time();
1826 if ($expiry === null || $expiry < $timemodified) {
1827 $expiry = $timemodified + 24 * 60 * 60;
1828 } else {
1829 $expiry = (int)$expiry;
1832 if ($value === null) {
1833 unset_cache_flag($type, $name);
1834 return true;
1837 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1838 // This is a potential problem in DEBUG_DEVELOPER.
1839 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1840 return true; // No need to update.
1842 $f->value = $value;
1843 $f->expiry = $expiry;
1844 $f->timemodified = $timemodified;
1845 $DB->update_record('cache_flags', $f);
1846 } else {
1847 $f = new stdClass();
1848 $f->flagtype = $type;
1849 $f->name = $name;
1850 $f->value = $value;
1851 $f->expiry = $expiry;
1852 $f->timemodified = $timemodified;
1853 $DB->insert_record('cache_flags', $f);
1855 return true;
1859 * Removes a single volatile flag
1861 * @param string $type the "type" namespace for the key
1862 * @param string $name the key to set
1863 * @return bool
1865 function unset_cache_flag($type, $name) {
1866 global $DB;
1867 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1868 return true;
1872 * Garbage-collect volatile flags
1874 * @return bool Always returns true
1876 function gc_cache_flags() {
1877 global $DB;
1878 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1879 return true;
1882 // USER PREFERENCE API.
1885 * Refresh user preference cache. This is used most often for $USER
1886 * object that is stored in session, but it also helps with performance in cron script.
1888 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1890 * @package core
1891 * @category preference
1892 * @access public
1893 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1894 * @param int $cachelifetime Cache life time on the current page (in seconds)
1895 * @throws coding_exception
1896 * @return null
1898 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1899 global $DB;
1900 // Static cache, we need to check on each page load, not only every 2 minutes.
1901 static $loadedusers = array();
1903 if (!isset($user->id)) {
1904 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1907 if (empty($user->id) or isguestuser($user->id)) {
1908 // No permanent storage for not-logged-in users and guest.
1909 if (!isset($user->preference)) {
1910 $user->preference = array();
1912 return;
1915 $timenow = time();
1917 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1918 // Already loaded at least once on this page. Are we up to date?
1919 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1920 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1921 return;
1923 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1924 // No change since the lastcheck on this page.
1925 $user->preference['_lastloaded'] = $timenow;
1926 return;
1930 // OK, so we have to reload all preferences.
1931 $loadedusers[$user->id] = true;
1932 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1933 $user->preference['_lastloaded'] = $timenow;
1937 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1939 * NOTE: internal function, do not call from other code.
1941 * @package core
1942 * @access private
1943 * @param integer $userid the user whose prefs were changed.
1945 function mark_user_preferences_changed($userid) {
1946 global $CFG;
1948 if (empty($userid) or isguestuser($userid)) {
1949 // No cache flags for guest and not-logged-in users.
1950 return;
1953 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1957 * Sets a preference for the specified user.
1959 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1961 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1963 * @package core
1964 * @category preference
1965 * @access public
1966 * @param string $name The key to set as preference for the specified user
1967 * @param string $value The value to set for the $name key in the specified user's
1968 * record, null means delete current value.
1969 * @param stdClass|int|null $user A moodle user object or id, null means current user
1970 * @throws coding_exception
1971 * @return bool Always true or exception
1973 function set_user_preference($name, $value, $user = null) {
1974 global $USER, $DB;
1976 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1977 throw new coding_exception('Invalid preference name in set_user_preference() call');
1980 if (is_null($value)) {
1981 // Null means delete current.
1982 return unset_user_preference($name, $user);
1983 } else if (is_object($value)) {
1984 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1985 } else if (is_array($value)) {
1986 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1988 // Value column maximum length is 1333 characters.
1989 $value = (string)$value;
1990 if (core_text::strlen($value) > 1333) {
1991 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1994 if (is_null($user)) {
1995 $user = $USER;
1996 } else if (isset($user->id)) {
1997 // It is a valid object.
1998 } else if (is_numeric($user)) {
1999 $user = (object)array('id' => (int)$user);
2000 } else {
2001 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
2004 check_user_preferences_loaded($user);
2006 if (empty($user->id) or isguestuser($user->id)) {
2007 // No permanent storage for not-logged-in users and guest.
2008 $user->preference[$name] = $value;
2009 return true;
2012 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
2013 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
2014 // Preference already set to this value.
2015 return true;
2017 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
2019 } else {
2020 $preference = new stdClass();
2021 $preference->userid = $user->id;
2022 $preference->name = $name;
2023 $preference->value = $value;
2024 $DB->insert_record('user_preferences', $preference);
2027 // Update value in cache.
2028 $user->preference[$name] = $value;
2029 // Update the $USER in case where we've not a direct reference to $USER.
2030 if ($user !== $USER && $user->id == $USER->id) {
2031 $USER->preference[$name] = $value;
2034 // Set reload flag for other sessions.
2035 mark_user_preferences_changed($user->id);
2037 return true;
2041 * Sets a whole array of preferences for the current user
2043 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2045 * @package core
2046 * @category preference
2047 * @access public
2048 * @param array $prefarray An array of key/value pairs to be set
2049 * @param stdClass|int|null $user A moodle user object or id, null means current user
2050 * @return bool Always true or exception
2052 function set_user_preferences(array $prefarray, $user = null) {
2053 foreach ($prefarray as $name => $value) {
2054 set_user_preference($name, $value, $user);
2056 return true;
2060 * Unsets a preference completely by deleting it from the database
2062 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2064 * @package core
2065 * @category preference
2066 * @access public
2067 * @param string $name The key to unset as preference for the specified user
2068 * @param stdClass|int|null $user A moodle user object or id, null means current user
2069 * @throws coding_exception
2070 * @return bool Always true or exception
2072 function unset_user_preference($name, $user = null) {
2073 global $USER, $DB;
2075 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2076 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2079 if (is_null($user)) {
2080 $user = $USER;
2081 } else if (isset($user->id)) {
2082 // It is a valid object.
2083 } else if (is_numeric($user)) {
2084 $user = (object)array('id' => (int)$user);
2085 } else {
2086 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2089 check_user_preferences_loaded($user);
2091 if (empty($user->id) or isguestuser($user->id)) {
2092 // No permanent storage for not-logged-in user and guest.
2093 unset($user->preference[$name]);
2094 return true;
2097 // Delete from DB.
2098 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2100 // Delete the preference from cache.
2101 unset($user->preference[$name]);
2102 // Update the $USER in case where we've not a direct reference to $USER.
2103 if ($user !== $USER && $user->id == $USER->id) {
2104 unset($USER->preference[$name]);
2107 // Set reload flag for other sessions.
2108 mark_user_preferences_changed($user->id);
2110 return true;
2114 * Used to fetch user preference(s)
2116 * If no arguments are supplied this function will return
2117 * all of the current user preferences as an array.
2119 * If a name is specified then this function
2120 * attempts to return that particular preference value. If
2121 * none is found, then the optional value $default is returned,
2122 * otherwise null.
2124 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2126 * @package core
2127 * @category preference
2128 * @access public
2129 * @param string $name Name of the key to use in finding a preference value
2130 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2131 * @param stdClass|int|null $user A moodle user object or id, null means current user
2132 * @throws coding_exception
2133 * @return string|mixed|null A string containing the value of a single preference. An
2134 * array with all of the preferences or null
2136 function get_user_preferences($name = null, $default = null, $user = null) {
2137 global $USER;
2139 if (is_null($name)) {
2140 // All prefs.
2141 } else if (is_numeric($name) or $name === '_lastloaded') {
2142 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2145 if (is_null($user)) {
2146 $user = $USER;
2147 } else if (isset($user->id)) {
2148 // Is a valid object.
2149 } else if (is_numeric($user)) {
2150 if ($USER->id == $user) {
2151 $user = $USER;
2152 } else {
2153 $user = (object)array('id' => (int)$user);
2155 } else {
2156 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2159 check_user_preferences_loaded($user);
2161 if (empty($name)) {
2162 // All values.
2163 return $user->preference;
2164 } else if (isset($user->preference[$name])) {
2165 // The single string value.
2166 return $user->preference[$name];
2167 } else {
2168 // Default value (null if not specified).
2169 return $default;
2173 // FUNCTIONS FOR HANDLING TIME.
2176 * Given Gregorian date parts in user time produce a GMT timestamp.
2178 * @package core
2179 * @category time
2180 * @param int $year The year part to create timestamp of
2181 * @param int $month The month part to create timestamp of
2182 * @param int $day The day part to create timestamp of
2183 * @param int $hour The hour part to create timestamp of
2184 * @param int $minute The minute part to create timestamp of
2185 * @param int $second The second part to create timestamp of
2186 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2187 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2188 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2189 * applied only if timezone is 99 or string.
2190 * @return int GMT timestamp
2192 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2193 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2194 $date->setDate((int)$year, (int)$month, (int)$day);
2195 $date->setTime((int)$hour, (int)$minute, (int)$second);
2197 $time = $date->getTimestamp();
2199 if ($time === false) {
2200 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2201 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2204 // Moodle BC DST stuff.
2205 if (!$applydst) {
2206 $time += dst_offset_on($time, $timezone);
2209 return $time;
2214 * Format a date/time (seconds) as weeks, days, hours etc as needed
2216 * Given an amount of time in seconds, returns string
2217 * formatted nicely as years, days, hours etc as needed
2219 * @package core
2220 * @category time
2221 * @uses MINSECS
2222 * @uses HOURSECS
2223 * @uses DAYSECS
2224 * @uses YEARSECS
2225 * @param int $totalsecs Time in seconds
2226 * @param stdClass $str Should be a time object
2227 * @return string A nicely formatted date/time string
2229 function format_time($totalsecs, $str = null) {
2231 $totalsecs = abs($totalsecs);
2233 if (!$str) {
2234 // Create the str structure the slow way.
2235 $str = new stdClass();
2236 $str->day = get_string('day');
2237 $str->days = get_string('days');
2238 $str->hour = get_string('hour');
2239 $str->hours = get_string('hours');
2240 $str->min = get_string('min');
2241 $str->mins = get_string('mins');
2242 $str->sec = get_string('sec');
2243 $str->secs = get_string('secs');
2244 $str->year = get_string('year');
2245 $str->years = get_string('years');
2248 $years = floor($totalsecs/YEARSECS);
2249 $remainder = $totalsecs - ($years*YEARSECS);
2250 $days = floor($remainder/DAYSECS);
2251 $remainder = $totalsecs - ($days*DAYSECS);
2252 $hours = floor($remainder/HOURSECS);
2253 $remainder = $remainder - ($hours*HOURSECS);
2254 $mins = floor($remainder/MINSECS);
2255 $secs = $remainder - ($mins*MINSECS);
2257 $ss = ($secs == 1) ? $str->sec : $str->secs;
2258 $sm = ($mins == 1) ? $str->min : $str->mins;
2259 $sh = ($hours == 1) ? $str->hour : $str->hours;
2260 $sd = ($days == 1) ? $str->day : $str->days;
2261 $sy = ($years == 1) ? $str->year : $str->years;
2263 $oyears = '';
2264 $odays = '';
2265 $ohours = '';
2266 $omins = '';
2267 $osecs = '';
2269 if ($years) {
2270 $oyears = $years .' '. $sy;
2272 if ($days) {
2273 $odays = $days .' '. $sd;
2275 if ($hours) {
2276 $ohours = $hours .' '. $sh;
2278 if ($mins) {
2279 $omins = $mins .' '. $sm;
2281 if ($secs) {
2282 $osecs = $secs .' '. $ss;
2285 if ($years) {
2286 return trim($oyears .' '. $odays);
2288 if ($days) {
2289 return trim($odays .' '. $ohours);
2291 if ($hours) {
2292 return trim($ohours .' '. $omins);
2294 if ($mins) {
2295 return trim($omins .' '. $osecs);
2297 if ($secs) {
2298 return $osecs;
2300 return get_string('now');
2304 * Returns a formatted string that represents a date in user time.
2306 * @package core
2307 * @category time
2308 * @param int $date the timestamp in UTC, as obtained from the database.
2309 * @param string $format strftime format. You should probably get this using
2310 * get_string('strftime...', 'langconfig');
2311 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2312 * not 99 then daylight saving will not be added.
2313 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2314 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2315 * If false then the leading zero is maintained.
2316 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2317 * @return string the formatted date/time.
2319 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2320 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2321 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2325 * Returns a html "time" tag with both the exact user date with timezone information
2326 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2328 * @package core
2329 * @category time
2330 * @param int $date the timestamp in UTC, as obtained from the database.
2331 * @param string $format strftime format. You should probably get this using
2332 * get_string('strftime...', 'langconfig');
2333 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2334 * not 99 then daylight saving will not be added.
2335 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2336 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2337 * If false then the leading zero is maintained.
2338 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2339 * @return string the formatted date/time.
2341 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2342 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2343 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2344 return $userdatestr;
2346 $machinedate = new DateTime();
2347 $machinedate->setTimestamp(intval($date));
2348 $machinedate->setTimezone(core_date::get_user_timezone_object());
2350 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2354 * Returns a formatted date ensuring it is UTF-8.
2356 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2357 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2359 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2360 * @param string $format strftime format.
2361 * @param int|float|string $tz the user timezone
2362 * @return string the formatted date/time.
2363 * @since Moodle 2.3.3
2365 function date_format_string($date, $format, $tz = 99) {
2367 date_default_timezone_set(core_date::get_user_timezone($tz));
2369 if (date('A', 0) === date('A', HOURSECS * 18)) {
2370 $datearray = getdate($date);
2371 $format = str_replace([
2372 '%P',
2373 '%p',
2374 ], [
2375 $datearray['hours'] < 12 ? get_string('am', 'langconfig') : get_string('pm', 'langconfig'),
2376 $datearray['hours'] < 12 ? get_string('amcaps', 'langconfig') : get_string('pmcaps', 'langconfig'),
2377 ], $format);
2380 $datestring = core_date::strftime($format, $date);
2381 core_date::set_default_server_timezone();
2383 return $datestring;
2387 * Given a $time timestamp in GMT (seconds since epoch),
2388 * returns an array that represents the Gregorian date in user time
2390 * @package core
2391 * @category time
2392 * @param int $time Timestamp in GMT
2393 * @param float|int|string $timezone user timezone
2394 * @return array An array that represents the date in user time
2396 function usergetdate($time, $timezone=99) {
2397 if ($time === null) {
2398 // PHP8 and PHP7 return different results when getdate(null) is called.
2399 // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
2400 // In the future versions of Moodle we may consider adding a strict typehint.
2401 debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER);
2402 $time = 0;
2405 date_default_timezone_set(core_date::get_user_timezone($timezone));
2406 $result = getdate($time);
2407 core_date::set_default_server_timezone();
2409 return $result;
2413 * Given a GMT timestamp (seconds since epoch), offsets it by
2414 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2416 * NOTE: this function does not include DST properly,
2417 * you should use the PHP date stuff instead!
2419 * @package core
2420 * @category time
2421 * @param int $date Timestamp in GMT
2422 * @param float|int|string $timezone user timezone
2423 * @return int
2425 function usertime($date, $timezone=99) {
2426 $userdate = new DateTime('@' . $date);
2427 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2428 $dst = dst_offset_on($date, $timezone);
2430 return $date - $userdate->getOffset() + $dst;
2434 * Get a formatted string representation of an interval between two unix timestamps.
2436 * E.g.
2437 * $intervalstring = get_time_interval_string(12345600, 12345660);
2438 * Will produce the string:
2439 * '0d 0h 1m'
2441 * @param int $time1 unix timestamp
2442 * @param int $time2 unix timestamp
2443 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2444 * @param bool $dropzeroes If format is not provided and this is set to true, do not include zero time units.
2445 * e.g. a duration of 3 days and 2 hours will be displayed as '3d 2h' instead of '3d 2h 0s'
2446 * @param bool $fullformat If format is not provided and this is set to true, display time units in full format.
2447 * e.g. instead of showing "3d", "3 days" will be returned.
2448 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2450 function get_time_interval_string(int $time1, int $time2, string $format = '',
2451 bool $dropzeroes = false, bool $fullformat = false): string {
2452 $dtdate = new DateTime();
2453 $dtdate->setTimeStamp($time1);
2454 $dtdate2 = new DateTime();
2455 $dtdate2->setTimeStamp($time2);
2456 $interval = $dtdate2->diff($dtdate);
2458 if (empty(trim($format))) {
2459 // Default to this key.
2460 $formatkey = 'dateintervaldayhrmin';
2462 if ($dropzeroes) {
2463 $units = [
2464 'y' => 'yr',
2465 'm' => 'mo',
2466 'd' => 'day',
2467 'h' => 'hr',
2468 'i' => 'min',
2469 's' => 'sec',
2471 $formatunits = [];
2472 foreach ($units as $key => $unit) {
2473 if (empty($interval->$key)) {
2474 continue;
2476 $formatunits[] = $unit;
2478 if (!empty($formatunits)) {
2479 $formatkey = 'dateinterval' . implode("", $formatunits);
2483 if ($fullformat) {
2484 $formatkey .= 'full';
2486 $format = get_string($formatkey, 'langconfig');
2488 return $interval->format($format);
2492 * Given a time, return the GMT timestamp of the most recent midnight
2493 * for the current user.
2495 * @package core
2496 * @category time
2497 * @param int $date Timestamp in GMT
2498 * @param float|int|string $timezone user timezone
2499 * @return int Returns a GMT timestamp
2501 function usergetmidnight($date, $timezone=99) {
2503 $userdate = usergetdate($date, $timezone);
2505 // Time of midnight of this user's day, in GMT.
2506 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2511 * Returns a string that prints the user's timezone
2513 * @package core
2514 * @category time
2515 * @param float|int|string $timezone user timezone
2516 * @return string
2518 function usertimezone($timezone=99) {
2519 $tz = core_date::get_user_timezone($timezone);
2520 return core_date::get_localised_timezone($tz);
2524 * Returns a float or a string which denotes the user's timezone
2525 * 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)
2526 * means that for this timezone there are also DST rules to be taken into account
2527 * Checks various settings and picks the most dominant of those which have a value
2529 * @package core
2530 * @category time
2531 * @param float|int|string $tz timezone to calculate GMT time offset before
2532 * calculating user timezone, 99 is default user timezone
2533 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2534 * @return float|string
2536 function get_user_timezone($tz = 99) {
2537 global $USER, $CFG;
2539 $timezones = array(
2540 $tz,
2541 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2542 isset($USER->timezone) ? $USER->timezone : 99,
2543 isset($CFG->timezone) ? $CFG->timezone : 99,
2546 $tz = 99;
2548 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2549 foreach ($timezones as $nextvalue) {
2550 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2551 $tz = $nextvalue;
2554 return is_numeric($tz) ? (float) $tz : $tz;
2558 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2559 * - Note: Daylight saving only works for string timezones and not for float.
2561 * @package core
2562 * @category time
2563 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2564 * @param int|float|string $strtimezone user timezone
2565 * @return int
2567 function dst_offset_on($time, $strtimezone = null) {
2568 $tz = core_date::get_user_timezone($strtimezone);
2569 $date = new DateTime('@' . $time);
2570 $date->setTimezone(new DateTimeZone($tz));
2571 if ($date->format('I') == '1') {
2572 if ($tz === 'Australia/Lord_Howe') {
2573 return 1800;
2575 return 3600;
2577 return 0;
2581 * Calculates when the day appears in specific month
2583 * @package core
2584 * @category time
2585 * @param int $startday starting day of the month
2586 * @param int $weekday The day when week starts (normally taken from user preferences)
2587 * @param int $month The month whose day is sought
2588 * @param int $year The year of the month whose day is sought
2589 * @return int
2591 function find_day_in_month($startday, $weekday, $month, $year) {
2592 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2594 $daysinmonth = days_in_month($month, $year);
2595 $daysinweek = count($calendartype->get_weekdays());
2597 if ($weekday == -1) {
2598 // Don't care about weekday, so return:
2599 // abs($startday) if $startday != -1
2600 // $daysinmonth otherwise.
2601 return ($startday == -1) ? $daysinmonth : abs($startday);
2604 // From now on we 're looking for a specific weekday.
2605 // Give "end of month" its actual value, since we know it.
2606 if ($startday == -1) {
2607 $startday = -1 * $daysinmonth;
2610 // Starting from day $startday, the sign is the direction.
2611 if ($startday < 1) {
2612 $startday = abs($startday);
2613 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2615 // This is the last such weekday of the month.
2616 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2617 if ($lastinmonth > $daysinmonth) {
2618 $lastinmonth -= $daysinweek;
2621 // Find the first such weekday <= $startday.
2622 while ($lastinmonth > $startday) {
2623 $lastinmonth -= $daysinweek;
2626 return $lastinmonth;
2627 } else {
2628 $indexweekday = dayofweek($startday, $month, $year);
2630 $diff = $weekday - $indexweekday;
2631 if ($diff < 0) {
2632 $diff += $daysinweek;
2635 // This is the first such weekday of the month equal to or after $startday.
2636 $firstfromindex = $startday + $diff;
2638 return $firstfromindex;
2643 * Calculate the number of days in a given month
2645 * @package core
2646 * @category time
2647 * @param int $month The month whose day count is sought
2648 * @param int $year The year of the month whose day count is sought
2649 * @return int
2651 function days_in_month($month, $year) {
2652 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2653 return $calendartype->get_num_days_in_month($year, $month);
2657 * Calculate the position in the week of a specific calendar day
2659 * @package core
2660 * @category time
2661 * @param int $day The day of the date whose position in the week is sought
2662 * @param int $month The month of the date whose position in the week is sought
2663 * @param int $year The year of the date whose position in the week is sought
2664 * @return int
2666 function dayofweek($day, $month, $year) {
2667 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2668 return $calendartype->get_weekday($year, $month, $day);
2671 // USER AUTHENTICATION AND LOGIN.
2674 * Returns full login url.
2676 * Any form submissions for authentication to this URL must include username,
2677 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2679 * @return string login url
2681 function get_login_url() {
2682 global $CFG;
2684 return "$CFG->wwwroot/login/index.php";
2688 * This function checks that the current user is logged in and has the
2689 * required privileges
2691 * This function checks that the current user is logged in, and optionally
2692 * whether they are allowed to be in a particular course and view a particular
2693 * course module.
2694 * If they are not logged in, then it redirects them to the site login unless
2695 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2696 * case they are automatically logged in as guests.
2697 * If $courseid is given and the user is not enrolled in that course then the
2698 * user is redirected to the course enrolment page.
2699 * If $cm is given and the course module is hidden and the user is not a teacher
2700 * in the course then the user is redirected to the course home page.
2702 * When $cm parameter specified, this function sets page layout to 'module'.
2703 * You need to change it manually later if some other layout needed.
2705 * @package core_access
2706 * @category access
2708 * @param mixed $courseorid id of the course or course object
2709 * @param bool $autologinguest default true
2710 * @param object $cm course module object
2711 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2712 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2713 * in order to keep redirects working properly. MDL-14495
2714 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2715 * @return mixed Void, exit, and die depending on path
2716 * @throws coding_exception
2717 * @throws require_login_exception
2718 * @throws moodle_exception
2720 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2721 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2723 // Must not redirect when byteserving already started.
2724 if (!empty($_SERVER['HTTP_RANGE'])) {
2725 $preventredirect = true;
2728 if (AJAX_SCRIPT) {
2729 // We cannot redirect for AJAX scripts either.
2730 $preventredirect = true;
2733 // Setup global $COURSE, themes, language and locale.
2734 if (!empty($courseorid)) {
2735 if (is_object($courseorid)) {
2736 $course = $courseorid;
2737 } else if ($courseorid == SITEID) {
2738 $course = clone($SITE);
2739 } else {
2740 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2742 if ($cm) {
2743 if ($cm->course != $course->id) {
2744 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2746 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2747 if (!($cm instanceof cm_info)) {
2748 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2749 // db queries so this is not really a performance concern, however it is obviously
2750 // better if you use get_fast_modinfo to get the cm before calling this.
2751 $modinfo = get_fast_modinfo($course);
2752 $cm = $modinfo->get_cm($cm->id);
2755 } else {
2756 // Do not touch global $COURSE via $PAGE->set_course(),
2757 // the reasons is we need to be able to call require_login() at any time!!
2758 $course = $SITE;
2759 if ($cm) {
2760 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2764 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2765 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2766 // risk leading the user back to the AJAX request URL.
2767 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2768 $setwantsurltome = false;
2771 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2772 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2773 if ($preventredirect) {
2774 throw new require_login_session_timeout_exception();
2775 } else {
2776 if ($setwantsurltome) {
2777 $SESSION->wantsurl = qualified_me();
2779 redirect(get_login_url());
2783 // If the user is not even logged in yet then make sure they are.
2784 if (!isloggedin()) {
2785 if ($autologinguest && !empty($CFG->autologinguests)) {
2786 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2787 // Misconfigured site guest, just redirect to login page.
2788 redirect(get_login_url());
2789 exit; // Never reached.
2791 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2792 complete_user_login($guest);
2793 $USER->autologinguest = true;
2794 $SESSION->lang = $lang;
2795 } else {
2796 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2797 if ($preventredirect) {
2798 throw new require_login_exception('You are not logged in');
2801 if ($setwantsurltome) {
2802 $SESSION->wantsurl = qualified_me();
2805 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2806 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
2807 foreach($authsequence as $authname) {
2808 $authplugin = get_auth_plugin($authname);
2809 $authplugin->pre_loginpage_hook();
2810 if (isloggedin()) {
2811 if ($cm) {
2812 $modinfo = get_fast_modinfo($course);
2813 $cm = $modinfo->get_cm($cm->id);
2815 set_access_log_user();
2816 break;
2820 // If we're still not logged in then go to the login page
2821 if (!isloggedin()) {
2822 redirect(get_login_url());
2823 exit; // Never reached.
2828 // Loginas as redirection if needed.
2829 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2830 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2831 if ($USER->loginascontext->instanceid != $course->id) {
2832 throw new \moodle_exception('loginasonecourse', '',
2833 $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2838 // Check whether the user should be changing password (but only if it is REALLY them).
2839 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2840 $userauth = get_auth_plugin($USER->auth);
2841 if ($userauth->can_change_password() and !$preventredirect) {
2842 if ($setwantsurltome) {
2843 $SESSION->wantsurl = qualified_me();
2845 if ($changeurl = $userauth->change_password_url()) {
2846 // Use plugin custom url.
2847 redirect($changeurl);
2848 } else {
2849 // Use moodle internal method.
2850 redirect($CFG->wwwroot .'/login/change_password.php');
2852 } else if ($userauth->can_change_password()) {
2853 throw new moodle_exception('forcepasswordchangenotice');
2854 } else {
2855 throw new moodle_exception('nopasswordchangeforced', 'auth');
2859 // Check that the user account is properly set up. If we can't redirect to
2860 // edit their profile and this is not a WS request, perform just the lax check.
2861 // It will allow them to use filepicker on the profile edit page.
2863 if ($preventredirect && !WS_SERVER) {
2864 $usernotfullysetup = user_not_fully_set_up($USER, false);
2865 } else {
2866 $usernotfullysetup = user_not_fully_set_up($USER, true);
2869 if ($usernotfullysetup) {
2870 if ($preventredirect) {
2871 throw new moodle_exception('usernotfullysetup');
2873 if ($setwantsurltome) {
2874 $SESSION->wantsurl = qualified_me();
2876 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2879 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2880 sesskey();
2882 if (\core\session\manager::is_loggedinas()) {
2883 // During a "logged in as" session we should force all content to be cleaned because the
2884 // logged in user will be viewing potentially malicious user generated content.
2885 // See MDL-63786 for more details.
2886 $CFG->forceclean = true;
2889 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2891 // Do not bother admins with any formalities, except for activities pending deletion.
2892 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2893 // Set the global $COURSE.
2894 if ($cm) {
2895 $PAGE->set_cm($cm, $course);
2896 $PAGE->set_pagelayout('incourse');
2897 } else if (!empty($courseorid)) {
2898 $PAGE->set_course($course);
2900 // Set accesstime or the user will appear offline which messes up messaging.
2901 // Do not update access time for webservice or ajax requests.
2902 if (!WS_SERVER && !AJAX_SCRIPT) {
2903 user_accesstime_log($course->id);
2906 foreach ($afterlogins as $plugintype => $plugins) {
2907 foreach ($plugins as $pluginfunction) {
2908 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2911 return;
2914 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2915 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2916 if (!defined('NO_SITEPOLICY_CHECK')) {
2917 define('NO_SITEPOLICY_CHECK', false);
2920 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2921 // Do not test if the script explicitly asked for skipping the site policies check.
2922 // Or if the user auth type is webservice.
2923 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK && $USER->auth !== 'webservice') {
2924 $manager = new \core_privacy\local\sitepolicy\manager();
2925 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2926 if ($preventredirect) {
2927 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2929 if ($setwantsurltome) {
2930 $SESSION->wantsurl = qualified_me();
2932 redirect($policyurl);
2936 // Fetch the system context, the course context, and prefetch its child contexts.
2937 $sysctx = context_system::instance();
2938 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2939 if ($cm) {
2940 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2941 } else {
2942 $cmcontext = null;
2945 // If the site is currently under maintenance, then print a message.
2946 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2947 if ($preventredirect) {
2948 throw new require_login_exception('Maintenance in progress');
2950 $PAGE->set_context(null);
2951 print_maintenance_message();
2954 // Make sure the course itself is not hidden.
2955 if ($course->id == SITEID) {
2956 // Frontpage can not be hidden.
2957 } else {
2958 if (is_role_switched($course->id)) {
2959 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2960 } else {
2961 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2962 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2963 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2964 if ($preventredirect) {
2965 throw new require_login_exception('Course is hidden');
2967 $PAGE->set_context(null);
2968 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2969 // the navigation will mess up when trying to find it.
2970 navigation_node::override_active_url(new moodle_url('/'));
2971 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2976 // Is the user enrolled?
2977 if ($course->id == SITEID) {
2978 // Everybody is enrolled on the frontpage.
2979 } else {
2980 if (\core\session\manager::is_loggedinas()) {
2981 // Make sure the REAL person can access this course first.
2982 $realuser = \core\session\manager::get_realuser();
2983 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2984 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2985 if ($preventredirect) {
2986 throw new require_login_exception('Invalid course login-as access');
2988 $PAGE->set_context(null);
2989 echo $OUTPUT->header();
2990 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2994 $access = false;
2996 if (is_role_switched($course->id)) {
2997 // Ok, user had to be inside this course before the switch.
2998 $access = true;
3000 } else if (is_viewing($coursecontext, $USER)) {
3001 // Ok, no need to mess with enrol.
3002 $access = true;
3004 } else {
3005 if (isset($USER->enrol['enrolled'][$course->id])) {
3006 if ($USER->enrol['enrolled'][$course->id] > time()) {
3007 $access = true;
3008 if (isset($USER->enrol['tempguest'][$course->id])) {
3009 unset($USER->enrol['tempguest'][$course->id]);
3010 remove_temp_course_roles($coursecontext);
3012 } else {
3013 // Expired.
3014 unset($USER->enrol['enrolled'][$course->id]);
3017 if (isset($USER->enrol['tempguest'][$course->id])) {
3018 if ($USER->enrol['tempguest'][$course->id] == 0) {
3019 $access = true;
3020 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3021 $access = true;
3022 } else {
3023 // Expired.
3024 unset($USER->enrol['tempguest'][$course->id]);
3025 remove_temp_course_roles($coursecontext);
3029 if (!$access) {
3030 // Cache not ok.
3031 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3032 if ($until !== false) {
3033 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3034 if ($until == 0) {
3035 $until = ENROL_MAX_TIMESTAMP;
3037 $USER->enrol['enrolled'][$course->id] = $until;
3038 $access = true;
3040 } else if (core_course_category::can_view_course_info($course)) {
3041 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3042 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3043 $enrols = enrol_get_plugins(true);
3044 // First ask all enabled enrol instances in course if they want to auto enrol user.
3045 foreach ($instances as $instance) {
3046 if (!isset($enrols[$instance->enrol])) {
3047 continue;
3049 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3050 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3051 if ($until !== false) {
3052 if ($until == 0) {
3053 $until = ENROL_MAX_TIMESTAMP;
3055 $USER->enrol['enrolled'][$course->id] = $until;
3056 $access = true;
3057 break;
3060 // If not enrolled yet try to gain temporary guest access.
3061 if (!$access) {
3062 foreach ($instances as $instance) {
3063 if (!isset($enrols[$instance->enrol])) {
3064 continue;
3066 // Get a duration for the guest access, a timestamp in the future or false.
3067 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3068 if ($until !== false and $until > time()) {
3069 $USER->enrol['tempguest'][$course->id] = $until;
3070 $access = true;
3071 break;
3075 } else {
3076 // User is not enrolled and is not allowed to browse courses here.
3077 if ($preventredirect) {
3078 throw new require_login_exception('Course is not available');
3080 $PAGE->set_context(null);
3081 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3082 // the navigation will mess up when trying to find it.
3083 navigation_node::override_active_url(new moodle_url('/'));
3084 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3089 if (!$access) {
3090 if ($preventredirect) {
3091 throw new require_login_exception('Not enrolled');
3093 if ($setwantsurltome) {
3094 $SESSION->wantsurl = qualified_me();
3096 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3100 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3101 if ($cm && $cm->deletioninprogress) {
3102 if ($preventredirect) {
3103 throw new moodle_exception('activityisscheduledfordeletion');
3105 require_once($CFG->dirroot . '/course/lib.php');
3106 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3109 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3110 if ($cm && !$cm->uservisible) {
3111 if ($preventredirect) {
3112 throw new require_login_exception('Activity is hidden');
3114 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3115 $PAGE->set_course($course);
3116 $renderer = $PAGE->get_renderer('course');
3117 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3118 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3121 // Set the global $COURSE.
3122 if ($cm) {
3123 $PAGE->set_cm($cm, $course);
3124 $PAGE->set_pagelayout('incourse');
3125 } else if (!empty($courseorid)) {
3126 $PAGE->set_course($course);
3129 foreach ($afterlogins as $plugintype => $plugins) {
3130 foreach ($plugins as $pluginfunction) {
3131 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3135 // Finally access granted, update lastaccess times.
3136 // Do not update access time for webservice or ajax requests.
3137 if (!WS_SERVER && !AJAX_SCRIPT) {
3138 user_accesstime_log($course->id);
3143 * A convenience function for where we must be logged in as admin
3144 * @return void
3146 function require_admin() {
3147 require_login(null, false);
3148 require_capability('moodle/site:config', context_system::instance());
3152 * This function just makes sure a user is logged out.
3154 * @package core_access
3155 * @category access
3157 function require_logout() {
3158 global $USER, $DB;
3160 if (!isloggedin()) {
3161 // This should not happen often, no need for hooks or events here.
3162 \core\session\manager::terminate_current();
3163 return;
3166 // Execute hooks before action.
3167 $authplugins = array();
3168 $authsequence = get_enabled_auth_plugins();
3169 foreach ($authsequence as $authname) {
3170 $authplugins[$authname] = get_auth_plugin($authname);
3171 $authplugins[$authname]->prelogout_hook();
3174 // Store info that gets removed during logout.
3175 $sid = session_id();
3176 $event = \core\event\user_loggedout::create(
3177 array(
3178 'userid' => $USER->id,
3179 'objectid' => $USER->id,
3180 'other' => array('sessionid' => $sid),
3183 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3184 $event->add_record_snapshot('sessions', $session);
3187 // Clone of $USER object to be used by auth plugins.
3188 $user = fullclone($USER);
3190 // Delete session record and drop $_SESSION content.
3191 \core\session\manager::terminate_current();
3193 // Trigger event AFTER action.
3194 $event->trigger();
3196 // Hook to execute auth plugins redirection after event trigger.
3197 foreach ($authplugins as $authplugin) {
3198 $authplugin->postlogout_hook($user);
3203 * Weaker version of require_login()
3205 * This is a weaker version of {@link require_login()} which only requires login
3206 * when called from within a course rather than the site page, unless
3207 * the forcelogin option is turned on.
3208 * @see require_login()
3210 * @package core_access
3211 * @category access
3213 * @param mixed $courseorid The course object or id in question
3214 * @param bool $autologinguest Allow autologin guests if that is wanted
3215 * @param object $cm Course activity module if known
3216 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3217 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3218 * in order to keep redirects working properly. MDL-14495
3219 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3220 * @return void
3221 * @throws coding_exception
3223 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3224 global $CFG, $PAGE, $SITE;
3225 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3226 or (!is_object($courseorid) and $courseorid == SITEID));
3227 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3228 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3229 // db queries so this is not really a performance concern, however it is obviously
3230 // better if you use get_fast_modinfo to get the cm before calling this.
3231 if (is_object($courseorid)) {
3232 $course = $courseorid;
3233 } else {
3234 $course = clone($SITE);
3236 $modinfo = get_fast_modinfo($course);
3237 $cm = $modinfo->get_cm($cm->id);
3239 if (!empty($CFG->forcelogin)) {
3240 // Login required for both SITE and courses.
3241 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3243 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3244 // Always login for hidden activities.
3245 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3247 } else if (isloggedin() && !isguestuser()) {
3248 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3249 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3251 } else if ($issite) {
3252 // Login for SITE not required.
3253 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3254 if (!empty($courseorid)) {
3255 if (is_object($courseorid)) {
3256 $course = $courseorid;
3257 } else {
3258 $course = clone $SITE;
3260 if ($cm) {
3261 if ($cm->course != $course->id) {
3262 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3264 $PAGE->set_cm($cm, $course);
3265 $PAGE->set_pagelayout('incourse');
3266 } else {
3267 $PAGE->set_course($course);
3269 } else {
3270 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3271 $PAGE->set_course($PAGE->course);
3273 // Do not update access time for webservice or ajax requests.
3274 if (!WS_SERVER && !AJAX_SCRIPT) {
3275 user_accesstime_log(SITEID);
3277 return;
3279 } else {
3280 // Course login always required.
3281 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3286 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3288 * @param string $keyvalue the key value
3289 * @param string $script unique script identifier
3290 * @param int $instance instance id
3291 * @return stdClass the key entry in the user_private_key table
3292 * @since Moodle 3.2
3293 * @throws moodle_exception
3295 function validate_user_key($keyvalue, $script, $instance) {
3296 global $DB;
3298 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3299 throw new \moodle_exception('invalidkey');
3302 if (!empty($key->validuntil) and $key->validuntil < time()) {
3303 throw new \moodle_exception('expiredkey');
3306 if ($key->iprestriction) {
3307 $remoteaddr = getremoteaddr(null);
3308 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3309 throw new \moodle_exception('ipmismatch');
3312 return $key;
3316 * Require key login. Function terminates with error if key not found or incorrect.
3318 * @uses NO_MOODLE_COOKIES
3319 * @uses PARAM_ALPHANUM
3320 * @param string $script unique script identifier
3321 * @param int $instance optional instance id
3322 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3323 * @return int Instance ID
3325 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3326 global $DB;
3328 if (!NO_MOODLE_COOKIES) {
3329 throw new \moodle_exception('sessioncookiesdisable');
3332 // Extra safety.
3333 \core\session\manager::write_close();
3335 if (null === $keyvalue) {
3336 $keyvalue = required_param('key', PARAM_ALPHANUM);
3339 $key = validate_user_key($keyvalue, $script, $instance);
3341 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3342 throw new \moodle_exception('invaliduserid');
3345 core_user::require_active_user($user, true, true);
3347 // Emulate normal session.
3348 enrol_check_plugins($user, false);
3349 \core\session\manager::set_user($user);
3351 // Note we are not using normal login.
3352 if (!defined('USER_KEY_LOGIN')) {
3353 define('USER_KEY_LOGIN', true);
3356 // Return instance id - it might be empty.
3357 return $key->instance;
3361 * Creates a new private user access key.
3363 * @param string $script unique target identifier
3364 * @param int $userid
3365 * @param int $instance optional instance id
3366 * @param string $iprestriction optional ip restricted access
3367 * @param int $validuntil key valid only until given data
3368 * @return string access key value
3370 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3371 global $DB;
3373 $key = new stdClass();
3374 $key->script = $script;
3375 $key->userid = $userid;
3376 $key->instance = $instance;
3377 $key->iprestriction = $iprestriction;
3378 $key->validuntil = $validuntil;
3379 $key->timecreated = time();
3381 // Something long and unique.
3382 $key->value = md5($userid.'_'.time().random_string(40));
3383 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3384 // Must be unique.
3385 $key->value = md5($userid.'_'.time().random_string(40));
3387 $DB->insert_record('user_private_key', $key);
3388 return $key->value;
3392 * Delete the user's new private user access keys for a particular script.
3394 * @param string $script unique target identifier
3395 * @param int $userid
3396 * @return void
3398 function delete_user_key($script, $userid) {
3399 global $DB;
3400 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3404 * Gets a private user access key (and creates one if one doesn't exist).
3406 * @param string $script unique target identifier
3407 * @param int $userid
3408 * @param int $instance optional instance id
3409 * @param string $iprestriction optional ip restricted access
3410 * @param int $validuntil key valid only until given date
3411 * @return string access key value
3413 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3414 global $DB;
3416 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3417 'instance' => $instance, 'iprestriction' => $iprestriction,
3418 'validuntil' => $validuntil))) {
3419 return $key->value;
3420 } else {
3421 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3427 * Modify the user table by setting the currently logged in user's last login to now.
3429 * @return bool Always returns true
3431 function update_user_login_times() {
3432 global $USER, $DB, $SESSION;
3434 if (isguestuser()) {
3435 // Do not update guest access times/ips for performance.
3436 return true;
3439 if (defined('USER_KEY_LOGIN') && USER_KEY_LOGIN === true) {
3440 // Do not update user login time when using user key login.
3441 return true;
3444 $now = time();
3446 $user = new stdClass();
3447 $user->id = $USER->id;
3449 // Make sure all users that logged in have some firstaccess.
3450 if ($USER->firstaccess == 0) {
3451 $USER->firstaccess = $user->firstaccess = $now;
3454 // Store the previous current as lastlogin.
3455 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3457 $USER->currentlogin = $user->currentlogin = $now;
3459 // Function user_accesstime_log() may not update immediately, better do it here.
3460 $USER->lastaccess = $user->lastaccess = $now;
3461 $SESSION->userpreviousip = $USER->lastip;
3462 $USER->lastip = $user->lastip = getremoteaddr();
3464 // Note: do not call user_update_user() here because this is part of the login process,
3465 // the login event means that these fields were updated.
3466 $DB->update_record('user', $user);
3467 return true;
3471 * Determines if a user has completed setting up their account.
3473 * The lax mode (with $strict = false) has been introduced for special cases
3474 * only where we want to skip certain checks intentionally. This is valid in
3475 * certain mnet or ajax scenarios when the user cannot / should not be
3476 * redirected to edit their profile. In most cases, you should perform the
3477 * strict check.
3479 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3480 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3481 * @return bool
3483 function user_not_fully_set_up($user, $strict = true) {
3484 global $CFG, $SESSION, $USER;
3485 require_once($CFG->dirroot.'/user/profile/lib.php');
3487 // If the user is setup then store this in the session to avoid re-checking.
3488 // Some edge cases are when the users email starts to bounce or the
3489 // configuration for custom fields has changed while they are logged in so
3490 // we re-check this fully every hour for the rare cases it has changed.
3491 if (isset($USER->id) && isset($user->id) && $USER->id === $user->id &&
3492 isset($SESSION->fullysetupstrict) && (time() - $SESSION->fullysetupstrict) < HOURSECS) {
3493 return false;
3496 if (isguestuser($user)) {
3497 return false;
3500 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3501 return true;
3504 if ($strict) {
3505 if (empty($user->id)) {
3506 // Strict mode can be used with existing accounts only.
3507 return true;
3509 if (!profile_has_required_custom_fields_set($user->id)) {
3510 return true;
3512 if (isset($USER->id) && isset($user->id) && $USER->id === $user->id) {
3513 $SESSION->fullysetupstrict = time();
3517 return false;
3521 * Check whether the user has exceeded the bounce threshold
3523 * @param stdClass $user A {@link $USER} object
3524 * @return bool true => User has exceeded bounce threshold
3526 function over_bounce_threshold($user) {
3527 global $CFG, $DB;
3529 if (empty($CFG->handlebounces)) {
3530 return false;
3533 if (empty($user->id)) {
3534 // No real (DB) user, nothing to do here.
3535 return false;
3538 // Set sensible defaults.
3539 if (empty($CFG->minbounces)) {
3540 $CFG->minbounces = 10;
3542 if (empty($CFG->bounceratio)) {
3543 $CFG->bounceratio = .20;
3545 $bouncecount = 0;
3546 $sendcount = 0;
3547 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3548 $bouncecount = $bounce->value;
3550 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3551 $sendcount = $send->value;
3553 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3557 * Used to increment or reset email sent count
3559 * @param stdClass $user object containing an id
3560 * @param bool $reset will reset the count to 0
3561 * @return void
3563 function set_send_count($user, $reset=false) {
3564 global $DB;
3566 if (empty($user->id)) {
3567 // No real (DB) user, nothing to do here.
3568 return;
3571 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3572 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3573 $DB->update_record('user_preferences', $pref);
3574 } else if (!empty($reset)) {
3575 // If it's not there and we're resetting, don't bother. Make a new one.
3576 $pref = new stdClass();
3577 $pref->name = 'email_send_count';
3578 $pref->value = 1;
3579 $pref->userid = $user->id;
3580 $DB->insert_record('user_preferences', $pref, false);
3585 * Increment or reset user's email bounce count
3587 * @param stdClass $user object containing an id
3588 * @param bool $reset will reset the count to 0
3590 function set_bounce_count($user, $reset=false) {
3591 global $DB;
3593 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3594 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3595 $DB->update_record('user_preferences', $pref);
3596 } else if (!empty($reset)) {
3597 // If it's not there and we're resetting, don't bother. Make a new one.
3598 $pref = new stdClass();
3599 $pref->name = 'email_bounce_count';
3600 $pref->value = 1;
3601 $pref->userid = $user->id;
3602 $DB->insert_record('user_preferences', $pref, false);
3607 * Determines if the logged in user is currently moving an activity
3609 * @param int $courseid The id of the course being tested
3610 * @return bool
3612 function ismoving($courseid) {
3613 global $USER;
3615 if (!empty($USER->activitycopy)) {
3616 return ($USER->activitycopycourse == $courseid);
3618 return false;
3622 * Returns a persons full name
3624 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3625 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3626 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3627 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3629 * @param stdClass $user A {@link $USER} object to get full name of.
3630 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3631 * @return string
3633 function fullname($user, $override=false) {
3634 // Note: We do not intend to deprecate this function any time soon as it is too widely used at this time.
3635 // Uses of it should be updated to use the new API and pass updated arguments.
3637 // Return an empty string if there is no user.
3638 if (empty($user)) {
3639 return '';
3642 $options = ['override' => $override];
3643 return core_user::get_fullname($user, null, $options);
3647 * Reduces lines of duplicated code for getting user name fields.
3649 * See also {@link user_picture::unalias()}
3651 * @param object $addtoobject Object to add user name fields to.
3652 * @param object $secondobject Object that contains user name field information.
3653 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3654 * @param array $additionalfields Additional fields to be matched with data in the second object.
3655 * The key can be set to the user table field name.
3656 * @return object User name fields.
3658 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3659 $fields = [];
3660 foreach (\core_user\fields::get_name_fields() as $field) {
3661 $fields[$field] = $prefix . $field;
3663 if ($additionalfields) {
3664 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3665 // the key is a number and then sets the key to the array value.
3666 foreach ($additionalfields as $key => $value) {
3667 if (is_numeric($key)) {
3668 $additionalfields[$value] = $prefix . $value;
3669 unset($additionalfields[$key]);
3670 } else {
3671 $additionalfields[$key] = $prefix . $value;
3674 $fields = array_merge($fields, $additionalfields);
3676 foreach ($fields as $key => $field) {
3677 // Important that we have all of the user name fields present in the object that we are sending back.
3678 $addtoobject->$key = '';
3679 if (isset($secondobject->$field)) {
3680 $addtoobject->$key = $secondobject->$field;
3683 return $addtoobject;
3687 * Returns an array of values in order of occurance in a provided string.
3688 * The key in the result is the character postion in the string.
3690 * @param array $values Values to be found in the string format
3691 * @param string $stringformat The string which may contain values being searched for.
3692 * @return array An array of values in order according to placement in the string format.
3694 function order_in_string($values, $stringformat) {
3695 $valuearray = array();
3696 foreach ($values as $value) {
3697 $pattern = "/$value\b/";
3698 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3699 if (preg_match($pattern, $stringformat)) {
3700 $replacement = "thing";
3701 // Replace the value with something more unique to ensure we get the right position when using strpos().
3702 $newformat = preg_replace($pattern, $replacement, $stringformat);
3703 $position = strpos($newformat, $replacement);
3704 $valuearray[$position] = $value;
3707 ksort($valuearray);
3708 return $valuearray;
3712 * Returns whether a given authentication plugin exists.
3714 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3715 * @return boolean Whether the plugin is available.
3717 function exists_auth_plugin($auth) {
3718 global $CFG;
3720 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3721 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3723 return false;
3727 * Checks if a given plugin is in the list of enabled authentication plugins.
3729 * @param string $auth Authentication plugin.
3730 * @return boolean Whether the plugin is enabled.
3732 function is_enabled_auth($auth) {
3733 if (empty($auth)) {
3734 return false;
3737 $enabled = get_enabled_auth_plugins();
3739 return in_array($auth, $enabled);
3743 * Returns an authentication plugin instance.
3745 * @param string $auth name of authentication plugin
3746 * @return auth_plugin_base An instance of the required authentication plugin.
3748 function get_auth_plugin($auth) {
3749 global $CFG;
3751 // Check the plugin exists first.
3752 if (! exists_auth_plugin($auth)) {
3753 throw new \moodle_exception('authpluginnotfound', 'debug', '', $auth);
3756 // Return auth plugin instance.
3757 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3758 $class = "auth_plugin_$auth";
3759 return new $class;
3763 * Returns array of active auth plugins.
3765 * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
3766 * @return array
3768 function get_enabled_auth_plugins($fix=false) {
3769 global $CFG;
3771 $default = array('manual', 'nologin');
3773 if (empty($CFG->auth)) {
3774 $auths = array();
3775 } else {
3776 $auths = explode(',', $CFG->auth);
3779 $auths = array_unique($auths);
3780 $oldauthconfig = implode(',', $auths);
3781 foreach ($auths as $k => $authname) {
3782 if (in_array($authname, $default)) {
3783 // The manual and nologin plugin never need to be stored.
3784 unset($auths[$k]);
3785 } else if (!exists_auth_plugin($authname)) {
3786 debugging(get_string('authpluginnotfound', 'debug', $authname));
3787 unset($auths[$k]);
3791 // Ideally only explicit interaction from a human admin should trigger a
3792 // change in auth config, see MDL-70424 for details.
3793 if ($fix) {
3794 $newconfig = implode(',', $auths);
3795 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3796 add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
3797 set_config('auth', $newconfig);
3801 return (array_merge($default, $auths));
3805 * Returns true if an internal authentication method is being used.
3806 * if method not specified then, global default is assumed
3808 * @param string $auth Form of authentication required
3809 * @return bool
3811 function is_internal_auth($auth) {
3812 // Throws error if bad $auth.
3813 $authplugin = get_auth_plugin($auth);
3814 return $authplugin->is_internal();
3818 * Returns true if the user is a 'restored' one.
3820 * Used in the login process to inform the user and allow him/her to reset the password
3822 * @param string $username username to be checked
3823 * @return bool
3825 function is_restored_user($username) {
3826 global $CFG, $DB;
3828 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3832 * Returns an array of user fields
3834 * @return array User field/column names
3836 function get_user_fieldnames() {
3837 global $DB;
3839 $fieldarray = $DB->get_columns('user');
3840 unset($fieldarray['id']);
3841 $fieldarray = array_keys($fieldarray);
3843 return $fieldarray;
3847 * Returns the string of the language for the new user.
3849 * @return string language for the new user
3851 function get_newuser_language() {
3852 global $CFG, $SESSION;
3853 return (!empty($CFG->autolangusercreation) && !empty($SESSION->lang)) ? $SESSION->lang : $CFG->lang;
3857 * Creates a bare-bones user record
3859 * @todo Outline auth types and provide code example
3861 * @param string $username New user's username to add to record
3862 * @param string $password New user's password to add to record
3863 * @param string $auth Form of authentication required
3864 * @return stdClass A complete user object
3866 function create_user_record($username, $password, $auth = 'manual') {
3867 global $CFG, $DB, $SESSION;
3868 require_once($CFG->dirroot.'/user/profile/lib.php');
3869 require_once($CFG->dirroot.'/user/lib.php');
3871 // Just in case check text case.
3872 $username = trim(core_text::strtolower($username));
3874 $authplugin = get_auth_plugin($auth);
3875 $customfields = $authplugin->get_custom_user_profile_fields();
3876 $newuser = new stdClass();
3877 if ($newinfo = $authplugin->get_userinfo($username)) {
3878 $newinfo = truncate_userinfo($newinfo);
3879 foreach ($newinfo as $key => $value) {
3880 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3881 $newuser->$key = $value;
3886 if (!empty($newuser->email)) {
3887 if (email_is_not_allowed($newuser->email)) {
3888 unset($newuser->email);
3892 $newuser->auth = $auth;
3893 $newuser->username = $username;
3895 // Fix for MDL-8480
3896 // user CFG lang for user if $newuser->lang is empty
3897 // or $user->lang is not an installed language.
3898 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3899 $newuser->lang = get_newuser_language();
3901 $newuser->confirmed = 1;
3902 $newuser->lastip = getremoteaddr();
3903 $newuser->timecreated = time();
3904 $newuser->timemodified = $newuser->timecreated;
3905 $newuser->mnethostid = $CFG->mnet_localhost_id;
3907 $newuser->id = user_create_user($newuser, false, false);
3909 // Save user profile data.
3910 profile_save_data($newuser);
3912 $user = get_complete_user_data('id', $newuser->id);
3913 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3914 set_user_preference('auth_forcepasswordchange', 1, $user);
3916 // Set the password.
3917 update_internal_user_password($user, $password);
3919 // Trigger event.
3920 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3922 return $user;
3926 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3928 * @param string $username user's username to update the record
3929 * @return stdClass A complete user object
3931 function update_user_record($username) {
3932 global $DB, $CFG;
3933 // Just in case check text case.
3934 $username = trim(core_text::strtolower($username));
3936 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3937 return update_user_record_by_id($oldinfo->id);
3941 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3943 * @param int $id user id
3944 * @return stdClass A complete user object
3946 function update_user_record_by_id($id) {
3947 global $DB, $CFG;
3948 require_once($CFG->dirroot."/user/profile/lib.php");
3949 require_once($CFG->dirroot.'/user/lib.php');
3951 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3952 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3954 $newuser = array();
3955 $userauth = get_auth_plugin($oldinfo->auth);
3957 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3958 $newinfo = truncate_userinfo($newinfo);
3959 $customfields = $userauth->get_custom_user_profile_fields();
3961 foreach ($newinfo as $key => $value) {
3962 $iscustom = in_array($key, $customfields);
3963 if (!$iscustom) {
3964 $key = strtolower($key);
3966 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3967 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3968 // Unknown or must not be changed.
3969 continue;
3971 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
3972 continue;
3974 $confval = $userauth->config->{'field_updatelocal_' . $key};
3975 $lockval = $userauth->config->{'field_lock_' . $key};
3976 if ($confval === 'onlogin') {
3977 // MDL-4207 Don't overwrite modified user profile values with
3978 // empty LDAP values when 'unlocked if empty' is set. The purpose
3979 // of the setting 'unlocked if empty' is to allow the user to fill
3980 // in a value for the selected field _if LDAP is giving
3981 // nothing_ for this field. Thus it makes sense to let this value
3982 // stand in until LDAP is giving a value for this field.
3983 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3984 if ($iscustom || (in_array($key, $userauth->userfields) &&
3985 ((string)$oldinfo->$key !== (string)$value))) {
3986 $newuser[$key] = (string)$value;
3991 if ($newuser) {
3992 $newuser['id'] = $oldinfo->id;
3993 $newuser['timemodified'] = time();
3994 user_update_user((object) $newuser, false, false);
3996 // Save user profile data.
3997 profile_save_data((object) $newuser);
3999 // Trigger event.
4000 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4004 return get_complete_user_data('id', $oldinfo->id);
4008 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4010 * @param array $info Array of user properties to truncate if needed
4011 * @return array The now truncated information that was passed in
4013 function truncate_userinfo(array $info) {
4014 // Define the limits.
4015 $limit = array(
4016 'username' => 100,
4017 'idnumber' => 255,
4018 'firstname' => 100,
4019 'lastname' => 100,
4020 'email' => 100,
4021 'phone1' => 20,
4022 'phone2' => 20,
4023 'institution' => 255,
4024 'department' => 255,
4025 'address' => 255,
4026 'city' => 120,
4027 'country' => 2,
4030 // Apply where needed.
4031 foreach (array_keys($info) as $key) {
4032 if (!empty($limit[$key])) {
4033 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4037 return $info;
4041 * Marks user deleted in internal user database and notifies the auth plugin.
4042 * Also unenrols user from all roles and does other cleanup.
4044 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4046 * @param stdClass $user full user object before delete
4047 * @return boolean success
4048 * @throws coding_exception if invalid $user parameter detected
4050 function delete_user(stdClass $user) {
4051 global $CFG, $DB, $SESSION;
4052 require_once($CFG->libdir.'/grouplib.php');
4053 require_once($CFG->libdir.'/gradelib.php');
4054 require_once($CFG->dirroot.'/message/lib.php');
4055 require_once($CFG->dirroot.'/user/lib.php');
4057 // Make sure nobody sends bogus record type as parameter.
4058 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4059 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4062 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4063 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4064 debugging('Attempt to delete unknown user account.');
4065 return false;
4068 // There must be always exactly one guest record, originally the guest account was identified by username only,
4069 // now we use $CFG->siteguest for performance reasons.
4070 if ($user->username === 'guest' or isguestuser($user)) {
4071 debugging('Guest user account can not be deleted.');
4072 return false;
4075 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4076 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4077 if ($user->auth === 'manual' and is_siteadmin($user)) {
4078 debugging('Local administrator accounts can not be deleted.');
4079 return false;
4082 // Allow plugins to use this user object before we completely delete it.
4083 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4084 foreach ($pluginsfunction as $plugintype => $plugins) {
4085 foreach ($plugins as $pluginfunction) {
4086 $pluginfunction($user);
4091 // Keep user record before updating it, as we have to pass this to user_deleted event.
4092 $olduser = clone $user;
4094 // Keep a copy of user context, we need it for event.
4095 $usercontext = context_user::instance($user->id);
4097 // Remove user from communication rooms immediately.
4098 if (core_communication\api::is_available()) {
4099 foreach (enrol_get_users_courses($user->id) as $course) {
4100 $communication = \core_communication\processor::load_by_instance(
4101 'core_course',
4102 'coursecommunication',
4103 $course->id
4105 $communication->get_room_user_provider()->remove_members_from_room([$user->id]);
4106 $communication->delete_instance_user_mapping([$user->id]);
4110 // Delete all grades - backup is kept in grade_grades_history table.
4111 grade_user_delete($user->id);
4113 // TODO: remove from cohorts using standard API here.
4115 // Remove user tags.
4116 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4118 // Unconditionally unenrol from all courses.
4119 enrol_user_delete($user);
4121 // Unenrol from all roles in all contexts.
4122 // This might be slow but it is really needed - modules might do some extra cleanup!
4123 role_unassign_all(array('userid' => $user->id));
4125 // Notify the competency subsystem.
4126 \core_competency\api::hook_user_deleted($user->id);
4128 // Now do a brute force cleanup.
4130 // Delete all user events and subscription events.
4131 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
4133 // Now, delete all calendar subscription from the user.
4134 $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
4136 // Remove from all cohorts.
4137 $DB->delete_records('cohort_members', array('userid' => $user->id));
4139 // Remove from all groups.
4140 $DB->delete_records('groups_members', array('userid' => $user->id));
4142 // Brute force unenrol from all courses.
4143 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4145 // Purge user preferences.
4146 $DB->delete_records('user_preferences', array('userid' => $user->id));
4148 // Purge user extra profile info.
4149 $DB->delete_records('user_info_data', array('userid' => $user->id));
4151 // Purge log of previous password hashes.
4152 $DB->delete_records('user_password_history', array('userid' => $user->id));
4154 // Last course access not necessary either.
4155 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4156 // Remove all user tokens.
4157 $DB->delete_records('external_tokens', array('userid' => $user->id));
4159 // Unauthorise the user for all services.
4160 $DB->delete_records('external_services_users', array('userid' => $user->id));
4162 // Remove users private keys.
4163 $DB->delete_records('user_private_key', array('userid' => $user->id));
4165 // Remove users customised pages.
4166 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4168 // Remove user's oauth2 refresh tokens, if present.
4169 $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id));
4171 // Delete user from $SESSION->bulk_users.
4172 if (isset($SESSION->bulk_users[$user->id])) {
4173 unset($SESSION->bulk_users[$user->id]);
4176 // Force logout - may fail if file based sessions used, sorry.
4177 \core\session\manager::kill_user_sessions($user->id);
4179 // Generate username from email address, or a fake email.
4180 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4182 $deltime = time();
4183 $deltimelength = core_text::strlen((string) $deltime);
4185 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4186 $delname = clean_param($delemail, PARAM_USERNAME);
4187 $delname = core_text::substr($delname, 0, 100 - ($deltimelength + 1)) . ".{$deltime}";
4189 // Workaround for bulk deletes of users with the same email address.
4190 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4191 $delname++;
4194 // Mark internal user record as "deleted".
4195 $updateuser = new stdClass();
4196 $updateuser->id = $user->id;
4197 $updateuser->deleted = 1;
4198 $updateuser->username = $delname; // Remember it just in case.
4199 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4200 $updateuser->idnumber = ''; // Clear this field to free it up.
4201 $updateuser->picture = 0;
4202 $updateuser->timemodified = $deltime;
4204 // Don't trigger update event, as user is being deleted.
4205 user_update_user($updateuser, false, false);
4207 // Delete all content associated with the user context, but not the context itself.
4208 $usercontext->delete_content();
4210 // Delete any search data.
4211 \core_search\manager::context_deleted($usercontext);
4213 // Any plugin that needs to cleanup should register this event.
4214 // Trigger event.
4215 $event = \core\event\user_deleted::create(
4216 array(
4217 'objectid' => $user->id,
4218 'relateduserid' => $user->id,
4219 'context' => $usercontext,
4220 'other' => array(
4221 'username' => $user->username,
4222 'email' => $user->email,
4223 'idnumber' => $user->idnumber,
4224 'picture' => $user->picture,
4225 'mnethostid' => $user->mnethostid
4229 $event->add_record_snapshot('user', $olduser);
4230 $event->trigger();
4232 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4233 // should know about this updated property persisted to the user's table.
4234 $user->timemodified = $updateuser->timemodified;
4236 // Notify auth plugin - do not block the delete even when plugin fails.
4237 $authplugin = get_auth_plugin($user->auth);
4238 $authplugin->user_delete($user);
4240 return true;
4244 * Retrieve the guest user object.
4246 * @return stdClass A {@link $USER} object
4248 function guest_user() {
4249 global $CFG, $DB;
4251 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4252 $newuser->confirmed = 1;
4253 $newuser->lang = get_newuser_language();
4254 $newuser->lastip = getremoteaddr();
4257 return $newuser;
4261 * Authenticates a user against the chosen authentication mechanism
4263 * Given a username and password, this function looks them
4264 * up using the currently selected authentication mechanism,
4265 * and if the authentication is successful, it returns a
4266 * valid $user object from the 'user' table.
4268 * Uses auth_ functions from the currently active auth module
4270 * After authenticate_user_login() returns success, you will need to
4271 * log that the user has logged in, and call complete_user_login() to set
4272 * the session up.
4274 * Note: this function works only with non-mnet accounts!
4276 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4277 * @param string $password User's password
4278 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4279 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4280 * @param string|bool $logintoken If this is set to a string it is validated against the login token for the session.
4281 * @param string|bool $loginrecaptcha If this is set to a string it is validated against Google reCaptcha.
4282 * @return stdClass|false A {@link $USER} object or false if error
4284 function authenticate_user_login(
4285 $username,
4286 $password,
4287 $ignorelockout = false,
4288 &$failurereason = null,
4289 $logintoken = false,
4290 string|bool $loginrecaptcha = false,
4292 global $CFG, $DB, $PAGE, $SESSION;
4293 require_once("$CFG->libdir/authlib.php");
4295 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4296 // we have found the user
4298 } else if (!empty($CFG->authloginviaemail)) {
4299 if ($email = clean_param($username, PARAM_EMAIL)) {
4300 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4301 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4302 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4303 if (count($users) === 1) {
4304 // Use email for login only if unique.
4305 $user = reset($users);
4306 $user = get_complete_user_data('id', $user->id);
4307 $username = $user->username;
4309 unset($users);
4313 // Make sure this request came from the login form.
4314 if (!\core\session\manager::validate_login_token($logintoken)) {
4315 $failurereason = AUTH_LOGIN_FAILED;
4317 // Trigger login failed event (specifying the ID of the found user, if available).
4318 \core\event\user_login_failed::create([
4319 'userid' => ($user->id ?? 0),
4320 'other' => [
4321 'username' => $username,
4322 'reason' => $failurereason,
4324 ])->trigger();
4326 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4327 return false;
4330 // Login reCaptcha.
4331 if (login_captcha_enabled() && !validate_login_captcha($loginrecaptcha)) {
4332 $failurereason = AUTH_LOGIN_FAILED_RECAPTCHA;
4333 // Trigger login failed event (specifying the ID of the found user, if available).
4334 \core\event\user_login_failed::create([
4335 'userid' => ($user->id ?? 0),
4336 'other' => [
4337 'username' => $username,
4338 'reason' => $failurereason,
4340 ])->trigger();
4341 return false;
4344 $authsenabled = get_enabled_auth_plugins();
4346 if ($user) {
4347 // Use manual if auth not set.
4348 $auth = empty($user->auth) ? 'manual' : $user->auth;
4350 if (in_array($user->auth, $authsenabled)) {
4351 $authplugin = get_auth_plugin($user->auth);
4352 $authplugin->pre_user_login_hook($user);
4355 if (!empty($user->suspended)) {
4356 $failurereason = AUTH_LOGIN_SUSPENDED;
4358 // Trigger login failed event.
4359 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4360 'other' => array('username' => $username, 'reason' => $failurereason)));
4361 $event->trigger();
4362 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4363 return false;
4365 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4366 // Legacy way to suspend user.
4367 $failurereason = AUTH_LOGIN_SUSPENDED;
4369 // Trigger login failed event.
4370 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4371 'other' => array('username' => $username, 'reason' => $failurereason)));
4372 $event->trigger();
4373 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4374 return false;
4376 $auths = array($auth);
4378 } else {
4379 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4380 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4381 $failurereason = AUTH_LOGIN_NOUSER;
4383 // Trigger login failed event.
4384 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4385 'reason' => $failurereason)));
4386 $event->trigger();
4387 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4388 return false;
4391 // User does not exist.
4392 $auths = $authsenabled;
4393 $user = new stdClass();
4394 $user->id = 0;
4397 if ($ignorelockout) {
4398 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4399 // or this function is called from a SSO script.
4400 } else if ($user->id) {
4401 // Verify login lockout after other ways that may prevent user login.
4402 if (login_is_lockedout($user)) {
4403 $failurereason = AUTH_LOGIN_LOCKOUT;
4405 // Trigger login failed event.
4406 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4407 'other' => array('username' => $username, 'reason' => $failurereason)));
4408 $event->trigger();
4410 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4411 $SESSION->loginerrormsg = get_string('accountlocked', 'admin');
4413 return false;
4415 } else {
4416 // We can not lockout non-existing accounts.
4419 foreach ($auths as $auth) {
4420 $authplugin = get_auth_plugin($auth);
4422 // On auth fail fall through to the next plugin.
4423 if (!$authplugin->user_login($username, $password)) {
4424 continue;
4427 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4428 if (!empty($CFG->passwordpolicycheckonlogin)) {
4429 $errmsg = '';
4430 $passed = check_password_policy($password, $errmsg, $user);
4431 if (!$passed) {
4432 // First trigger event for failure.
4433 $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
4434 $failedevent->trigger();
4436 // If able to change password, set flag and move on.
4437 if ($authplugin->can_change_password()) {
4438 // Check if we are on internal change password page, or service is external, don't show notification.
4439 $internalchangeurl = new moodle_url('/login/change_password.php');
4440 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
4441 \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
4443 set_user_preference('auth_forcepasswordchange', 1, $user);
4444 } else if ($authplugin->can_reset_password()) {
4445 // Else force a reset if possible.
4446 \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
4447 redirect(new moodle_url('/login/forgot_password.php'));
4448 } else {
4449 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4450 // If support page is set, add link for help.
4451 if (!empty($CFG->supportpage)) {
4452 $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
4453 $link = \html_writer::tag('p', $link);
4454 $notifymsg .= $link;
4457 // If no change or reset is possible, add a notification for user.
4458 \core\notification::error($notifymsg);
4463 // Successful authentication.
4464 if ($user->id) {
4465 // User already exists in database.
4466 if (empty($user->auth)) {
4467 // For some reason auth isn't set yet.
4468 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4469 $user->auth = $auth;
4472 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4473 // the current hash algorithm while we have access to the user's password.
4474 update_internal_user_password($user, $password);
4476 if ($authplugin->is_synchronised_with_external()) {
4477 // Update user record from external DB.
4478 $user = update_user_record_by_id($user->id);
4480 } else {
4481 // The user is authenticated but user creation may be disabled.
4482 if (!empty($CFG->authpreventaccountcreation)) {
4483 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4485 // Trigger login failed event.
4486 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4487 'reason' => $failurereason)));
4488 $event->trigger();
4490 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4491 $_SERVER['HTTP_USER_AGENT']);
4492 return false;
4493 } else {
4494 $user = create_user_record($username, $password, $auth);
4498 $authplugin->sync_roles($user);
4500 foreach ($authsenabled as $hau) {
4501 $hauth = get_auth_plugin($hau);
4502 $hauth->user_authenticated_hook($user, $username, $password);
4505 if (empty($user->id)) {
4506 $failurereason = AUTH_LOGIN_NOUSER;
4507 // Trigger login failed event.
4508 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4509 'reason' => $failurereason)));
4510 $event->trigger();
4511 return false;
4514 if (!empty($user->suspended)) {
4515 // Just in case some auth plugin suspended account.
4516 $failurereason = AUTH_LOGIN_SUSPENDED;
4517 // Trigger login failed event.
4518 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4519 'other' => array('username' => $username, 'reason' => $failurereason)));
4520 $event->trigger();
4521 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4522 return false;
4525 login_attempt_valid($user);
4526 $failurereason = AUTH_LOGIN_OK;
4527 return $user;
4530 // Failed if all the plugins have failed.
4531 if (debugging('', DEBUG_ALL)) {
4532 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4535 if ($user->id) {
4536 login_attempt_failed($user);
4537 $failurereason = AUTH_LOGIN_FAILED;
4538 // Trigger login failed event.
4539 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4540 'other' => array('username' => $username, 'reason' => $failurereason)));
4541 $event->trigger();
4542 } else {
4543 $failurereason = AUTH_LOGIN_NOUSER;
4544 // Trigger login failed event.
4545 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4546 'reason' => $failurereason)));
4547 $event->trigger();
4550 return false;
4554 * Call to complete the user login process after authenticate_user_login()
4555 * has succeeded. It will setup the $USER variable and other required bits
4556 * and pieces.
4558 * NOTE:
4559 * - It will NOT log anything -- up to the caller to decide what to log.
4560 * - this function does not set any cookies any more!
4562 * @param stdClass $user
4563 * @param array $extrauserinfo
4564 * @return stdClass A {@link $USER} object - BC only, do not use
4566 function complete_user_login($user, array $extrauserinfo = []) {
4567 global $CFG, $DB, $USER, $SESSION;
4569 \core\session\manager::login_user($user);
4571 // Reload preferences from DB.
4572 unset($USER->preference);
4573 check_user_preferences_loaded($USER);
4575 // Update login times.
4576 update_user_login_times();
4578 // Extra session prefs init.
4579 set_login_session_preferences();
4581 // Trigger login event.
4582 $event = \core\event\user_loggedin::create(
4583 array(
4584 'userid' => $USER->id,
4585 'objectid' => $USER->id,
4586 'other' => [
4587 'username' => $USER->username,
4588 'extrauserinfo' => $extrauserinfo
4592 $event->trigger();
4594 // Check if the user is using a new browser or session (a new MoodleSession cookie is set in that case).
4595 // If the user is accessing from the same IP, ignore everything (most of the time will be a new session in the same browser).
4596 // Skip Web Service requests, CLI scripts, AJAX scripts, and request from the mobile app itself.
4597 $loginip = getremoteaddr();
4598 $isnewip = isset($SESSION->userpreviousip) && $SESSION->userpreviousip != $loginip;
4599 $isvalidenv = (!WS_SERVER && !CLI_SCRIPT && !NO_MOODLE_COOKIES) || PHPUNIT_TEST;
4601 if (!empty($SESSION->isnewsessioncookie) && $isnewip && $isvalidenv && !\core_useragent::is_moodle_app()) {
4603 $logintime = time();
4604 $ismoodleapp = false;
4605 $useragent = \core_useragent::get_user_agent_string();
4607 // Schedule adhoc task to sent a login notification to the user.
4608 $task = new \core\task\send_login_notifications();
4609 $task->set_userid($USER->id);
4610 $task->set_custom_data(compact('ismoodleapp', 'useragent', 'loginip', 'logintime'));
4611 $task->set_component('core');
4612 \core\task\manager::queue_adhoc_task($task);
4615 // Queue migrating the messaging data, if we need to.
4616 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4617 // Check if there are any legacy messages to migrate.
4618 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4619 \core_message\task\migrate_message_data::queue_task($USER->id);
4620 } else {
4621 set_user_preference('core_message_migrate_data', true, $USER->id);
4625 if (isguestuser()) {
4626 // No need to continue when user is THE guest.
4627 return $USER;
4630 if (CLI_SCRIPT) {
4631 // We can redirect to password change URL only in browser.
4632 return $USER;
4635 // Select password change url.
4636 $userauth = get_auth_plugin($USER->auth);
4638 // Check whether the user should be changing password.
4639 if (get_user_preferences('auth_forcepasswordchange', false)) {
4640 if ($userauth->can_change_password()) {
4641 if ($changeurl = $userauth->change_password_url()) {
4642 redirect($changeurl);
4643 } else {
4644 require_once($CFG->dirroot . '/login/lib.php');
4645 $SESSION->wantsurl = core_login_get_return_url();
4646 redirect($CFG->wwwroot.'/login/change_password.php');
4648 } else {
4649 throw new \moodle_exception('nopasswordchangeforced', 'auth');
4652 return $USER;
4656 * Check a password hash to see if it was hashed using the legacy hash algorithm (bcrypt).
4658 * @param string $password String to check.
4659 * @return bool True if the $password matches the format of a bcrypt hash.
4661 function password_is_legacy_hash(#[\SensitiveParameter] string $password): bool {
4662 return (bool) preg_match('/^\$2y\$[\d]{2}\$[A-Za-z0-9\.\/]{53}$/', $password);
4666 * Compare password against hash stored in user object to determine if it is valid.
4668 * If necessary it also updates the stored hash to the current format.
4670 * @param stdClass $user (Password property may be updated).
4671 * @param string $password Plain text password.
4672 * @return bool True if password is valid.
4674 function validate_internal_user_password(stdClass $user, #[\SensitiveParameter] string $password): bool {
4676 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4677 // Internal password is not used at all, it can not validate.
4678 return false;
4681 // First check if the password is valid, that is the password matches the stored hash.
4682 $validated = password_verify($password, $user->password);
4684 // If the password is valid, next check if the hash is legacy (bcrypt).
4685 // If it is, we update the hash to the new algorithm.
4686 if ($validated && password_is_legacy_hash($user->password)) {
4687 update_internal_user_password($user, $password);
4688 return true;
4689 } else if ($validated) {
4690 // If the password is valid, but the hash is not legacy, we can just return true.
4691 return true;
4692 } else {
4693 // If the password is not valid, we return false.
4694 return false;
4699 * Calculate hash for a plain text password.
4701 * @param string $password Plain text password to be hashed.
4702 * @param bool $fasthash If true, use a low number of rounds when generating the hash
4703 * This is faster to generate but makes the hash less secure.
4704 * It is used when lots of hashes need to be generated quickly.
4705 * @return string The hashed password.
4707 * @throws moodle_exception If a problem occurs while generating the hash.
4709 function hash_internal_user_password(#[\SensitiveParameter] string $password, $fasthash = false): string {
4710 // Set the cost factor to 5000 for fast hashing, otherwise use default cost.
4711 $rounds = $fasthash ? 5000 : 10000;
4713 // First generate a cryptographically suitable salt.
4714 $randombytes = random_bytes(16);
4715 $salt = substr(strtr(base64_encode($randombytes), '+', '.'), 0, 16);
4717 // Now construct the password string with the salt and number of rounds.
4718 // The password string is in the format $algorithm$rounds$salt$hash. ($6 is the SHA512 algorithm).
4719 $generatedhash = crypt($password, implode('$', [
4721 // The SHA512 Algorithm
4722 '6',
4723 "rounds={$rounds}",
4724 $salt,
4726 ]));
4728 if ($generatedhash === false || $generatedhash === null) {
4729 throw new moodle_exception('Failed to generate password hash.');
4732 return $generatedhash;
4736 * Update password hash in user object (if necessary).
4738 * The password is updated if:
4739 * 1. The password has changed (the hash of $user->password is different
4740 * to the hash of $password).
4741 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4742 * md5 algorithm).
4744 * Updating the password will modify the $user object and the database
4745 * record to use the current hashing algorithm.
4746 * It will remove Web Services user tokens too.
4748 * @param stdClass $user User object (password property may be updated).
4749 * @param string $password Plain text password.
4750 * @param bool $fasthash If true, use a low cost factor when generating the hash
4751 * This is much faster to generate but makes the hash
4752 * less secure. It is used when lots of hashes need to
4753 * be generated quickly.
4754 * @return bool Always returns true.
4756 function update_internal_user_password(
4757 stdClass $user,
4758 #[\SensitiveParameter] string $password,
4759 bool $fasthash = false
4760 ): bool {
4761 global $CFG, $DB;
4763 // Figure out what the hashed password should be.
4764 if (!isset($user->auth)) {
4765 debugging('User record in update_internal_user_password() must include field auth',
4766 DEBUG_DEVELOPER);
4767 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4769 $authplugin = get_auth_plugin($user->auth);
4770 if ($authplugin->prevent_local_passwords()) {
4771 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4772 } else {
4773 $hashedpassword = hash_internal_user_password($password, $fasthash);
4776 $algorithmchanged = false;
4778 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4779 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4780 $passwordchanged = ($user->password !== $hashedpassword);
4782 } else if (isset($user->password)) {
4783 // If verification fails then it means the password has changed.
4784 $passwordchanged = !password_verify($password, $user->password);
4785 $algorithmchanged = password_is_legacy_hash($user->password);
4786 } else {
4787 // While creating new user, password in unset in $user object, to avoid
4788 // saving it with user_create()
4789 $passwordchanged = true;
4792 if ($passwordchanged || $algorithmchanged) {
4793 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4794 $user->password = $hashedpassword;
4796 // Trigger event.
4797 $user = $DB->get_record('user', array('id' => $user->id));
4798 \core\event\user_password_updated::create_from_user($user)->trigger();
4800 // Remove WS user tokens.
4801 if (!empty($CFG->passwordchangetokendeletion)) {
4802 require_once($CFG->dirroot.'/webservice/lib.php');
4803 webservice::delete_user_ws_tokens($user->id);
4807 return true;
4811 * Get a complete user record, which includes all the info in the user record.
4813 * Intended for setting as $USER session variable
4815 * @param string $field The user field to be checked for a given value.
4816 * @param string $value The value to match for $field.
4817 * @param int $mnethostid
4818 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4819 * found. Otherwise, it will just return false.
4820 * @return mixed False, or A {@link $USER} object.
4822 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4823 global $CFG, $DB;
4825 if (!$field || !$value) {
4826 return false;
4829 // Change the field to lowercase.
4830 $field = core_text::strtolower($field);
4832 // List of case insensitive fields.
4833 $caseinsensitivefields = ['email'];
4835 // Username input is forced to lowercase and should be case sensitive.
4836 if ($field == 'username') {
4837 $value = core_text::strtolower($value);
4840 // Build the WHERE clause for an SQL query.
4841 $params = array('fieldval' => $value);
4843 // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4844 // such as MySQL by pre-filtering users with accent-insensitive subselect.
4845 if (in_array($field, $caseinsensitivefields)) {
4846 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4847 $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4848 $params['fieldval2'] = $value;
4849 } else {
4850 $fieldselect = "$field = :fieldval";
4851 $idsubselect = '';
4853 $constraints = "$fieldselect AND deleted <> 1";
4855 // If we are loading user data based on anything other than id,
4856 // we must also restrict our search based on mnet host.
4857 if ($field != 'id') {
4858 if (empty($mnethostid)) {
4859 // If empty, we restrict to local users.
4860 $mnethostid = $CFG->mnet_localhost_id;
4863 if (!empty($mnethostid)) {
4864 $params['mnethostid'] = $mnethostid;
4865 $constraints .= " AND mnethostid = :mnethostid";
4868 if ($idsubselect) {
4869 $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4872 // Get all the basic user data.
4873 try {
4874 // Make sure that there's only a single record that matches our query.
4875 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4876 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4877 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4878 } catch (dml_exception $exception) {
4879 if ($throwexception) {
4880 throw $exception;
4881 } else {
4882 // Return false when no records or multiple records were found.
4883 return false;
4887 // Get various settings and preferences.
4889 // Preload preference cache.
4890 check_user_preferences_loaded($user);
4892 // Load course enrolment related stuff.
4893 $user->lastcourseaccess = array(); // During last session.
4894 $user->currentcourseaccess = array(); // During current session.
4895 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4896 foreach ($lastaccesses as $lastaccess) {
4897 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4901 // Add cohort theme.
4902 if (!empty($CFG->allowcohortthemes)) {
4903 require_once($CFG->dirroot . '/cohort/lib.php');
4904 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4905 $user->cohorttheme = $cohorttheme;
4909 // Add the custom profile fields to the user record.
4910 $user->profile = array();
4911 if (!isguestuser($user)) {
4912 require_once($CFG->dirroot.'/user/profile/lib.php');
4913 profile_load_custom_fields($user);
4916 // Rewrite some variables if necessary.
4917 if (!empty($user->description)) {
4918 // No need to cart all of it around.
4919 $user->description = true;
4921 if (isguestuser($user)) {
4922 // Guest language always same as site.
4923 $user->lang = get_newuser_language();
4924 // Name always in current language.
4925 $user->firstname = get_string('guestuser');
4926 $user->lastname = ' ';
4929 return $user;
4933 * Validate a password against the configured password policy
4935 * @param string $password the password to be checked against the password policy
4936 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4937 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
4939 * @return bool true if the password is valid according to the policy. false otherwise.
4941 function check_password_policy($password, &$errmsg, $user = null) {
4942 global $CFG;
4944 if (!empty($CFG->passwordpolicy)) {
4945 $errmsg = '';
4946 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4947 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4949 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4950 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4952 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4953 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4955 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4956 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4958 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4959 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4961 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4962 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4965 // Fire any additional password policy functions from plugins.
4966 // Plugin functions should output an error message string or empty string for success.
4967 $pluginsfunction = get_plugins_with_function('check_password_policy');
4968 foreach ($pluginsfunction as $plugintype => $plugins) {
4969 foreach ($plugins as $pluginfunction) {
4970 $pluginerr = $pluginfunction($password, $user);
4971 if ($pluginerr) {
4972 $errmsg .= '<div>'. $pluginerr .'</div>';
4978 if ($errmsg == '') {
4979 return true;
4980 } else {
4981 return false;
4987 * When logging in, this function is run to set certain preferences for the current SESSION.
4989 function set_login_session_preferences() {
4990 global $SESSION;
4992 $SESSION->justloggedin = true;
4994 unset($SESSION->lang);
4995 unset($SESSION->forcelang);
4996 unset($SESSION->load_navigation_admin);
5001 * Delete a course, including all related data from the database, and any associated files.
5003 * @param mixed $courseorid The id of the course or course object to delete.
5004 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5005 * @return bool true if all the removals succeeded. false if there were any failures. If this
5006 * method returns false, some of the removals will probably have succeeded, and others
5007 * failed, but you have no way of knowing which.
5009 function delete_course($courseorid, $showfeedback = true) {
5010 global $DB, $CFG;
5012 if (is_object($courseorid)) {
5013 $courseid = $courseorid->id;
5014 $course = $courseorid;
5015 } else {
5016 $courseid = $courseorid;
5017 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5018 return false;
5021 $context = context_course::instance($courseid);
5023 // Frontpage course can not be deleted!!
5024 if ($courseid == SITEID) {
5025 return false;
5028 // Allow plugins to use this course before we completely delete it.
5029 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5030 foreach ($pluginsfunction as $plugintype => $plugins) {
5031 foreach ($plugins as $pluginfunction) {
5032 $pluginfunction($course);
5037 // Tell the search manager we are about to delete a course. This prevents us sending updates
5038 // for each individual context being deleted.
5039 \core_search\manager::course_deleting_start($courseid);
5041 $handler = core_course\customfield\course_handler::create();
5042 $handler->delete_instance($courseid);
5044 // Make the course completely empty.
5045 remove_course_contents($courseid, $showfeedback);
5047 // Delete the course and related context instance.
5048 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5050 // Communication provider delete associated information.
5051 $communication = \core_communication\api::load_by_instance(
5052 'core_course',
5053 'coursecommunication',
5054 $course->id
5057 // Update communication room membership of enrolled users.
5058 require_once($CFG->libdir . '/enrollib.php');
5059 $courseusers = enrol_get_course_users($courseid);
5060 $enrolledusers = [];
5062 foreach ($courseusers as $user) {
5063 $enrolledusers[] = $user->id;
5066 $communication->remove_members_from_room($enrolledusers);
5068 $communication->delete_room();
5070 $DB->delete_records("course", array("id" => $courseid));
5071 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5073 // Reset all course related caches here.
5074 core_courseformat\base::reset_course_cache($courseid);
5076 // Tell search that we have deleted the course so it can delete course data from the index.
5077 \core_search\manager::course_deleting_finish($courseid);
5079 // Trigger a course deleted event.
5080 $event = \core\event\course_deleted::create(array(
5081 'objectid' => $course->id,
5082 'context' => $context,
5083 'other' => array(
5084 'shortname' => $course->shortname,
5085 'fullname' => $course->fullname,
5086 'idnumber' => $course->idnumber
5089 $event->add_record_snapshot('course', $course);
5090 $event->trigger();
5092 return true;
5096 * Clear a course out completely, deleting all content but don't delete the course itself.
5098 * This function does not verify any permissions.
5100 * Please note this function also deletes all user enrolments,
5101 * enrolment instances and role assignments by default.
5103 * $options:
5104 * - 'keep_roles_and_enrolments' - false by default
5105 * - 'keep_groups_and_groupings' - false by default
5107 * @param int $courseid The id of the course that is being deleted
5108 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5109 * @param array $options extra options
5110 * @return bool true if all the removals succeeded. false if there were any failures. If this
5111 * method returns false, some of the removals will probably have succeeded, and others
5112 * failed, but you have no way of knowing which.
5114 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5115 global $CFG, $DB, $OUTPUT;
5117 require_once($CFG->libdir.'/badgeslib.php');
5118 require_once($CFG->libdir.'/completionlib.php');
5119 require_once($CFG->libdir.'/questionlib.php');
5120 require_once($CFG->libdir.'/gradelib.php');
5121 require_once($CFG->dirroot.'/group/lib.php');
5122 require_once($CFG->dirroot.'/comment/lib.php');
5123 require_once($CFG->dirroot.'/rating/lib.php');
5124 require_once($CFG->dirroot.'/notes/lib.php');
5126 // Handle course badges.
5127 badges_handle_course_deletion($courseid);
5129 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5130 $strdeleted = get_string('deleted').' - ';
5132 // Some crazy wishlist of stuff we should skip during purging of course content.
5133 $options = (array)$options;
5135 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5136 $coursecontext = context_course::instance($courseid);
5137 $fs = get_file_storage();
5139 // Delete course completion information, this has to be done before grades and enrols.
5140 $cc = new completion_info($course);
5141 $cc->clear_criteria();
5142 if ($showfeedback) {
5143 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5146 // Remove all data from gradebook - this needs to be done before course modules
5147 // because while deleting this information, the system may need to reference
5148 // the course modules that own the grades.
5149 remove_course_grades($courseid, $showfeedback);
5150 remove_grade_letters($coursecontext, $showfeedback);
5152 // Delete course blocks in any all child contexts,
5153 // they may depend on modules so delete them first.
5154 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5155 foreach ($childcontexts as $childcontext) {
5156 blocks_delete_all_for_context($childcontext->id);
5158 unset($childcontexts);
5159 blocks_delete_all_for_context($coursecontext->id);
5160 if ($showfeedback) {
5161 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5164 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
5165 rebuild_course_cache($courseid, true);
5167 // Get the list of all modules that are properly installed.
5168 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5170 // Delete every instance of every module,
5171 // this has to be done before deleting of course level stuff.
5172 $locations = core_component::get_plugin_list('mod');
5173 foreach ($locations as $modname => $moddir) {
5174 if ($modname === 'NEWMODULE') {
5175 continue;
5177 if (array_key_exists($modname, $allmodules)) {
5178 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5179 FROM {".$modname."} m
5180 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5181 WHERE m.course = :courseid";
5182 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5183 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5185 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5186 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5188 if ($instances) {
5189 foreach ($instances as $cm) {
5190 if ($cm->id) {
5191 // Delete activity context questions and question categories.
5192 question_delete_activity($cm);
5193 // Notify the competency subsystem.
5194 \core_competency\api::hook_course_module_deleted($cm);
5196 // Delete all tag instances associated with the instance of this module.
5197 core_tag_tag::delete_instances("mod_{$modname}", null, context_module::instance($cm->id)->id);
5198 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
5200 if (function_exists($moddelete)) {
5201 // This purges all module data in related tables, extra user prefs, settings, etc.
5202 $moddelete($cm->modinstance);
5203 } else {
5204 // NOTE: we should not allow installation of modules with missing delete support!
5205 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5206 $DB->delete_records($modname, array('id' => $cm->modinstance));
5209 if ($cm->id) {
5210 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5211 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5212 $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id]);
5213 $DB->delete_records('course_modules_viewed', ['coursemoduleid' => $cm->id]);
5214 $DB->delete_records('course_modules', array('id' => $cm->id));
5215 rebuild_course_cache($cm->course, true);
5219 if ($instances and $showfeedback) {
5220 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5222 } else {
5223 // Ooops, this module is not properly installed, force-delete it in the next block.
5227 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5229 // Delete completion defaults.
5230 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5232 // Remove all data from availability and completion tables that is associated
5233 // with course-modules belonging to this course. Note this is done even if the
5234 // features are not enabled now, in case they were enabled previously.
5235 $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
5236 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5237 $DB->delete_records_subquery('course_modules_viewed', 'coursemoduleid', 'id',
5238 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5240 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5241 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5242 $allmodulesbyid = array_flip($allmodules);
5243 foreach ($cms as $cm) {
5244 if (array_key_exists($cm->module, $allmodulesbyid)) {
5245 try {
5246 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5247 } catch (Exception $e) {
5248 // Ignore weird or missing table problems.
5251 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5252 $DB->delete_records('course_modules', array('id' => $cm->id));
5253 rebuild_course_cache($cm->course, true);
5256 if ($showfeedback) {
5257 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5260 // Delete questions and question categories.
5261 question_delete_course($course);
5262 if ($showfeedback) {
5263 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5266 // Delete content bank contents.
5267 $cb = new \core_contentbank\contentbank();
5268 $cbdeleted = $cb->delete_contents($coursecontext);
5269 if ($showfeedback && $cbdeleted) {
5270 echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5273 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5274 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5275 foreach ($childcontexts as $childcontext) {
5276 $childcontext->delete();
5278 unset($childcontexts);
5280 // Remove roles and enrolments by default.
5281 if (empty($options['keep_roles_and_enrolments'])) {
5282 // This hack is used in restore when deleting contents of existing course.
5283 // During restore, we should remove only enrolment related data that the user performing the restore has a
5284 // permission to remove.
5285 $userid = $options['userid'] ?? null;
5286 enrol_course_delete($course, $userid);
5287 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5288 if ($showfeedback) {
5289 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5293 // Delete any groups, removing members and grouping/course links first.
5294 if (empty($options['keep_groups_and_groupings'])) {
5295 groups_delete_groupings($course->id, $showfeedback);
5296 groups_delete_groups($course->id, $showfeedback);
5299 // Filters be gone!
5300 filter_delete_all_for_context($coursecontext->id);
5302 // Notes, you shall not pass!
5303 note_delete_all($course->id);
5305 // Die comments!
5306 comment::delete_comments($coursecontext->id);
5308 // Ratings are history too.
5309 $delopt = new stdclass();
5310 $delopt->contextid = $coursecontext->id;
5311 $rm = new rating_manager();
5312 $rm->delete_ratings($delopt);
5314 // Delete course tags.
5315 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5317 // Give the course format the opportunity to remove its obscure data.
5318 $format = course_get_format($course);
5319 $format->delete_format_data();
5321 // Notify the competency subsystem.
5322 \core_competency\api::hook_course_deleted($course);
5324 // Delete calendar events.
5325 $DB->delete_records('event', array('courseid' => $course->id));
5326 $fs->delete_area_files($coursecontext->id, 'calendar');
5328 // Delete all related records in other core tables that may have a courseid
5329 // This array stores the tables that need to be cleared, as
5330 // table_name => column_name that contains the course id.
5331 $tablestoclear = array(
5332 'backup_courses' => 'courseid', // Scheduled backup stuff.
5333 'user_lastaccess' => 'courseid', // User access info.
5335 foreach ($tablestoclear as $table => $col) {
5336 $DB->delete_records($table, array($col => $course->id));
5339 // Delete all course backup files.
5340 $fs->delete_area_files($coursecontext->id, 'backup');
5342 // Cleanup course record - remove links to deleted stuff.
5343 $oldcourse = new stdClass();
5344 $oldcourse->id = $course->id;
5345 $oldcourse->summary = '';
5346 $oldcourse->cacherev = 0;
5347 $oldcourse->legacyfiles = 0;
5348 if (!empty($options['keep_groups_and_groupings'])) {
5349 $oldcourse->defaultgroupingid = 0;
5351 $DB->update_record('course', $oldcourse);
5353 // Delete course sections.
5354 $DB->delete_records('course_sections', array('course' => $course->id));
5356 // Delete legacy, section and any other course files.
5357 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5359 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5360 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5361 // Easy, do not delete the context itself...
5362 $coursecontext->delete_content();
5363 } else {
5364 // Hack alert!!!!
5365 // We can not drop all context stuff because it would bork enrolments and roles,
5366 // there might be also files used by enrol plugins...
5369 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5370 // also some non-standard unsupported plugins may try to store something there.
5371 fulldelete($CFG->dataroot.'/'.$course->id);
5373 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5374 course_modinfo::purge_course_cache($courseid);
5376 // Trigger a course content deleted event.
5377 $event = \core\event\course_content_deleted::create(array(
5378 'objectid' => $course->id,
5379 'context' => $coursecontext,
5380 'other' => array('shortname' => $course->shortname,
5381 'fullname' => $course->fullname,
5382 'options' => $options) // Passing this for legacy reasons.
5384 $event->add_record_snapshot('course', $course);
5385 $event->trigger();
5387 return true;
5391 * Change dates in module - used from course reset.
5393 * @param string $modname forum, assignment, etc
5394 * @param array $fields array of date fields from mod table
5395 * @param int $timeshift time difference
5396 * @param int $courseid
5397 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5398 * @return bool success
5400 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5401 global $CFG, $DB;
5402 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5404 $return = true;
5405 $params = array($timeshift, $courseid);
5406 foreach ($fields as $field) {
5407 $updatesql = "UPDATE {".$modname."}
5408 SET $field = $field + ?
5409 WHERE course=? AND $field<>0";
5410 if ($modid) {
5411 $updatesql .= ' AND id=?';
5412 $params[] = $modid;
5414 $return = $DB->execute($updatesql, $params) && $return;
5417 return $return;
5421 * This function will empty a course of user data.
5422 * It will retain the activities and the structure of the course.
5424 * @param object $data an object containing all the settings including courseid (without magic quotes)
5425 * @return array status array of array component, item, error
5427 function reset_course_userdata($data) {
5428 global $CFG, $DB;
5429 require_once($CFG->libdir.'/gradelib.php');
5430 require_once($CFG->libdir.'/completionlib.php');
5431 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5432 require_once($CFG->dirroot.'/group/lib.php');
5434 $data->courseid = $data->id;
5435 $context = context_course::instance($data->courseid);
5437 $eventparams = array(
5438 'context' => $context,
5439 'courseid' => $data->id,
5440 'other' => array(
5441 'reset_options' => (array) $data
5444 $event = \core\event\course_reset_started::create($eventparams);
5445 $event->trigger();
5447 // Calculate the time shift of dates.
5448 if (!empty($data->reset_start_date)) {
5449 // Time part of course startdate should be zero.
5450 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5451 } else {
5452 $data->timeshift = 0;
5455 // Result array: component, item, error.
5456 $status = array();
5458 // Start the resetting.
5459 $componentstr = get_string('general');
5461 // Move the course start time.
5462 if (!empty($data->reset_start_date) and $data->timeshift) {
5463 // Change course start data.
5464 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5465 // Update all course and group events - do not move activity events.
5466 $updatesql = "UPDATE {event}
5467 SET timestart = timestart + ?
5468 WHERE courseid=? AND instance=0";
5469 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5471 // Update any date activity restrictions.
5472 if ($CFG->enableavailability) {
5473 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5476 // Update completion expected dates.
5477 if ($CFG->enablecompletion) {
5478 $modinfo = get_fast_modinfo($data->courseid);
5479 $changed = false;
5480 foreach ($modinfo->get_cms() as $cm) {
5481 if ($cm->completion && !empty($cm->completionexpected)) {
5482 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5483 array('id' => $cm->id));
5484 $changed = true;
5488 // Clear course cache if changes made.
5489 if ($changed) {
5490 rebuild_course_cache($data->courseid, true);
5493 // Update course date completion criteria.
5494 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5497 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5500 if (!empty($data->reset_end_date)) {
5501 // If the user set a end date value respect it.
5502 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5503 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5504 // If there is a time shift apply it to the end date as well.
5505 $enddate = $data->reset_end_date_old + $data->timeshift;
5506 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5509 if (!empty($data->reset_events)) {
5510 $DB->delete_records('event', array('courseid' => $data->courseid));
5511 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5514 if (!empty($data->reset_notes)) {
5515 require_once($CFG->dirroot.'/notes/lib.php');
5516 note_delete_all($data->courseid);
5517 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5520 if (!empty($data->delete_blog_associations)) {
5521 require_once($CFG->dirroot.'/blog/lib.php');
5522 blog_remove_associations_for_course($data->courseid);
5523 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5526 if (!empty($data->reset_completion)) {
5527 // Delete course and activity completion information.
5528 $course = $DB->get_record('course', array('id' => $data->courseid));
5529 $cc = new completion_info($course);
5530 $cc->delete_all_completion_data();
5531 $status[] = array('component' => $componentstr,
5532 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5535 if (!empty($data->reset_competency_ratings)) {
5536 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5537 $status[] = array('component' => $componentstr,
5538 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5541 $componentstr = get_string('roles');
5543 if (!empty($data->reset_roles_overrides)) {
5544 $children = $context->get_child_contexts();
5545 foreach ($children as $child) {
5546 $child->delete_capabilities();
5548 $context->delete_capabilities();
5549 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5552 if (!empty($data->reset_roles_local)) {
5553 $children = $context->get_child_contexts();
5554 foreach ($children as $child) {
5555 role_unassign_all(array('contextid' => $child->id));
5557 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5560 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5561 $data->unenrolled = array();
5562 if (!empty($data->unenrol_users)) {
5563 $plugins = enrol_get_plugins(true);
5564 $instances = enrol_get_instances($data->courseid, true);
5565 foreach ($instances as $key => $instance) {
5566 if (!isset($plugins[$instance->enrol])) {
5567 unset($instances[$key]);
5568 continue;
5572 $usersroles = enrol_get_course_users_roles($data->courseid);
5573 foreach ($data->unenrol_users as $withroleid) {
5574 if ($withroleid) {
5575 $sql = "SELECT ue.*
5576 FROM {user_enrolments} ue
5577 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5578 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5579 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5580 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5582 } else {
5583 // Without any role assigned at course context.
5584 $sql = "SELECT ue.*
5585 FROM {user_enrolments} ue
5586 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5587 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5588 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5589 WHERE ra.id IS null";
5590 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5593 $rs = $DB->get_recordset_sql($sql, $params);
5594 foreach ($rs as $ue) {
5595 if (!isset($instances[$ue->enrolid])) {
5596 continue;
5598 $instance = $instances[$ue->enrolid];
5599 $plugin = $plugins[$instance->enrol];
5600 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5601 continue;
5604 if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5605 // If we don't remove all roles and user has more than one role, just remove this role.
5606 role_unassign($withroleid, $ue->userid, $context->id);
5608 unset($usersroles[$ue->userid][$withroleid]);
5609 } else {
5610 // If we remove all roles or user has only one role, unenrol user from course.
5611 $plugin->unenrol_user($instance, $ue->userid);
5613 $data->unenrolled[$ue->userid] = $ue->userid;
5615 $rs->close();
5618 if (!empty($data->unenrolled)) {
5619 $status[] = array(
5620 'component' => $componentstr,
5621 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5622 'error' => false
5626 $componentstr = get_string('groups');
5628 // Remove all group members.
5629 if (!empty($data->reset_groups_members)) {
5630 groups_delete_group_members($data->courseid);
5631 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5634 // Remove all groups.
5635 if (!empty($data->reset_groups_remove)) {
5636 groups_delete_groups($data->courseid, false);
5637 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5640 // Remove all grouping members.
5641 if (!empty($data->reset_groupings_members)) {
5642 groups_delete_groupings_groups($data->courseid, false);
5643 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5646 // Remove all groupings.
5647 if (!empty($data->reset_groupings_remove)) {
5648 groups_delete_groupings($data->courseid, false);
5649 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5652 // Look in every instance of every module for data to delete.
5653 $unsupportedmods = array();
5654 if ($allmods = $DB->get_records('modules') ) {
5655 foreach ($allmods as $mod) {
5656 $modname = $mod->name;
5657 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5658 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5659 if (file_exists($modfile)) {
5660 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5661 continue; // Skip mods with no instances.
5663 include_once($modfile);
5664 if (function_exists($moddeleteuserdata)) {
5665 $modstatus = $moddeleteuserdata($data);
5666 if (is_array($modstatus)) {
5667 $status = array_merge($status, $modstatus);
5668 } else {
5669 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5671 } else {
5672 $unsupportedmods[] = $mod;
5674 } else {
5675 debugging('Missing lib.php in '.$modname.' module!');
5677 // Update calendar events for all modules.
5678 course_module_bulk_update_calendar_events($modname, $data->courseid);
5680 // Purge the course cache after resetting course start date. MDL-76936
5681 if ($data->timeshift) {
5682 course_modinfo::purge_course_cache($data->courseid);
5686 // Mention unsupported mods.
5687 if (!empty($unsupportedmods)) {
5688 foreach ($unsupportedmods as $mod) {
5689 $status[] = array(
5690 'component' => get_string('modulenameplural', $mod->name),
5691 'item' => '',
5692 'error' => get_string('resetnotimplemented')
5697 $componentstr = get_string('gradebook', 'grades');
5698 // Reset gradebook,.
5699 if (!empty($data->reset_gradebook_items)) {
5700 remove_course_grades($data->courseid, false);
5701 grade_grab_course_grades($data->courseid);
5702 grade_regrade_final_grades($data->courseid);
5703 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5705 } else if (!empty($data->reset_gradebook_grades)) {
5706 grade_course_reset($data->courseid);
5707 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5709 // Reset comments.
5710 if (!empty($data->reset_comments)) {
5711 require_once($CFG->dirroot.'/comment/lib.php');
5712 comment::reset_course_page_comments($context);
5715 $event = \core\event\course_reset_ended::create($eventparams);
5716 $event->trigger();
5718 return $status;
5722 * Generate an email processing address.
5724 * @param int $modid
5725 * @param string $modargs
5726 * @return string Returns email processing address
5728 function generate_email_processing_address($modid, $modargs) {
5729 global $CFG;
5731 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5732 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5738 * @todo Finish documenting this function
5740 * @param string $modargs
5741 * @param string $body Currently unused
5743 function moodle_process_email($modargs, $body) {
5744 global $DB;
5746 // The first char should be an unencoded letter. We'll take this as an action.
5747 switch ($modargs[0]) {
5748 case 'B': { // Bounce.
5749 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5750 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5751 // Check the half md5 of their email.
5752 $md5check = substr(md5($user->email), 0, 16);
5753 if ($md5check == substr($modargs, -16)) {
5754 set_bounce_count($user);
5756 // Else maybe they've already changed it?
5759 break;
5760 // Maybe more later?
5764 // CORRESPONDENCE.
5767 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5769 * @param string $action 'get', 'buffer', 'close' or 'flush'
5770 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5772 function get_mailer($action='get') {
5773 global $CFG;
5775 /** @var moodle_phpmailer $mailer */
5776 static $mailer = null;
5777 static $counter = 0;
5779 if (!isset($CFG->smtpmaxbulk)) {
5780 $CFG->smtpmaxbulk = 1;
5783 if ($action == 'get') {
5784 $prevkeepalive = false;
5786 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5787 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5788 $counter++;
5789 // Reset the mailer.
5790 $mailer->Priority = 3;
5791 $mailer->CharSet = 'UTF-8'; // Our default.
5792 $mailer->ContentType = "text/plain";
5793 $mailer->Encoding = "8bit";
5794 $mailer->From = "root@localhost";
5795 $mailer->FromName = "Root User";
5796 $mailer->Sender = "";
5797 $mailer->Subject = "";
5798 $mailer->Body = "";
5799 $mailer->AltBody = "";
5800 $mailer->ConfirmReadingTo = "";
5802 $mailer->clearAllRecipients();
5803 $mailer->clearReplyTos();
5804 $mailer->clearAttachments();
5805 $mailer->clearCustomHeaders();
5806 return $mailer;
5809 $prevkeepalive = $mailer->SMTPKeepAlive;
5810 get_mailer('flush');
5813 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5814 $mailer = new moodle_phpmailer();
5816 $counter = 1;
5818 if ($CFG->smtphosts == 'qmail') {
5819 // Use Qmail system.
5820 $mailer->isQmail();
5822 } else if (empty($CFG->smtphosts)) {
5823 // Use PHP mail() = sendmail.
5824 $mailer->isMail();
5826 } else {
5827 // Use SMTP directly.
5828 $mailer->isSMTP();
5829 if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5830 $mailer->SMTPDebug = 3;
5832 // Specify main and backup servers.
5833 $mailer->Host = $CFG->smtphosts;
5834 // Specify secure connection protocol.
5835 $mailer->SMTPSecure = $CFG->smtpsecure;
5836 // Use previous keepalive.
5837 $mailer->SMTPKeepAlive = $prevkeepalive;
5839 if ($CFG->smtpuser) {
5840 // Use SMTP authentication.
5841 $mailer->SMTPAuth = true;
5842 $mailer->Username = $CFG->smtpuser;
5843 $mailer->Password = $CFG->smtppass;
5847 return $mailer;
5850 $nothing = null;
5852 // Keep smtp session open after sending.
5853 if ($action == 'buffer') {
5854 if (!empty($CFG->smtpmaxbulk)) {
5855 get_mailer('flush');
5856 $m = get_mailer();
5857 if ($m->Mailer == 'smtp') {
5858 $m->SMTPKeepAlive = true;
5861 return $nothing;
5864 // Close smtp session, but continue buffering.
5865 if ($action == 'flush') {
5866 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5867 if (!empty($mailer->SMTPDebug)) {
5868 echo '<pre>'."\n";
5870 $mailer->SmtpClose();
5871 if (!empty($mailer->SMTPDebug)) {
5872 echo '</pre>';
5875 return $nothing;
5878 // Close smtp session, do not buffer anymore.
5879 if ($action == 'close') {
5880 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5881 get_mailer('flush');
5882 $mailer->SMTPKeepAlive = false;
5884 $mailer = null; // Better force new instance.
5885 return $nothing;
5890 * A helper function to test for email diversion
5892 * @param string $email
5893 * @return bool Returns true if the email should be diverted
5895 function email_should_be_diverted($email) {
5896 global $CFG;
5898 if (empty($CFG->divertallemailsto)) {
5899 return false;
5902 if (empty($CFG->divertallemailsexcept)) {
5903 return true;
5906 $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept, -1, PREG_SPLIT_NO_EMPTY));
5907 foreach ($patterns as $pattern) {
5908 if (preg_match("/{$pattern}/i", $email)) {
5909 return false;
5913 return true;
5917 * Generate a unique email Message-ID using the moodle domain and install path
5919 * @param string $localpart An optional unique message id prefix.
5920 * @return string The formatted ID ready for appending to the email headers.
5922 function generate_email_messageid($localpart = null) {
5923 global $CFG;
5925 $urlinfo = parse_url($CFG->wwwroot);
5926 $base = '@' . $urlinfo['host'];
5928 // If multiple moodles are on the same domain we want to tell them
5929 // apart so we add the install path to the local part. This means
5930 // that the id local part should never contain a / character so
5931 // we can correctly parse the id to reassemble the wwwroot.
5932 if (isset($urlinfo['path'])) {
5933 $base = $urlinfo['path'] . $base;
5936 if (empty($localpart)) {
5937 $localpart = uniqid('', true);
5940 // Because we may have an option /installpath suffix to the local part
5941 // of the id we need to escape any / chars which are in the $localpart.
5942 $localpart = str_replace('/', '%2F', $localpart);
5944 return '<' . $localpart . $base . '>';
5948 * Send an email to a specified user
5950 * @param stdClass $user A {@link $USER} object
5951 * @param stdClass $from A {@link $USER} object
5952 * @param string $subject plain text subject line of the email
5953 * @param string $messagetext plain text version of the message
5954 * @param string $messagehtml complete html version of the message (optional)
5955 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
5956 * the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
5957 * @param string $attachname the name of the file (extension indicates MIME)
5958 * @param bool $usetrueaddress determines whether $from email address should
5959 * be sent out. Will be overruled by user profile setting for maildisplay
5960 * @param string $replyto Email address to reply to
5961 * @param string $replytoname Name of reply to recipient
5962 * @param int $wordwrapwidth custom word wrap width, default 79
5963 * @return bool Returns true if mail was sent OK and false if there was an error.
5965 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5966 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5968 global $CFG, $PAGE, $SITE;
5970 if (empty($user) or empty($user->id)) {
5971 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5972 return false;
5975 if (empty($user->email)) {
5976 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5977 return false;
5980 if (!empty($user->deleted)) {
5981 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5982 return false;
5985 if (defined('BEHAT_SITE_RUNNING')) {
5986 // Fake email sending in behat.
5987 return true;
5990 if (!empty($CFG->noemailever)) {
5991 // Hidden setting for development sites, set in config.php if needed.
5992 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5993 return true;
5996 if (email_should_be_diverted($user->email)) {
5997 $subject = "[DIVERTED {$user->email}] $subject";
5998 $user = clone($user);
5999 $user->email = $CFG->divertallemailsto;
6002 // Skip mail to suspended users.
6003 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
6004 return true;
6007 if (!validate_email($user->email)) {
6008 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
6009 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
6010 return false;
6013 if (over_bounce_threshold($user)) {
6014 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
6015 return false;
6018 // TLD .invalid is specifically reserved for invalid domain names.
6019 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
6020 if (substr($user->email, -8) == '.invalid') {
6021 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
6022 return true; // This is not an error.
6025 // If the user is a remote mnet user, parse the email text for URL to the
6026 // wwwroot and modify the url to direct the user's browser to login at their
6027 // home site (identity provider - idp) before hitting the link itself.
6028 if (is_mnet_remote_user($user)) {
6029 require_once($CFG->dirroot.'/mnet/lib.php');
6031 $jumpurl = mnet_get_idp_jump_url($user);
6032 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
6034 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
6035 $callback,
6036 $messagetext);
6037 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
6038 $callback,
6039 $messagehtml);
6041 $mail = get_mailer();
6043 if (!empty($mail->SMTPDebug)) {
6044 echo '<pre>' . "\n";
6047 $temprecipients = array();
6048 $tempreplyto = array();
6050 // Make sure that we fall back onto some reasonable no-reply address.
6051 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
6052 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
6054 if (!validate_email($noreplyaddress)) {
6055 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6056 $noreplyaddress = $noreplyaddressdefault;
6059 // Make up an email address for handling bounces.
6060 if (!empty($CFG->handlebounces)) {
6061 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
6062 $mail->Sender = generate_email_processing_address(0, $modargs);
6063 } else {
6064 $mail->Sender = $noreplyaddress;
6067 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6068 if (!empty($replyto) && !validate_email($replyto)) {
6069 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6070 $replyto = $noreplyaddress;
6073 if (is_string($from)) { // So we can pass whatever we want if there is need.
6074 $mail->From = $noreplyaddress;
6075 $mail->FromName = $from;
6076 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6077 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6078 // in a course with the sender.
6079 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6080 if (!validate_email($from->email)) {
6081 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
6082 // Better not to use $noreplyaddress in this case.
6083 return false;
6085 $mail->From = $from->email;
6086 $fromdetails = new stdClass();
6087 $fromdetails->name = fullname($from);
6088 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6089 $fromdetails->siteshortname = format_string($SITE->shortname);
6090 $fromstring = $fromdetails->name;
6091 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
6092 $fromstring = get_string('emailvia', 'core', $fromdetails);
6094 $mail->FromName = $fromstring;
6095 if (empty($replyto)) {
6096 $tempreplyto[] = array($from->email, fullname($from));
6098 } else {
6099 $mail->From = $noreplyaddress;
6100 $fromdetails = new stdClass();
6101 $fromdetails->name = fullname($from);
6102 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6103 $fromdetails->siteshortname = format_string($SITE->shortname);
6104 $fromstring = $fromdetails->name;
6105 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
6106 $fromstring = get_string('emailvia', 'core', $fromdetails);
6108 $mail->FromName = $fromstring;
6109 if (empty($replyto)) {
6110 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6114 if (!empty($replyto)) {
6115 $tempreplyto[] = array($replyto, $replytoname);
6118 $temprecipients[] = array($user->email, fullname($user));
6120 // Set word wrap.
6121 $mail->WordWrap = $wordwrapwidth;
6123 if (!empty($from->customheaders)) {
6124 // Add custom headers.
6125 if (is_array($from->customheaders)) {
6126 foreach ($from->customheaders as $customheader) {
6127 $mail->addCustomHeader($customheader);
6129 } else {
6130 $mail->addCustomHeader($from->customheaders);
6134 // If the X-PHP-Originating-Script email header is on then also add an additional
6135 // header with details of where exactly in moodle the email was triggered from,
6136 // either a call to message_send() or to email_to_user().
6137 if (ini_get('mail.add_x_header')) {
6139 $stack = debug_backtrace(false);
6140 $origin = $stack[0];
6142 foreach ($stack as $depth => $call) {
6143 if ($call['function'] == 'message_send') {
6144 $origin = $call;
6148 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6149 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6150 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6153 if (!empty($CFG->emailheaders)) {
6154 $headers = array_map('trim', explode("\n", $CFG->emailheaders));
6155 foreach ($headers as $header) {
6156 if (!empty($header)) {
6157 $mail->addCustomHeader($header);
6162 if (!empty($from->priority)) {
6163 $mail->Priority = $from->priority;
6166 $renderer = $PAGE->get_renderer('core');
6167 $context = array(
6168 'sitefullname' => $SITE->fullname,
6169 'siteshortname' => $SITE->shortname,
6170 'sitewwwroot' => $CFG->wwwroot,
6171 'subject' => $subject,
6172 'prefix' => $CFG->emailsubjectprefix,
6173 'to' => $user->email,
6174 'toname' => fullname($user),
6175 'from' => $mail->From,
6176 'fromname' => $mail->FromName,
6178 if (!empty($tempreplyto[0])) {
6179 $context['replyto'] = $tempreplyto[0][0];
6180 $context['replytoname'] = $tempreplyto[0][1];
6182 if ($user->id > 0) {
6183 $context['touserid'] = $user->id;
6184 $context['tousername'] = $user->username;
6187 if (!empty($user->mailformat) && $user->mailformat == 1) {
6188 // Only process html templates if the user preferences allow html email.
6190 if (!$messagehtml) {
6191 // If no html has been given, BUT there is an html wrapping template then
6192 // auto convert the text to html and then wrap it.
6193 $messagehtml = trim(text_to_html($messagetext));
6195 $context['body'] = $messagehtml;
6196 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6199 $context['body'] = html_to_text(nl2br($messagetext));
6200 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6201 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6202 $messagetext = $renderer->render_from_template('core/email_text', $context);
6204 // Autogenerate a MessageID if it's missing.
6205 if (empty($mail->MessageID)) {
6206 $mail->MessageID = generate_email_messageid();
6209 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6210 // Don't ever send HTML to users who don't want it.
6211 $mail->isHTML(true);
6212 $mail->Encoding = 'quoted-printable';
6213 $mail->Body = $messagehtml;
6214 $mail->AltBody = "\n$messagetext\n";
6215 } else {
6216 $mail->IsHTML(false);
6217 $mail->Body = "\n$messagetext\n";
6220 if ($attachment && $attachname) {
6221 if (preg_match( "~\\.\\.~" , $attachment )) {
6222 // Security check for ".." in dir path.
6223 $supportuser = core_user::get_support_user();
6224 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6225 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6226 } else {
6227 require_once($CFG->libdir.'/filelib.php');
6228 $mimetype = mimeinfo('type', $attachname);
6230 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6231 // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
6232 $attachpath = str_replace('\\', '/', realpath($attachment));
6234 // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
6235 $allowedpaths = array_map(function(string $path): string {
6236 return str_replace('\\', '/', realpath($path));
6237 }, [
6238 $CFG->cachedir,
6239 $CFG->dataroot,
6240 $CFG->dirroot,
6241 $CFG->localcachedir,
6242 $CFG->tempdir,
6243 $CFG->localrequestdir,
6246 // Set addpath to true.
6247 $addpath = true;
6249 // Check if attachment includes one of the allowed paths.
6250 foreach (array_filter($allowedpaths) as $allowedpath) {
6251 // Set addpath to false if the attachment includes one of the allowed paths.
6252 if (strpos($attachpath, $allowedpath) === 0) {
6253 $addpath = false;
6254 break;
6258 // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
6259 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6260 if ($addpath == true) {
6261 $attachment = $CFG->dataroot . '/' . $attachment;
6264 $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
6268 // Check if the email should be sent in an other charset then the default UTF-8.
6269 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6271 // Use the defined site mail charset or eventually the one preferred by the recipient.
6272 $charset = $CFG->sitemailcharset;
6273 if (!empty($CFG->allowusermailcharset)) {
6274 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6275 $charset = $useremailcharset;
6279 // Convert all the necessary strings if the charset is supported.
6280 $charsets = get_list_of_charsets();
6281 unset($charsets['UTF-8']);
6282 if (in_array($charset, $charsets)) {
6283 $mail->CharSet = $charset;
6284 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6285 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6286 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6287 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6289 foreach ($temprecipients as $key => $values) {
6290 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6292 foreach ($tempreplyto as $key => $values) {
6293 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6298 foreach ($temprecipients as $values) {
6299 $mail->addAddress($values[0], $values[1]);
6301 foreach ($tempreplyto as $values) {
6302 $mail->addReplyTo($values[0], $values[1]);
6305 if (!empty($CFG->emaildkimselector)) {
6306 $domain = substr(strrchr($mail->From, "@"), 1);
6307 $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
6308 if (file_exists($pempath)) {
6309 $mail->DKIM_domain = $domain;
6310 $mail->DKIM_private = $pempath;
6311 $mail->DKIM_selector = $CFG->emaildkimselector;
6312 $mail->DKIM_identity = $mail->From;
6313 } else {
6314 debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER);
6318 if ($mail->send()) {
6319 set_send_count($user);
6320 if (!empty($mail->SMTPDebug)) {
6321 echo '</pre>';
6323 return true;
6324 } else {
6325 // Trigger event for failing to send email.
6326 $event = \core\event\email_failed::create(array(
6327 'context' => context_system::instance(),
6328 'userid' => $from->id,
6329 'relateduserid' => $user->id,
6330 'other' => array(
6331 'subject' => $subject,
6332 'message' => $messagetext,
6333 'errorinfo' => $mail->ErrorInfo
6336 $event->trigger();
6337 if (CLI_SCRIPT) {
6338 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6340 if (!empty($mail->SMTPDebug)) {
6341 echo '</pre>';
6343 return false;
6348 * Check to see if a user's real email address should be used for the "From" field.
6350 * @param object $from The user object for the user we are sending the email from.
6351 * @param object $user The user object that we are sending the email to.
6352 * @param array $unused No longer used.
6353 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6355 function can_send_from_real_email_address($from, $user, $unused = null) {
6356 global $CFG;
6357 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6358 return false;
6360 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6361 // Email is in the list of allowed domains for sending email,
6362 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6363 // in a course with the sender.
6364 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6365 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6366 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6367 && enrol_get_shared_courses($user, $from, false, true)))) {
6368 return true;
6370 return false;
6374 * Generate a signoff for emails based on support settings
6376 * @return string
6378 function generate_email_signoff() {
6379 global $CFG, $OUTPUT;
6381 $signoff = "\n";
6382 if (!empty($CFG->supportname)) {
6383 $signoff .= $CFG->supportname."\n";
6386 $supportemail = $OUTPUT->supportemail(['class' => 'font-weight-bold']);
6388 if ($supportemail) {
6389 $signoff .= "\n" . $supportemail . "\n";
6392 return $signoff;
6396 * Sets specified user's password and send the new password to the user via email.
6398 * @param stdClass $user A {@link $USER} object
6399 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6400 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6402 function setnew_password_and_mail($user, $fasthash = false) {
6403 global $CFG, $DB;
6405 // We try to send the mail in language the user understands,
6406 // unfortunately the filter_string() does not support alternative langs yet
6407 // so multilang will not work properly for site->fullname.
6408 $lang = empty($user->lang) ? get_newuser_language() : $user->lang;
6410 $site = get_site();
6412 $supportuser = core_user::get_support_user();
6414 $newpassword = generate_password();
6416 update_internal_user_password($user, $newpassword, $fasthash);
6418 $a = new stdClass();
6419 $a->firstname = fullname($user, true);
6420 $a->sitename = format_string($site->fullname);
6421 $a->username = $user->username;
6422 $a->newpassword = $newpassword;
6423 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6424 $a->signoff = generate_email_signoff();
6426 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6428 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6430 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6431 return email_to_user($user, $supportuser, $subject, $message);
6436 * Resets specified user's password and send the new password to the user via email.
6438 * @param stdClass $user A {@link $USER} object
6439 * @return bool Returns true if mail was sent OK and false if there was an error.
6441 function reset_password_and_mail($user) {
6442 global $CFG;
6444 $site = get_site();
6445 $supportuser = core_user::get_support_user();
6447 $userauth = get_auth_plugin($user->auth);
6448 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6449 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6450 return false;
6453 $newpassword = generate_password();
6455 if (!$userauth->user_update_password($user, $newpassword)) {
6456 throw new \moodle_exception("cannotsetpassword");
6459 $a = new stdClass();
6460 $a->firstname = $user->firstname;
6461 $a->lastname = $user->lastname;
6462 $a->sitename = format_string($site->fullname);
6463 $a->username = $user->username;
6464 $a->newpassword = $newpassword;
6465 $a->link = $CFG->wwwroot .'/login/change_password.php';
6466 $a->signoff = generate_email_signoff();
6468 $message = get_string('newpasswordtext', '', $a);
6470 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6472 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6474 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6475 return email_to_user($user, $supportuser, $subject, $message);
6479 * Send email to specified user with confirmation text and activation link.
6481 * @param stdClass $user A {@link $USER} object
6482 * @param string $confirmationurl user confirmation URL
6483 * @return bool Returns true if mail was sent OK and false if there was an error.
6485 function send_confirmation_email($user, $confirmationurl = null) {
6486 global $CFG;
6488 $site = get_site();
6489 $supportuser = core_user::get_support_user();
6491 $data = new stdClass();
6492 $data->sitename = format_string($site->fullname);
6493 $data->admin = generate_email_signoff();
6495 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6497 if (empty($confirmationurl)) {
6498 $confirmationurl = '/login/confirm.php';
6501 $confirmationurl = new moodle_url($confirmationurl);
6502 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6503 $confirmationurl->remove_params('data');
6504 $confirmationpath = $confirmationurl->out(false);
6506 // We need to custom encode the username to include trailing dots in the link.
6507 // Because of this custom encoding we can't use moodle_url directly.
6508 // Determine if a query string is present in the confirmation url.
6509 $hasquerystring = strpos($confirmationpath, '?') !== false;
6510 // Perform normal url encoding of the username first.
6511 $username = urlencode($user->username);
6512 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6513 $username = str_replace('.', '%2E', $username);
6515 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6517 $message = get_string('emailconfirmation', '', $data);
6518 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6520 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6521 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6525 * Sends a password change confirmation email.
6527 * @param stdClass $user A {@link $USER} object
6528 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6529 * @return bool Returns true if mail was sent OK and false if there was an error.
6531 function send_password_change_confirmation_email($user, $resetrecord) {
6532 global $CFG;
6534 $site = get_site();
6535 $supportuser = core_user::get_support_user();
6536 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6538 $data = new stdClass();
6539 $data->firstname = $user->firstname;
6540 $data->lastname = $user->lastname;
6541 $data->username = $user->username;
6542 $data->sitename = format_string($site->fullname);
6543 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6544 $data->admin = generate_email_signoff();
6545 $data->resetminutes = $pwresetmins;
6547 $message = get_string('emailresetconfirmation', '', $data);
6548 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6550 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6551 return email_to_user($user, $supportuser, $subject, $message);
6556 * Sends an email containing information on how to change your password.
6558 * @param stdClass $user A {@link $USER} object
6559 * @return bool Returns true if mail was sent OK and false if there was an error.
6561 function send_password_change_info($user) {
6562 $site = get_site();
6563 $supportuser = core_user::get_support_user();
6565 $data = new stdClass();
6566 $data->firstname = $user->firstname;
6567 $data->lastname = $user->lastname;
6568 $data->username = $user->username;
6569 $data->sitename = format_string($site->fullname);
6570 $data->admin = generate_email_signoff();
6572 if (!is_enabled_auth($user->auth)) {
6573 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6574 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6575 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6576 return email_to_user($user, $supportuser, $subject, $message);
6579 $userauth = get_auth_plugin($user->auth);
6580 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6582 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6583 return email_to_user($user, $supportuser, $subject, $message);
6587 * Check that an email is allowed. It returns an error message if there was a problem.
6589 * @param string $email Content of email
6590 * @return string|false
6592 function email_is_not_allowed($email) {
6593 global $CFG;
6595 // Comparing lowercase domains.
6596 $email = strtolower($email);
6597 if (!empty($CFG->allowemailaddresses)) {
6598 $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6599 foreach ($allowed as $allowedpattern) {
6600 $allowedpattern = trim($allowedpattern);
6601 if (!$allowedpattern) {
6602 continue;
6604 if (strpos($allowedpattern, '.') === 0) {
6605 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6606 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6607 return false;
6610 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6611 return false;
6614 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6616 } else if (!empty($CFG->denyemailaddresses)) {
6617 $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6618 foreach ($denied as $deniedpattern) {
6619 $deniedpattern = trim($deniedpattern);
6620 if (!$deniedpattern) {
6621 continue;
6623 if (strpos($deniedpattern, '.') === 0) {
6624 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6625 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6626 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6629 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6630 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6635 return false;
6638 // FILE HANDLING.
6641 * Returns local file storage instance
6643 * @return file_storage
6645 function get_file_storage($reset = false) {
6646 global $CFG;
6648 static $fs = null;
6650 if ($reset) {
6651 $fs = null;
6652 return;
6655 if ($fs) {
6656 return $fs;
6659 require_once("$CFG->libdir/filelib.php");
6661 $fs = new file_storage();
6663 return $fs;
6667 * Returns local file storage instance
6669 * @return file_browser
6671 function get_file_browser() {
6672 global $CFG;
6674 static $fb = null;
6676 if ($fb) {
6677 return $fb;
6680 require_once("$CFG->libdir/filelib.php");
6682 $fb = new file_browser();
6684 return $fb;
6688 * Returns file packer
6690 * @param string $mimetype default application/zip
6691 * @return file_packer
6693 function get_file_packer($mimetype='application/zip') {
6694 global $CFG;
6696 static $fp = array();
6698 if (isset($fp[$mimetype])) {
6699 return $fp[$mimetype];
6702 switch ($mimetype) {
6703 case 'application/zip':
6704 case 'application/vnd.moodle.profiling':
6705 $classname = 'zip_packer';
6706 break;
6708 case 'application/x-gzip' :
6709 $classname = 'tgz_packer';
6710 break;
6712 case 'application/vnd.moodle.backup':
6713 $classname = 'mbz_packer';
6714 break;
6716 default:
6717 return false;
6720 require_once("$CFG->libdir/filestorage/$classname.php");
6721 $fp[$mimetype] = new $classname();
6723 return $fp[$mimetype];
6727 * Returns current name of file on disk if it exists.
6729 * @param string $newfile File to be verified
6730 * @return string Current name of file on disk if true
6732 function valid_uploaded_file($newfile) {
6733 if (empty($newfile)) {
6734 return '';
6736 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6737 return $newfile['tmp_name'];
6738 } else {
6739 return '';
6744 * Returns the maximum size for uploading files.
6746 * There are seven possible upload limits:
6747 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6748 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6749 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6750 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6751 * 5. by the Moodle admin in $CFG->maxbytes
6752 * 6. by the teacher in the current course $course->maxbytes
6753 * 7. by the teacher for the current module, eg $assignment->maxbytes
6755 * These last two are passed to this function as arguments (in bytes).
6756 * Anything defined as 0 is ignored.
6757 * The smallest of all the non-zero numbers is returned.
6759 * @todo Finish documenting this function
6761 * @param int $sitebytes Set maximum size
6762 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6763 * @param int $modulebytes Current module ->maxbytes (in bytes)
6764 * @param bool $unused This parameter has been deprecated and is not used any more.
6765 * @return int The maximum size for uploading files.
6767 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6769 if (! $filesize = ini_get('upload_max_filesize')) {
6770 $filesize = '5M';
6772 $minimumsize = get_real_size($filesize);
6774 if ($postsize = ini_get('post_max_size')) {
6775 $postsize = get_real_size($postsize);
6776 if ($postsize < $minimumsize) {
6777 $minimumsize = $postsize;
6781 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6782 $minimumsize = $sitebytes;
6785 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6786 $minimumsize = $coursebytes;
6789 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6790 $minimumsize = $modulebytes;
6793 return $minimumsize;
6797 * Returns the maximum size for uploading files for the current user
6799 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6801 * @param context $context The context in which to check user capabilities
6802 * @param int $sitebytes Set maximum size
6803 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6804 * @param int $modulebytes Current module ->maxbytes (in bytes)
6805 * @param stdClass $user The user
6806 * @param bool $unused This parameter has been deprecated and is not used any more.
6807 * @return int The maximum size for uploading files.
6809 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6810 $unused = false) {
6811 global $USER;
6813 if (empty($user)) {
6814 $user = $USER;
6817 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6818 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6821 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6825 * Returns an array of possible sizes in local language
6827 * Related to {@link get_max_upload_file_size()} - this function returns an
6828 * array of possible sizes in an array, translated to the
6829 * local language.
6831 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6833 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6834 * with the value set to 0. This option will be the first in the list.
6836 * @uses SORT_NUMERIC
6837 * @param int $sitebytes Set maximum size
6838 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6839 * @param int $modulebytes Current module ->maxbytes (in bytes)
6840 * @param int|array $custombytes custom upload size/s which will be added to list,
6841 * Only value/s smaller then maxsize will be added to list.
6842 * @return array
6844 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6845 global $CFG;
6847 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6848 return array();
6851 if ($sitebytes == 0) {
6852 // Will get the minimum of upload_max_filesize or post_max_size.
6853 $sitebytes = get_max_upload_file_size();
6856 $filesize = array();
6857 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6858 5242880, 10485760, 20971520, 52428800, 104857600,
6859 262144000, 524288000, 786432000, 1073741824,
6860 2147483648, 4294967296, 8589934592);
6862 // If custombytes is given and is valid then add it to the list.
6863 if (is_number($custombytes) and $custombytes > 0) {
6864 $custombytes = (int)$custombytes;
6865 if (!in_array($custombytes, $sizelist)) {
6866 $sizelist[] = $custombytes;
6868 } else if (is_array($custombytes)) {
6869 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6872 // Allow maxbytes to be selected if it falls outside the above boundaries.
6873 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6874 // Note: get_real_size() is used in order to prevent problems with invalid values.
6875 $sizelist[] = get_real_size($CFG->maxbytes);
6878 foreach ($sizelist as $sizebytes) {
6879 if ($sizebytes < $maxsize && $sizebytes > 0) {
6880 $filesize[(string)intval($sizebytes)] = display_size($sizebytes, 0);
6884 $limitlevel = '';
6885 $displaysize = '';
6886 if ($modulebytes &&
6887 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6888 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6889 $limitlevel = get_string('activity', 'core');
6890 $displaysize = display_size($modulebytes, 0);
6891 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6893 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6894 $limitlevel = get_string('course', 'core');
6895 $displaysize = display_size($coursebytes, 0);
6896 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6898 } else if ($sitebytes) {
6899 $limitlevel = get_string('site', 'core');
6900 $displaysize = display_size($sitebytes, 0);
6901 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6904 krsort($filesize, SORT_NUMERIC);
6905 if ($limitlevel) {
6906 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6907 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6910 return $filesize;
6914 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6916 * If excludefiles is defined, then that file/directory is ignored
6917 * If getdirs is true, then (sub)directories are included in the output
6918 * If getfiles is true, then files are included in the output
6919 * (at least one of these must be true!)
6921 * @todo Finish documenting this function. Add examples of $excludefile usage.
6923 * @param string $rootdir A given root directory to start from
6924 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6925 * @param bool $descend If true then subdirectories are recursed as well
6926 * @param bool $getdirs If true then (sub)directories are included in the output
6927 * @param bool $getfiles If true then files are included in the output
6928 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6930 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6932 $dirs = array();
6934 if (!$getdirs and !$getfiles) { // Nothing to show.
6935 return $dirs;
6938 if (!is_dir($rootdir)) { // Must be a directory.
6939 return $dirs;
6942 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6943 return $dirs;
6946 if (!is_array($excludefiles)) {
6947 $excludefiles = array($excludefiles);
6950 while (false !== ($file = readdir($dir))) {
6951 $firstchar = substr($file, 0, 1);
6952 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6953 continue;
6955 $fullfile = $rootdir .'/'. $file;
6956 if (filetype($fullfile) == 'dir') {
6957 if ($getdirs) {
6958 $dirs[] = $file;
6960 if ($descend) {
6961 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6962 foreach ($subdirs as $subdir) {
6963 $dirs[] = $file .'/'. $subdir;
6966 } else if ($getfiles) {
6967 $dirs[] = $file;
6970 closedir($dir);
6972 asort($dirs);
6974 return $dirs;
6979 * Adds up all the files in a directory and works out the size.
6981 * @param string $rootdir The directory to start from
6982 * @param string $excludefile A file to exclude when summing directory size
6983 * @return int The summed size of all files and subfiles within the root directory
6985 function get_directory_size($rootdir, $excludefile='') {
6986 global $CFG;
6988 // Do it this way if we can, it's much faster.
6989 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6990 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6991 $output = null;
6992 $return = null;
6993 exec($command, $output, $return);
6994 if (is_array($output)) {
6995 // We told it to return k.
6996 return get_real_size(intval($output[0]).'k');
7000 if (!is_dir($rootdir)) {
7001 // Must be a directory.
7002 return 0;
7005 if (!$dir = @opendir($rootdir)) {
7006 // Can't open it for some reason.
7007 return 0;
7010 $size = 0;
7012 while (false !== ($file = readdir($dir))) {
7013 $firstchar = substr($file, 0, 1);
7014 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
7015 continue;
7017 $fullfile = $rootdir .'/'. $file;
7018 if (filetype($fullfile) == 'dir') {
7019 $size += get_directory_size($fullfile, $excludefile);
7020 } else {
7021 $size += filesize($fullfile);
7024 closedir($dir);
7026 return $size;
7030 * Converts bytes into display form
7032 * @param int $size The size to convert to human readable form
7033 * @param int $decimalplaces If specified, uses fixed number of decimal places
7034 * @param string $fixedunits If specified, uses fixed units (e.g. 'KB')
7035 * @return string Display version of size
7037 function display_size($size, int $decimalplaces = 1, string $fixedunits = ''): string {
7039 static $units;
7041 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
7042 return get_string('unlimited');
7045 if (empty($units)) {
7046 $units[] = get_string('sizeb');
7047 $units[] = get_string('sizekb');
7048 $units[] = get_string('sizemb');
7049 $units[] = get_string('sizegb');
7050 $units[] = get_string('sizetb');
7051 $units[] = get_string('sizepb');
7054 switch ($fixedunits) {
7055 case 'PB' :
7056 $magnitude = 5;
7057 break;
7058 case 'TB' :
7059 $magnitude = 4;
7060 break;
7061 case 'GB' :
7062 $magnitude = 3;
7063 break;
7064 case 'MB' :
7065 $magnitude = 2;
7066 break;
7067 case 'KB' :
7068 $magnitude = 1;
7069 break;
7070 case 'B' :
7071 $magnitude = 0;
7072 break;
7073 case '':
7074 $magnitude = floor(log($size, 1024));
7075 $magnitude = max(0, min(5, $magnitude));
7076 break;
7077 default:
7078 throw new coding_exception('Unknown fixed units value: ' . $fixedunits);
7081 // Special case for magnitude 0 (bytes) - never use decimal places.
7082 $nbsp = "\xc2\xa0";
7083 if ($magnitude === 0) {
7084 return round($size) . $nbsp . $units[$magnitude];
7087 // Convert to specified units.
7088 $sizeinunit = $size / 1024 ** $magnitude;
7090 // Fixed decimal places.
7091 return sprintf('%.' . $decimalplaces . 'f', $sizeinunit) . $nbsp . $units[$magnitude];
7095 * Cleans a given filename by removing suspicious or troublesome characters
7097 * @see clean_param()
7098 * @param string $string file name
7099 * @return string cleaned file name
7101 function clean_filename($string) {
7102 return clean_param($string, PARAM_FILE);
7105 // STRING TRANSLATION.
7108 * Returns the code for the current language
7110 * @category string
7111 * @return string
7113 function current_language() {
7114 global $CFG, $PAGE, $SESSION, $USER;
7116 if (!empty($SESSION->forcelang)) {
7117 // Allows overriding course-forced language (useful for admins to check
7118 // issues in courses whose language they don't understand).
7119 // Also used by some code to temporarily get language-related information in a
7120 // specific language (see force_current_language()).
7121 $return = $SESSION->forcelang;
7123 } else if (!empty($PAGE->cm->lang)) {
7124 // Activity language, if set.
7125 $return = $PAGE->cm->lang;
7127 } else if (!empty($PAGE->course->id) && $PAGE->course->id != SITEID && !empty($PAGE->course->lang)) {
7128 // Course language can override all other settings for this page.
7129 $return = $PAGE->course->lang;
7131 } else if (!empty($SESSION->lang)) {
7132 // Session language can override other settings.
7133 $return = $SESSION->lang;
7135 } else if (!empty($USER->lang)) {
7136 $return = $USER->lang;
7138 } else if (isset($CFG->lang)) {
7139 $return = $CFG->lang;
7141 } else {
7142 $return = 'en';
7145 // Just in case this slipped in from somewhere by accident.
7146 $return = str_replace('_utf8', '', $return);
7148 return $return;
7152 * Fix the current language to the given language code.
7154 * @param string $lang The language code to use.
7155 * @return void
7157 function fix_current_language(string $lang): void {
7158 global $CFG, $COURSE, $SESSION, $USER;
7160 if (!get_string_manager()->translation_exists($lang)) {
7161 throw new coding_exception("The language pack for $lang is not available");
7164 $fixglobal = '';
7165 $fixlang = 'lang';
7166 if (!empty($SESSION->forcelang)) {
7167 $fixglobal = $SESSION;
7168 $fixlang = 'forcelang';
7169 } else if (!empty($COURSE->id) && $COURSE->id != SITEID && !empty($COURSE->lang)) {
7170 $fixglobal = $COURSE;
7171 } else if (!empty($SESSION->lang)) {
7172 $fixglobal = $SESSION;
7173 } else if (!empty($USER->lang)) {
7174 $fixglobal = $USER;
7175 } else if (isset($CFG->lang)) {
7176 set_config('lang', $lang);
7179 if ($fixglobal) {
7180 $fixglobal->$fixlang = $lang;
7185 * Returns parent language of current active language if defined
7187 * @category string
7188 * @param string $lang null means current language
7189 * @return string
7191 function get_parent_language($lang=null) {
7193 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7195 if ($parentlang === 'en') {
7196 $parentlang = '';
7199 return $parentlang;
7203 * Force the current language to get strings and dates localised in the given language.
7205 * After calling this function, all strings will be provided in the given language
7206 * until this function is called again, or equivalent code is run.
7208 * @param string $language
7209 * @return string previous $SESSION->forcelang value
7211 function force_current_language($language) {
7212 global $SESSION;
7213 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
7214 if ($language !== $sessionforcelang) {
7215 // Setting forcelang to null or an empty string disables its effect.
7216 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
7217 $SESSION->forcelang = $language;
7218 moodle_setlocale();
7221 return $sessionforcelang;
7225 * Returns current string_manager instance.
7227 * The param $forcereload is needed for CLI installer only where the string_manager instance
7228 * must be replaced during the install.php script life time.
7230 * @category string
7231 * @param bool $forcereload shall the singleton be released and new instance created instead?
7232 * @return core_string_manager
7234 function get_string_manager($forcereload=false) {
7235 global $CFG;
7237 static $singleton = null;
7239 if ($forcereload) {
7240 $singleton = null;
7242 if ($singleton === null) {
7243 if (empty($CFG->early_install_lang)) {
7245 $transaliases = array();
7246 if (empty($CFG->langlist)) {
7247 $translist = array();
7248 } else {
7249 $translist = explode(',', $CFG->langlist);
7250 $translist = array_map('trim', $translist);
7251 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7252 foreach ($translist as $i => $value) {
7253 $parts = preg_split('/\s*\|\s*/', $value, 2);
7254 if (count($parts) == 2) {
7255 $transaliases[$parts[0]] = $parts[1];
7256 $translist[$i] = $parts[0];
7261 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7262 $classname = $CFG->config_php_settings['customstringmanager'];
7264 if (class_exists($classname)) {
7265 $implements = class_implements($classname);
7267 if (isset($implements['core_string_manager'])) {
7268 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7269 return $singleton;
7271 } else {
7272 debugging('Unable to instantiate custom string manager: class '.$classname.
7273 ' does not implement the core_string_manager interface.');
7276 } else {
7277 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7281 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7283 } else {
7284 $singleton = new core_string_manager_install();
7288 return $singleton;
7292 * Returns a localized string.
7294 * Returns the translated string specified by $identifier as
7295 * for $module. Uses the same format files as STphp.
7296 * $a is an object, string or number that can be used
7297 * within translation strings
7299 * eg 'hello {$a->firstname} {$a->lastname}'
7300 * or 'hello {$a}'
7302 * If you would like to directly echo the localized string use
7303 * the function {@link print_string()}
7305 * Example usage of this function involves finding the string you would
7306 * like a local equivalent of and using its identifier and module information
7307 * to retrieve it.<br/>
7308 * If you open moodle/lang/en/moodle.php and look near line 278
7309 * you will find a string to prompt a user for their word for 'course'
7310 * <code>
7311 * $string['course'] = 'Course';
7312 * </code>
7313 * So if you want to display the string 'Course'
7314 * in any language that supports it on your site
7315 * you just need to use the identifier 'course'
7316 * <code>
7317 * $mystring = '<strong>'. get_string('course') .'</strong>';
7318 * or
7319 * </code>
7320 * If the string you want is in another file you'd take a slightly
7321 * different approach. Looking in moodle/lang/en/calendar.php you find
7322 * around line 75:
7323 * <code>
7324 * $string['typecourse'] = 'Course event';
7325 * </code>
7326 * If you want to display the string "Course event" in any language
7327 * supported you would use the identifier 'typecourse' and the module 'calendar'
7328 * (because it is in the file calendar.php):
7329 * <code>
7330 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7331 * </code>
7333 * As a last resort, should the identifier fail to map to a string
7334 * the returned string will be [[ $identifier ]]
7336 * In Moodle 2.3 there is a new argument to this function $lazyload.
7337 * Setting $lazyload to true causes get_string to return a lang_string object
7338 * rather than the string itself. The fetching of the string is then put off until
7339 * the string object is first used. The object can be used by calling it's out
7340 * method or by casting the object to a string, either directly e.g.
7341 * (string)$stringobject
7342 * or indirectly by using the string within another string or echoing it out e.g.
7343 * echo $stringobject
7344 * return "<p>{$stringobject}</p>";
7345 * It is worth noting that using $lazyload and attempting to use the string as an
7346 * array key will cause a fatal error as objects cannot be used as array keys.
7347 * But you should never do that anyway!
7348 * For more information {@link lang_string}
7350 * @category string
7351 * @param string $identifier The key identifier for the localized string
7352 * @param string $component The module where the key identifier is stored,
7353 * usually expressed as the filename in the language pack without the
7354 * .php on the end but can also be written as mod/forum or grade/export/xls.
7355 * If none is specified then moodle.php is used.
7356 * @param string|object|array|int $a An object, string or number that can be used
7357 * within translation strings
7358 * @param bool $lazyload If set to true a string object is returned instead of
7359 * the string itself. The string then isn't calculated until it is first used.
7360 * @return string The localized string.
7361 * @throws coding_exception
7363 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7364 global $CFG;
7366 // If the lazy load argument has been supplied return a lang_string object
7367 // instead.
7368 // We need to make sure it is true (and a bool) as you will see below there
7369 // used to be a forth argument at one point.
7370 if ($lazyload === true) {
7371 return new lang_string($identifier, $component, $a);
7374 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7375 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7378 // There is now a forth argument again, this time it is a boolean however so
7379 // we can still check for the old extralocations parameter.
7380 if (!is_bool($lazyload) && !empty($lazyload)) {
7381 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7384 if (strpos((string)$component, '/') !== false) {
7385 debugging('The module name you passed to get_string is the deprecated format ' .
7386 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7387 $componentpath = explode('/', $component);
7389 switch ($componentpath[0]) {
7390 case 'mod':
7391 $component = $componentpath[1];
7392 break;
7393 case 'blocks':
7394 case 'block':
7395 $component = 'block_'.$componentpath[1];
7396 break;
7397 case 'enrol':
7398 $component = 'enrol_'.$componentpath[1];
7399 break;
7400 case 'format':
7401 $component = 'format_'.$componentpath[1];
7402 break;
7403 case 'grade':
7404 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7405 break;
7409 $result = get_string_manager()->get_string($identifier, $component, $a);
7411 // Debugging feature lets you display string identifier and component.
7412 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7413 $result .= ' {' . $identifier . '/' . $component . '}';
7415 return $result;
7419 * Converts an array of strings to their localized value.
7421 * @param array $array An array of strings
7422 * @param string $component The language module that these strings can be found in.
7423 * @return stdClass translated strings.
7425 function get_strings($array, $component = '') {
7426 $string = new stdClass;
7427 foreach ($array as $item) {
7428 $string->$item = get_string($item, $component);
7430 return $string;
7434 * Prints out a translated string.
7436 * Prints out a translated string using the return value from the {@link get_string()} function.
7438 * Example usage of this function when the string is in the moodle.php file:<br/>
7439 * <code>
7440 * echo '<strong>';
7441 * print_string('course');
7442 * echo '</strong>';
7443 * </code>
7445 * Example usage of this function when the string is not in the moodle.php file:<br/>
7446 * <code>
7447 * echo '<h1>';
7448 * print_string('typecourse', 'calendar');
7449 * echo '</h1>';
7450 * </code>
7452 * @category string
7453 * @param string $identifier The key identifier for the localized string
7454 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7455 * @param string|object|array $a An object, string or number that can be used within translation strings
7457 function print_string($identifier, $component = '', $a = null) {
7458 echo get_string($identifier, $component, $a);
7462 * Returns a list of charset codes
7464 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7465 * (checking that such charset is supported by the texlib library!)
7467 * @return array And associative array with contents in the form of charset => charset
7469 function get_list_of_charsets() {
7471 $charsets = array(
7472 'EUC-JP' => 'EUC-JP',
7473 'ISO-2022-JP'=> 'ISO-2022-JP',
7474 'ISO-8859-1' => 'ISO-8859-1',
7475 'SHIFT-JIS' => 'SHIFT-JIS',
7476 'GB2312' => 'GB2312',
7477 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7478 'UTF-8' => 'UTF-8');
7480 asort($charsets);
7482 return $charsets;
7486 * Returns a list of valid and compatible themes
7488 * @return array
7490 function get_list_of_themes() {
7491 global $CFG;
7493 $themes = array();
7495 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7496 $themelist = explode(',', $CFG->themelist);
7497 } else {
7498 $themelist = array_keys(core_component::get_plugin_list("theme"));
7501 foreach ($themelist as $key => $themename) {
7502 $theme = theme_config::load($themename);
7503 $themes[$themename] = $theme;
7506 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7508 return $themes;
7512 * Factory function for emoticon_manager
7514 * @return emoticon_manager singleton
7516 function get_emoticon_manager() {
7517 static $singleton = null;
7519 if (is_null($singleton)) {
7520 $singleton = new emoticon_manager();
7523 return $singleton;
7527 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7529 * Whenever this manager mentiones 'emoticon object', the following data
7530 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7531 * altidentifier and altcomponent
7533 * @see admin_setting_emoticons
7535 * @copyright 2010 David Mudrak
7536 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7538 class emoticon_manager {
7541 * Returns the currently enabled emoticons
7543 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7544 * @return array of emoticon objects
7546 public function get_emoticons($selectable = false) {
7547 global $CFG;
7548 $notselectable = ['martin', 'egg'];
7550 if (empty($CFG->emoticons)) {
7551 return array();
7554 $emoticons = $this->decode_stored_config($CFG->emoticons);
7556 if (!is_array($emoticons)) {
7557 // Something is wrong with the format of stored setting.
7558 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7559 return array();
7561 if ($selectable) {
7562 foreach ($emoticons as $index => $emote) {
7563 if (in_array($emote->altidentifier, $notselectable)) {
7564 // Skip this one.
7565 unset($emoticons[$index]);
7570 return $emoticons;
7574 * Converts emoticon object into renderable pix_emoticon object
7576 * @param stdClass $emoticon emoticon object
7577 * @param array $attributes explicit HTML attributes to set
7578 * @return pix_emoticon
7580 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7581 $stringmanager = get_string_manager();
7582 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7583 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7584 } else {
7585 $alt = s($emoticon->text);
7587 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7591 * Encodes the array of emoticon objects into a string storable in config table
7593 * @see self::decode_stored_config()
7594 * @param array $emoticons array of emtocion objects
7595 * @return string
7597 public function encode_stored_config(array $emoticons) {
7598 return json_encode($emoticons);
7602 * Decodes the string into an array of emoticon objects
7604 * @see self::encode_stored_config()
7605 * @param string $encoded
7606 * @return array|null
7608 public function decode_stored_config($encoded) {
7609 $decoded = json_decode($encoded);
7610 if (!is_array($decoded)) {
7611 return null;
7613 return $decoded;
7617 * Returns default set of emoticons supported by Moodle
7619 * @return array of sdtClasses
7621 public function default_emoticons() {
7622 return array(
7623 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7624 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7625 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7626 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7627 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7628 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7629 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7630 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7631 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7632 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7633 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7634 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7635 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7636 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7637 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7638 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7639 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7640 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7641 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7642 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7643 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7644 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7645 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7646 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7647 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7648 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7649 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7650 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7651 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7652 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7657 * Helper method preparing the stdClass with the emoticon properties
7659 * @param string|array $text or array of strings
7660 * @param string $imagename to be used by {@link pix_emoticon}
7661 * @param string $altidentifier alternative string identifier, null for no alt
7662 * @param string $altcomponent where the alternative string is defined
7663 * @param string $imagecomponent to be used by {@link pix_emoticon}
7664 * @return stdClass
7666 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7667 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7668 return (object)array(
7669 'text' => $text,
7670 'imagename' => $imagename,
7671 'imagecomponent' => $imagecomponent,
7672 'altidentifier' => $altidentifier,
7673 'altcomponent' => $altcomponent,
7678 // ENCRYPTION.
7681 * rc4encrypt
7683 * @param string $data Data to encrypt.
7684 * @return string The now encrypted data.
7686 function rc4encrypt($data) {
7687 return endecrypt(get_site_identifier(), $data, '');
7691 * rc4decrypt
7693 * @param string $data Data to decrypt.
7694 * @return string The now decrypted data.
7696 function rc4decrypt($data) {
7697 return endecrypt(get_site_identifier(), $data, 'de');
7701 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7703 * @todo Finish documenting this function
7705 * @param string $pwd The password to use when encrypting or decrypting
7706 * @param string $data The data to be decrypted/encrypted
7707 * @param string $case Either 'de' for decrypt or '' for encrypt
7708 * @return string
7710 function endecrypt ($pwd, $data, $case) {
7712 if ($case == 'de') {
7713 $data = urldecode($data);
7716 $key[] = '';
7717 $box[] = '';
7718 $pwdlength = strlen($pwd);
7720 for ($i = 0; $i <= 255; $i++) {
7721 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7722 $box[$i] = $i;
7725 $x = 0;
7727 for ($i = 0; $i <= 255; $i++) {
7728 $x = ($x + $box[$i] + $key[$i]) % 256;
7729 $tempswap = $box[$i];
7730 $box[$i] = $box[$x];
7731 $box[$x] = $tempswap;
7734 $cipher = '';
7736 $a = 0;
7737 $j = 0;
7739 for ($i = 0; $i < strlen($data); $i++) {
7740 $a = ($a + 1) % 256;
7741 $j = ($j + $box[$a]) % 256;
7742 $temp = $box[$a];
7743 $box[$a] = $box[$j];
7744 $box[$j] = $temp;
7745 $k = $box[(($box[$a] + $box[$j]) % 256)];
7746 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7747 $cipher .= chr($cipherby);
7750 if ($case == 'de') {
7751 $cipher = urldecode(urlencode($cipher));
7752 } else {
7753 $cipher = urlencode($cipher);
7756 return $cipher;
7759 // ENVIRONMENT CHECKING.
7762 * This method validates a plug name. It is much faster than calling clean_param.
7764 * @param string $name a string that might be a plugin name.
7765 * @return bool if this string is a valid plugin name.
7767 function is_valid_plugin_name($name) {
7768 // This does not work for 'mod', bad luck, use any other type.
7769 return core_component::is_valid_plugin_name('tool', $name);
7773 * Get a list of all the plugins of a given type that define a certain API function
7774 * in a certain file. The plugin component names and function names are returned.
7776 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7777 * @param string $function the part of the name of the function after the
7778 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7779 * names like report_courselist_hook.
7780 * @param string $file the name of file within the plugin that defines the
7781 * function. Defaults to lib.php.
7782 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7783 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7785 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7786 global $CFG;
7788 // We don't include here as all plugin types files would be included.
7789 $plugins = get_plugins_with_function($function, $file, false);
7791 if (empty($plugins[$plugintype])) {
7792 return array();
7795 $allplugins = core_component::get_plugin_list($plugintype);
7797 // Reformat the array and include the files.
7798 $pluginfunctions = array();
7799 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7801 // Check that it has not been removed and the file is still available.
7802 if (!empty($allplugins[$pluginname])) {
7804 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7805 if (file_exists($filepath)) {
7806 include_once($filepath);
7808 // Now that the file is loaded, we must verify the function still exists.
7809 if (function_exists($functionname)) {
7810 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7811 } else {
7812 // Invalidate the cache for next run.
7813 \cache_helper::invalidate_by_definition('core', 'plugin_functions');
7819 return $pluginfunctions;
7823 * Get a list of all the plugins that define a certain API function in a certain file.
7825 * @param string $function the part of the name of the function after the
7826 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7827 * names like report_courselist_hook.
7828 * @param string $file the name of file within the plugin that defines the
7829 * function. Defaults to lib.php.
7830 * @param bool $include Whether to include the files that contain the functions or not.
7831 * @param bool $migratedtohook if true this is a deprecated lib.php callback, if hook callback is present then do nothing
7832 * @return array with [plugintype][plugin] = functionname
7834 function get_plugins_with_function($function, $file = 'lib.php', $include = true, bool $migratedtohook = false) {
7835 global $CFG;
7837 if (during_initial_install() || isset($CFG->upgraderunning)) {
7838 // API functions _must not_ be called during an installation or upgrade.
7839 return [];
7842 $plugincallback = $function;
7843 $filtermigrated = function($plugincallback, $pluginfunctions): array {
7844 foreach ($pluginfunctions as $plugintype => $plugins) {
7845 foreach ($plugins as $plugin => $unusedfunction) {
7846 $component = $plugintype . '_' . $plugin;
7847 if (\core\hook\manager::get_instance()->is_deprecated_plugin_callback($plugincallback)) {
7848 if (\core\hook\manager::get_instance()->is_deprecating_hook_present($component, $plugincallback)) {
7849 // Ignore the old callback, it is there only for older Moodle versions.
7850 unset($pluginfunctions[$plugintype][$plugin]);
7851 } else {
7852 debugging("Callback $plugincallback in $component component should be migrated to new hook callback",
7853 DEBUG_DEVELOPER);
7858 return $pluginfunctions;
7861 $cache = \cache::make('core', 'plugin_functions');
7863 // Including both although I doubt that we will find two functions definitions with the same name.
7864 // Clean the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7865 $pluginfunctions = false;
7866 if (!empty($CFG->allversionshash)) {
7867 $key = $CFG->allversionshash . '_' . $function . '_' . clean_param($file, PARAM_ALPHA);
7868 $pluginfunctions = $cache->get($key);
7870 $dirty = false;
7872 // Use the plugin manager to check that plugins are currently installed.
7873 $pluginmanager = \core_plugin_manager::instance();
7875 if ($pluginfunctions !== false) {
7877 // Checking that the files are still available.
7878 foreach ($pluginfunctions as $plugintype => $plugins) {
7880 $allplugins = \core_component::get_plugin_list($plugintype);
7881 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7882 foreach ($plugins as $plugin => $function) {
7883 if (!isset($installedplugins[$plugin])) {
7884 // Plugin code is still present on disk but it is not installed.
7885 $dirty = true;
7886 break 2;
7889 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7890 if (empty($allplugins[$plugin])) {
7891 $dirty = true;
7892 break 2;
7895 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7896 if ($include && $fileexists) {
7897 // Include the files if it was requested.
7898 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7899 } else if (!$fileexists) {
7900 // If the file is not available any more it should not be returned.
7901 $dirty = true;
7902 break 2;
7905 // Check if the function still exists in the file.
7906 if ($include && !function_exists($function)) {
7907 $dirty = true;
7908 break 2;
7913 // If the cache is dirty, we should fall through and let it rebuild.
7914 if (!$dirty) {
7915 if ($migratedtohook && $file === 'lib.php') {
7916 $pluginfunctions = $filtermigrated($plugincallback, $pluginfunctions);
7918 return $pluginfunctions;
7922 $pluginfunctions = array();
7924 // To fill the cached. Also, everything should continue working with cache disabled.
7925 $plugintypes = \core_component::get_plugin_types();
7926 foreach ($plugintypes as $plugintype => $unused) {
7928 // We need to include files here.
7929 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7930 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7931 foreach ($pluginswithfile as $plugin => $notused) {
7933 if (!isset($installedplugins[$plugin])) {
7934 continue;
7937 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7939 $pluginfunction = false;
7940 if (function_exists($fullfunction)) {
7941 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7942 $pluginfunction = $fullfunction;
7944 } else if ($plugintype === 'mod') {
7945 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7946 $shortfunction = $plugin . '_' . $function;
7947 if (function_exists($shortfunction)) {
7948 $pluginfunction = $shortfunction;
7952 if ($pluginfunction) {
7953 if (empty($pluginfunctions[$plugintype])) {
7954 $pluginfunctions[$plugintype] = array();
7956 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7961 if (!empty($CFG->allversionshash)) {
7962 $cache->set($key, $pluginfunctions);
7965 if ($migratedtohook && $file === 'lib.php') {
7966 $pluginfunctions = $filtermigrated($plugincallback, $pluginfunctions);
7969 return $pluginfunctions;
7974 * Lists plugin-like directories within specified directory
7976 * This function was originally used for standard Moodle plugins, please use
7977 * new core_component::get_plugin_list() now.
7979 * This function is used for general directory listing and backwards compatility.
7981 * @param string $directory relative directory from root
7982 * @param string $exclude dir name to exclude from the list (defaults to none)
7983 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7984 * @return array Sorted array of directory names found under the requested parameters
7986 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7987 global $CFG;
7989 $plugins = array();
7991 if (empty($basedir)) {
7992 $basedir = $CFG->dirroot .'/'. $directory;
7994 } else {
7995 $basedir = $basedir .'/'. $directory;
7998 if ($CFG->debugdeveloper and empty($exclude)) {
7999 // Make sure devs do not use this to list normal plugins,
8000 // this is intended for general directories that are not plugins!
8002 $subtypes = core_component::get_plugin_types();
8003 if (in_array($basedir, $subtypes)) {
8004 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
8006 unset($subtypes);
8009 $ignorelist = array_flip(array_filter([
8010 'CVS',
8011 '_vti_cnf',
8012 'amd',
8013 'classes',
8014 'simpletest',
8015 'tests',
8016 'templates',
8017 'yui',
8018 $exclude,
8019 ]));
8021 if (file_exists($basedir) && filetype($basedir) == 'dir') {
8022 if (!$dirhandle = opendir($basedir)) {
8023 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
8024 return array();
8026 while (false !== ($dir = readdir($dirhandle))) {
8027 if (strpos($dir, '.') === 0) {
8028 // Ignore directories starting with .
8029 // These are treated as hidden directories.
8030 continue;
8032 if (array_key_exists($dir, $ignorelist)) {
8033 // This directory features on the ignore list.
8034 continue;
8036 if (filetype($basedir .'/'. $dir) != 'dir') {
8037 continue;
8039 $plugins[] = $dir;
8041 closedir($dirhandle);
8043 if ($plugins) {
8044 asort($plugins);
8046 return $plugins;
8050 * Invoke plugin's callback functions
8052 * @param string $type plugin type e.g. 'mod'
8053 * @param string $name plugin name
8054 * @param string $feature feature name
8055 * @param string $action feature's action
8056 * @param array $params parameters of callback function, should be an array
8057 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
8058 * @param bool $migratedtohook if true this is a deprecated callback, if hook callback is present then do nothing
8059 * @return mixed
8061 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
8063 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null, bool $migratedtohook = false) {
8064 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default, $migratedtohook);
8068 * Invoke component's callback functions
8070 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8071 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8072 * @param array $params parameters of callback function
8073 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
8074 * @param bool $migratedtohook if true this is a deprecated callback, if hook callback is present then do nothing
8075 * @return mixed
8077 function component_callback($component, $function, array $params = array(), $default = null, bool $migratedtohook = false) {
8079 $functionname = component_callback_exists($component, $function);
8081 if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
8082 // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
8083 // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
8084 // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
8085 // This check can be removed when minimum PHP version for Moodle is raised to 8.
8086 debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
8087 DEBUG_DEVELOPER);
8088 $params = array_values($params);
8091 if ($functionname) {
8092 if ($migratedtohook) {
8093 if (\core\hook\manager::get_instance()->is_deprecated_plugin_callback($function)) {
8094 if (\core\hook\manager::get_instance()->is_deprecating_hook_present($component, $function)) {
8095 // Do not call the old lib.php callback,
8096 // it is there for compatibility with older Moodle versions only.
8097 return null;
8098 } else {
8099 debugging("Callback $function in $component component should be migrated to new hook callback",
8100 DEBUG_DEVELOPER);
8105 // Function exists, so just return function result.
8106 $ret = call_user_func_array($functionname, $params);
8107 if (is_null($ret)) {
8108 return $default;
8109 } else {
8110 return $ret;
8113 return $default;
8117 * Determine if a component callback exists and return the function name to call. Note that this
8118 * function will include the required library files so that the functioname returned can be
8119 * called directly.
8121 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8122 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8123 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
8124 * @throws coding_exception if invalid component specfied
8126 function component_callback_exists($component, $function) {
8127 global $CFG; // This is needed for the inclusions.
8129 $cleancomponent = clean_param($component, PARAM_COMPONENT);
8130 if (empty($cleancomponent)) {
8131 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8133 $component = $cleancomponent;
8135 list($type, $name) = core_component::normalize_component($component);
8136 $component = $type . '_' . $name;
8138 $oldfunction = $name.'_'.$function;
8139 $function = $component.'_'.$function;
8141 $dir = core_component::get_component_directory($component);
8142 if (empty($dir)) {
8143 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8146 // Load library and look for function.
8147 if (file_exists($dir.'/lib.php')) {
8148 require_once($dir.'/lib.php');
8151 if (!function_exists($function) and function_exists($oldfunction)) {
8152 if ($type !== 'mod' and $type !== 'core') {
8153 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
8155 $function = $oldfunction;
8158 if (function_exists($function)) {
8159 return $function;
8161 return false;
8165 * Call the specified callback method on the provided class.
8167 * If the callback returns null, then the default value is returned instead.
8168 * If the class does not exist, then the default value is returned.
8170 * @param string $classname The name of the class to call upon.
8171 * @param string $methodname The name of the staticically defined method on the class.
8172 * @param array $params The arguments to pass into the method.
8173 * @param mixed $default The default value.
8174 * @return mixed The return value.
8176 function component_class_callback($classname, $methodname, array $params, $default = null) {
8177 if (!class_exists($classname)) {
8178 return $default;
8181 if (!method_exists($classname, $methodname)) {
8182 return $default;
8185 $fullfunction = $classname . '::' . $methodname;
8186 $result = call_user_func_array($fullfunction, $params);
8188 if (null === $result) {
8189 return $default;
8190 } else {
8191 return $result;
8196 * Checks whether a plugin supports a specified feature.
8198 * @param string $type Plugin type e.g. 'mod'
8199 * @param string $name Plugin name e.g. 'forum'
8200 * @param string $feature Feature code (FEATURE_xx constant)
8201 * @param mixed $default default value if feature support unknown
8202 * @return mixed Feature result (false if not supported, null if feature is unknown,
8203 * otherwise usually true but may have other feature-specific value such as array)
8204 * @throws coding_exception
8206 function plugin_supports($type, $name, $feature, $default = null) {
8207 global $CFG;
8209 if ($type === 'mod' and $name === 'NEWMODULE') {
8210 // Somebody forgot to rename the module template.
8211 return false;
8214 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8215 if (empty($component)) {
8216 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8219 $function = null;
8221 if ($type === 'mod') {
8222 // We need this special case because we support subplugins in modules,
8223 // otherwise it would end up in infinite loop.
8224 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8225 include_once("$CFG->dirroot/mod/$name/lib.php");
8226 $function = $component.'_supports';
8227 if (!function_exists($function)) {
8228 // Legacy non-frankenstyle function name.
8229 $function = $name.'_supports';
8233 } else {
8234 if (!$path = core_component::get_plugin_directory($type, $name)) {
8235 // Non existent plugin type.
8236 return false;
8238 if (file_exists("$path/lib.php")) {
8239 include_once("$path/lib.php");
8240 $function = $component.'_supports';
8244 if ($function and function_exists($function)) {
8245 $supports = $function($feature);
8246 if (is_null($supports)) {
8247 // Plugin does not know - use default.
8248 return $default;
8249 } else {
8250 return $supports;
8254 // Plugin does not care, so use default.
8255 return $default;
8259 * Returns true if the current version of PHP is greater that the specified one.
8261 * @todo Check PHP version being required here is it too low?
8263 * @param string $version The version of php being tested.
8264 * @return bool
8266 function check_php_version($version='5.2.4') {
8267 return (version_compare(phpversion(), $version) >= 0);
8271 * Determine if moodle installation requires update.
8273 * Checks version numbers of main code and all plugins to see
8274 * if there are any mismatches.
8276 * @param bool $checkupgradeflag check the outagelessupgrade flag to see if an upgrade is running.
8277 * @return bool
8279 function moodle_needs_upgrading($checkupgradeflag = true) {
8280 global $CFG, $DB;
8282 // Say no if there is already an upgrade running.
8283 if ($checkupgradeflag) {
8284 $lock = $DB->get_field('config', 'value', ['name' => 'outagelessupgrade']);
8285 $currentprocessrunningupgrade = (defined('CLI_UPGRADE_RUNNING') && CLI_UPGRADE_RUNNING);
8286 // If we ARE locked, but this PHP process is NOT the process running the upgrade,
8287 // We should always return false.
8288 // This means the upgrade is running from CLI somewhere, or about to.
8289 if (!empty($lock) && !$currentprocessrunningupgrade) {
8290 return false;
8294 if (empty($CFG->version)) {
8295 return true;
8298 // There is no need to purge plugininfo caches here because
8299 // these caches are not used during upgrade and they are purged after
8300 // every upgrade.
8302 if (empty($CFG->allversionshash)) {
8303 return true;
8306 $hash = core_component::get_all_versions_hash();
8308 return ($hash !== $CFG->allversionshash);
8312 * Returns the major version of this site
8314 * Moodle version numbers consist of three numbers separated by a dot, for
8315 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8316 * called major version. This function extracts the major version from either
8317 * $CFG->release (default) or eventually from the $release variable defined in
8318 * the main version.php.
8320 * @param bool $fromdisk should the version if source code files be used
8321 * @return string|false the major version like '2.3', false if could not be determined
8323 function moodle_major_version($fromdisk = false) {
8324 global $CFG;
8326 if ($fromdisk) {
8327 $release = null;
8328 require($CFG->dirroot.'/version.php');
8329 if (empty($release)) {
8330 return false;
8333 } else {
8334 if (empty($CFG->release)) {
8335 return false;
8337 $release = $CFG->release;
8340 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8341 return $matches[0];
8342 } else {
8343 return false;
8347 // MISCELLANEOUS.
8350 * Gets the system locale
8352 * @return string Retuns the current locale.
8354 function moodle_getlocale() {
8355 global $CFG;
8357 // Fetch the correct locale based on ostype.
8358 if ($CFG->ostype == 'WINDOWS') {
8359 $stringtofetch = 'localewin';
8360 } else {
8361 $stringtofetch = 'locale';
8364 if (!empty($CFG->locale)) { // Override locale for all language packs.
8365 return $CFG->locale;
8368 return get_string($stringtofetch, 'langconfig');
8372 * Sets the system locale
8374 * @category string
8375 * @param string $locale Can be used to force a locale
8377 function moodle_setlocale($locale='') {
8378 global $CFG;
8380 static $currentlocale = ''; // Last locale caching.
8382 $oldlocale = $currentlocale;
8384 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8385 if (!empty($locale)) {
8386 $currentlocale = $locale;
8387 } else {
8388 $currentlocale = moodle_getlocale();
8391 // Do nothing if locale already set up.
8392 if ($oldlocale == $currentlocale) {
8393 return;
8396 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8397 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8398 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8400 // Get current values.
8401 $monetary= setlocale (LC_MONETARY, 0);
8402 $numeric = setlocale (LC_NUMERIC, 0);
8403 $ctype = setlocale (LC_CTYPE, 0);
8404 if ($CFG->ostype != 'WINDOWS') {
8405 $messages= setlocale (LC_MESSAGES, 0);
8407 // Set locale to all.
8408 $result = setlocale (LC_ALL, $currentlocale);
8409 // If setting of locale fails try the other utf8 or utf-8 variant,
8410 // some operating systems support both (Debian), others just one (OSX).
8411 if ($result === false) {
8412 if (stripos($currentlocale, '.UTF-8') !== false) {
8413 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8414 setlocale (LC_ALL, $newlocale);
8415 } else if (stripos($currentlocale, '.UTF8') !== false) {
8416 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8417 setlocale (LC_ALL, $newlocale);
8420 // Set old values.
8421 setlocale (LC_MONETARY, $monetary);
8422 setlocale (LC_NUMERIC, $numeric);
8423 if ($CFG->ostype != 'WINDOWS') {
8424 setlocale (LC_MESSAGES, $messages);
8426 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8427 // To workaround a well-known PHP problem with Turkish letter Ii.
8428 setlocale (LC_CTYPE, $ctype);
8433 * Count words in a string.
8435 * Words are defined as things between whitespace.
8437 * @category string
8438 * @param string $string The text to be searched for words. May be HTML.
8439 * @param int|null $format
8440 * @return int The count of words in the specified string
8442 function count_words($string, $format = null) {
8443 // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8444 // Also, br is a special case because it definitely delimits a word, but has no close tag.
8445 $string = preg_replace('~
8446 ( # Capture the tag we match.
8447 </ # Start of close tag.
8448 (?! # Do not match any of these specific close tag names.
8449 a> | b> | del> | em> | i> |
8450 ins> | s> | small> | span> |
8451 strong> | sub> | sup> | u>
8453 \w+ # But, apart from those execptions, match any tag name.
8454 > # End of close tag.
8456 <br> | <br\s*/> # Special cases that are not close tags.
8458 ~x', '$1 ', $string); // Add a space after the close tag.
8459 if ($format !== null && $format != FORMAT_PLAIN) {
8460 // Match the usual text cleaning before display.
8461 // Ideally we should apply multilang filter only here, other filters might add extra text.
8462 $string = format_text($string, $format, ['filter' => false, 'noclean' => false, 'para' => false]);
8464 // Now remove HTML tags.
8465 $string = strip_tags($string);
8466 // Decode HTML entities.
8467 $string = html_entity_decode($string, ENT_COMPAT);
8469 // Now, the word count is the number of blocks of characters separated
8470 // by any sort of space. That seems to be the definition used by all other systems.
8471 // To be precise about what is considered to separate words:
8472 // * Anything that Unicode considers a 'Separator'
8473 // * Anything that Unicode considers a 'Control character'
8474 // * An em- or en- dash.
8475 return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY));
8479 * Count letters in a string.
8481 * Letters are defined as chars not in tags and different from whitespace.
8483 * @category string
8484 * @param string $string The text to be searched for letters. May be HTML.
8485 * @param int|null $format
8486 * @return int The count of letters in the specified text.
8488 function count_letters($string, $format = null) {
8489 if ($format !== null && $format != FORMAT_PLAIN) {
8490 // Match the usual text cleaning before display.
8491 // Ideally we should apply multilang filter only here, other filters might add extra text.
8492 $string = format_text($string, $format, ['filter' => false, 'noclean' => false, 'para' => false]);
8494 $string = strip_tags($string); // Tags are out now.
8495 $string = html_entity_decode($string, ENT_COMPAT);
8496 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8498 return core_text::strlen($string);
8502 * Generate and return a random string of the specified length.
8504 * @param int $length The length of the string to be created.
8505 * @return string
8507 function random_string($length=15) {
8508 $randombytes = random_bytes($length);
8509 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8510 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8511 $pool .= '0123456789';
8512 $poollen = strlen($pool);
8513 $string = '';
8514 for ($i = 0; $i < $length; $i++) {
8515 $rand = ord($randombytes[$i]);
8516 $string .= substr($pool, ($rand%($poollen)), 1);
8518 return $string;
8522 * Generate a complex random string (useful for md5 salts)
8524 * This function is based on the above {@link random_string()} however it uses a
8525 * larger pool of characters and generates a string between 24 and 32 characters
8527 * @param int $length Optional if set generates a string to exactly this length
8528 * @return string
8530 function complex_random_string($length=null) {
8531 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8532 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8533 $poollen = strlen($pool);
8534 if ($length===null) {
8535 $length = floor(rand(24, 32));
8537 $randombytes = random_bytes($length);
8538 $string = '';
8539 for ($i = 0; $i < $length; $i++) {
8540 $rand = ord($randombytes[$i]);
8541 $string .= $pool[($rand%$poollen)];
8543 return $string;
8547 * Given some text (which may contain HTML) and an ideal length,
8548 * this function truncates the text neatly on a word boundary if possible
8550 * @category string
8551 * @param string $text text to be shortened
8552 * @param int $ideal ideal string length
8553 * @param boolean $exact if false, $text will not be cut mid-word
8554 * @param string $ending The string to append if the passed string is truncated
8555 * @return string $truncate shortened string
8557 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8558 // If the plain text is shorter than the maximum length, return the whole text.
8559 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8560 return $text;
8563 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8564 // and only tag in its 'line'.
8565 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8567 $totallength = core_text::strlen($ending);
8568 $truncate = '';
8570 // This array stores information about open and close tags and their position
8571 // in the truncated string. Each item in the array is an object with fields
8572 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8573 // (byte position in truncated text).
8574 $tagdetails = array();
8576 foreach ($lines as $linematchings) {
8577 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8578 if (!empty($linematchings[1])) {
8579 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8580 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8581 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8582 // Record closing tag.
8583 $tagdetails[] = (object) array(
8584 'open' => false,
8585 'tag' => core_text::strtolower($tagmatchings[1]),
8586 'pos' => core_text::strlen($truncate),
8589 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8590 // Record opening tag.
8591 $tagdetails[] = (object) array(
8592 'open' => true,
8593 'tag' => core_text::strtolower($tagmatchings[1]),
8594 'pos' => core_text::strlen($truncate),
8596 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8597 $tagdetails[] = (object) array(
8598 'open' => true,
8599 'tag' => core_text::strtolower('if'),
8600 'pos' => core_text::strlen($truncate),
8602 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8603 $tagdetails[] = (object) array(
8604 'open' => false,
8605 'tag' => core_text::strtolower('if'),
8606 'pos' => core_text::strlen($truncate),
8610 // Add html-tag to $truncate'd text.
8611 $truncate .= $linematchings[1];
8614 // Calculate the length of the plain text part of the line; handle entities as one character.
8615 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8616 if ($totallength + $contentlength > $ideal) {
8617 // The number of characters which are left.
8618 $left = $ideal - $totallength;
8619 $entitieslength = 0;
8620 // Search for html entities.
8621 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)) {
8622 // Calculate the real length of all entities in the legal range.
8623 foreach ($entities[0] as $entity) {
8624 if ($entity[1]+1-$entitieslength <= $left) {
8625 $left--;
8626 $entitieslength += core_text::strlen($entity[0]);
8627 } else {
8628 // No more characters left.
8629 break;
8633 $breakpos = $left + $entitieslength;
8635 // If the words shouldn't be cut in the middle...
8636 if (!$exact) {
8637 // Search the last occurence of a space.
8638 for (; $breakpos > 0; $breakpos--) {
8639 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8640 if ($char === '.' or $char === ' ') {
8641 $breakpos += 1;
8642 break;
8643 } else if (strlen($char) > 2) {
8644 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8645 $breakpos += 1;
8646 break;
8651 if ($breakpos == 0) {
8652 // This deals with the test_shorten_text_no_spaces case.
8653 $breakpos = $left + $entitieslength;
8654 } else if ($breakpos > $left + $entitieslength) {
8655 // This deals with the previous for loop breaking on the first char.
8656 $breakpos = $left + $entitieslength;
8659 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8660 // Maximum length is reached, so get off the loop.
8661 break;
8662 } else {
8663 $truncate .= $linematchings[2];
8664 $totallength += $contentlength;
8667 // If the maximum length is reached, get off the loop.
8668 if ($totallength >= $ideal) {
8669 break;
8673 // Add the defined ending to the text.
8674 $truncate .= $ending;
8676 // Now calculate the list of open html tags based on the truncate position.
8677 $opentags = array();
8678 foreach ($tagdetails as $taginfo) {
8679 if ($taginfo->open) {
8680 // Add tag to the beginning of $opentags list.
8681 array_unshift($opentags, $taginfo->tag);
8682 } else {
8683 // Can have multiple exact same open tags, close the last one.
8684 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8685 if ($pos !== false) {
8686 unset($opentags[$pos]);
8691 // Close all unclosed html-tags.
8692 foreach ($opentags as $tag) {
8693 if ($tag === 'if') {
8694 $truncate .= '<!--<![endif]-->';
8695 } else {
8696 $truncate .= '</' . $tag . '>';
8700 return $truncate;
8704 * Shortens a given filename by removing characters positioned after the ideal string length.
8705 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8706 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8708 * @param string $filename file name
8709 * @param int $length ideal string length
8710 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8711 * @return string $shortened shortened file name
8713 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8714 $shortened = $filename;
8715 // Extract a part of the filename if it's char size exceeds the ideal string length.
8716 if (core_text::strlen($filename) > $length) {
8717 // Exclude extension if present in filename.
8718 $mimetypes = get_mimetypes_array();
8719 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8720 if ($extension && !empty($mimetypes[$extension])) {
8721 $basename = pathinfo($filename, PATHINFO_FILENAME);
8722 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8723 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8724 $shortened .= '.' . $extension;
8725 } else {
8726 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8727 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8730 return $shortened;
8734 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8736 * @param array $path The paths to reduce the length.
8737 * @param int $length Ideal string length
8738 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8739 * @return array $result Shortened paths in array.
8741 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8742 $result = null;
8744 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8745 $carry[] = shorten_filename($singlepath, $length, $includehash);
8746 return $carry;
8747 }, []);
8749 return $result;
8753 * Given dates in seconds, how many weeks is the date from startdate
8754 * The first week is 1, the second 2 etc ...
8756 * @param int $startdate Timestamp for the start date
8757 * @param int $thedate Timestamp for the end date
8758 * @return string
8760 function getweek ($startdate, $thedate) {
8761 if ($thedate < $startdate) {
8762 return 0;
8765 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8769 * Returns a randomly generated password of length $maxlen. inspired by
8771 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8772 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8774 * @param int $maxlen The maximum size of the password being generated.
8775 * @return string
8777 function generate_password($maxlen=10) {
8778 global $CFG;
8780 if (empty($CFG->passwordpolicy)) {
8781 $fillers = PASSWORD_DIGITS;
8782 $wordlist = file($CFG->wordlist);
8783 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8784 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8785 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8786 $password = $word1 . $filler1 . $word2;
8787 } else {
8788 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8789 $digits = $CFG->minpassworddigits;
8790 $lower = $CFG->minpasswordlower;
8791 $upper = $CFG->minpasswordupper;
8792 $nonalphanum = $CFG->minpasswordnonalphanum;
8793 $total = $lower + $upper + $digits + $nonalphanum;
8794 // Var minlength should be the greater one of the two ( $minlen and $total ).
8795 $minlen = $minlen < $total ? $total : $minlen;
8796 // Var maxlen can never be smaller than minlen.
8797 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8798 $additional = $maxlen - $total;
8800 // Make sure we have enough characters to fulfill
8801 // complexity requirements.
8802 $passworddigits = PASSWORD_DIGITS;
8803 while ($digits > strlen($passworddigits)) {
8804 $passworddigits .= PASSWORD_DIGITS;
8806 $passwordlower = PASSWORD_LOWER;
8807 while ($lower > strlen($passwordlower)) {
8808 $passwordlower .= PASSWORD_LOWER;
8810 $passwordupper = PASSWORD_UPPER;
8811 while ($upper > strlen($passwordupper)) {
8812 $passwordupper .= PASSWORD_UPPER;
8814 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8815 while ($nonalphanum > strlen($passwordnonalphanum)) {
8816 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8819 // Now mix and shuffle it all.
8820 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8821 substr(str_shuffle ($passwordupper), 0, $upper) .
8822 substr(str_shuffle ($passworddigits), 0, $digits) .
8823 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8824 substr(str_shuffle ($passwordlower .
8825 $passwordupper .
8826 $passworddigits .
8827 $passwordnonalphanum), 0 , $additional));
8830 return substr ($password, 0, $maxlen);
8834 * Given a float, prints it nicely.
8835 * Localized floats must not be used in calculations!
8837 * The stripzeros feature is intended for making numbers look nicer in small
8838 * areas where it is not necessary to indicate the degree of accuracy by showing
8839 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8840 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8842 * @param float $float The float to print
8843 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8844 * @param bool $localized use localized decimal separator
8845 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8846 * the decimal point are always striped if $decimalpoints is -1.
8847 * @return string locale float
8849 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8850 if (is_null($float)) {
8851 return '';
8853 if ($localized) {
8854 $separator = get_string('decsep', 'langconfig');
8855 } else {
8856 $separator = '.';
8858 if ($decimalpoints == -1) {
8859 // The following counts the number of decimals.
8860 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8861 $floatval = floatval($float);
8862 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
8865 $result = number_format($float, $decimalpoints, $separator, '');
8866 if ($stripzeros && $decimalpoints > 0) {
8867 // Remove zeros and final dot if not needed.
8868 // However, only do this if there is a decimal point!
8869 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8871 return $result;
8875 * Converts locale specific floating point/comma number back to standard PHP float value
8876 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8878 * @param string $localefloat locale aware float representation
8879 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8880 * @return mixed float|bool - false or the parsed float.
8882 function unformat_float($localefloat, $strict = false) {
8883 $localefloat = trim((string)$localefloat);
8885 if ($localefloat == '') {
8886 return null;
8889 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8890 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8892 if ($strict && !is_numeric($localefloat)) {
8893 return false;
8896 return (float)$localefloat;
8900 * Given a simple array, this shuffles it up just like shuffle()
8901 * Unlike PHP's shuffle() this function works on any machine.
8903 * @param array $array The array to be rearranged
8904 * @return array
8906 function swapshuffle($array) {
8908 $last = count($array) - 1;
8909 for ($i = 0; $i <= $last; $i++) {
8910 $from = rand(0, $last);
8911 $curr = $array[$i];
8912 $array[$i] = $array[$from];
8913 $array[$from] = $curr;
8915 return $array;
8919 * Like {@link swapshuffle()}, but works on associative arrays
8921 * @param array $array The associative array to be rearranged
8922 * @return array
8924 function swapshuffle_assoc($array) {
8926 $newarray = array();
8927 $newkeys = swapshuffle(array_keys($array));
8929 foreach ($newkeys as $newkey) {
8930 $newarray[$newkey] = $array[$newkey];
8932 return $newarray;
8936 * Given an arbitrary array, and a number of draws,
8937 * this function returns an array with that amount
8938 * of items. The indexes are retained.
8940 * @todo Finish documenting this function
8942 * @param array $array
8943 * @param int $draws
8944 * @return array
8946 function draw_rand_array($array, $draws) {
8948 $return = array();
8950 $last = count($array);
8952 if ($draws > $last) {
8953 $draws = $last;
8956 while ($draws > 0) {
8957 $last--;
8959 $keys = array_keys($array);
8960 $rand = rand(0, $last);
8962 $return[$keys[$rand]] = $array[$keys[$rand]];
8963 unset($array[$keys[$rand]]);
8965 $draws--;
8968 return $return;
8972 * Calculate the difference between two microtimes
8974 * @param string $a The first Microtime
8975 * @param string $b The second Microtime
8976 * @return string
8978 function microtime_diff($a, $b) {
8979 list($adec, $asec) = explode(' ', $a);
8980 list($bdec, $bsec) = explode(' ', $b);
8981 return $bsec - $asec + $bdec - $adec;
8985 * Given a list (eg a,b,c,d,e) this function returns
8986 * an array of 1->a, 2->b, 3->c etc
8988 * @param string $list The string to explode into array bits
8989 * @param string $separator The separator used within the list string
8990 * @return array The now assembled array
8992 function make_menu_from_list($list, $separator=',') {
8994 $array = array_reverse(explode($separator, $list), true);
8995 foreach ($array as $key => $item) {
8996 $outarray[$key+1] = trim($item);
8998 return $outarray;
9002 * Creates an array that represents all the current grades that
9003 * can be chosen using the given grading type.
9005 * Negative numbers
9006 * are scales, zero is no grade, and positive numbers are maximum
9007 * grades.
9009 * @todo Finish documenting this function or better deprecated this completely!
9011 * @param int $gradingtype
9012 * @return array
9014 function make_grades_menu($gradingtype) {
9015 global $DB;
9017 $grades = array();
9018 if ($gradingtype < 0) {
9019 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
9020 return make_menu_from_list($scale->scale);
9022 } else if ($gradingtype > 0) {
9023 for ($i=$gradingtype; $i>=0; $i--) {
9024 $grades[$i] = $i .' / '. $gradingtype;
9026 return $grades;
9028 return $grades;
9032 * make_unique_id_code
9034 * @todo Finish documenting this function
9036 * @uses $_SERVER
9037 * @param string $extra Extra string to append to the end of the code
9038 * @return string
9040 function make_unique_id_code($extra = '') {
9042 $hostname = 'unknownhost';
9043 if (!empty($_SERVER['HTTP_HOST'])) {
9044 $hostname = $_SERVER['HTTP_HOST'];
9045 } else if (!empty($_ENV['HTTP_HOST'])) {
9046 $hostname = $_ENV['HTTP_HOST'];
9047 } else if (!empty($_SERVER['SERVER_NAME'])) {
9048 $hostname = $_SERVER['SERVER_NAME'];
9049 } else if (!empty($_ENV['SERVER_NAME'])) {
9050 $hostname = $_ENV['SERVER_NAME'];
9053 $date = gmdate("ymdHis");
9055 $random = random_string(6);
9057 if ($extra) {
9058 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
9059 } else {
9060 return $hostname .'+'. $date .'+'. $random;
9066 * Function to check the passed address is within the passed subnet
9068 * The parameter is a comma separated string of subnet definitions.
9069 * Subnet strings can be in one of three formats:
9070 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
9071 * 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)
9072 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
9073 * Code for type 1 modified from user posted comments by mediator at
9074 * {@link http://au.php.net/manual/en/function.ip2long.php}
9076 * @param string $addr The address you are checking
9077 * @param string $subnetstr The string of subnet addresses
9078 * @param bool $checkallzeros The state to whether check for 0.0.0.0
9079 * @return bool
9081 function address_in_subnet($addr, $subnetstr, $checkallzeros = false) {
9083 if ($addr == '0.0.0.0' && !$checkallzeros) {
9084 return false;
9086 $subnets = explode(',', $subnetstr);
9087 $found = false;
9088 $addr = trim($addr);
9089 $addr = cleanremoteaddr($addr, false); // Normalise.
9090 if ($addr === null) {
9091 return false;
9093 $addrparts = explode(':', $addr);
9095 $ipv6 = strpos($addr, ':');
9097 foreach ($subnets as $subnet) {
9098 $subnet = trim($subnet);
9099 if ($subnet === '') {
9100 continue;
9103 if (strpos($subnet, '/') !== false) {
9104 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
9105 list($ip, $mask) = explode('/', $subnet);
9106 $mask = trim($mask);
9107 if (!is_number($mask)) {
9108 continue; // Incorect mask number, eh?
9110 $ip = cleanremoteaddr($ip, false); // Normalise.
9111 if ($ip === null) {
9112 continue;
9114 if (strpos($ip, ':') !== false) {
9115 // IPv6.
9116 if (!$ipv6) {
9117 continue;
9119 if ($mask > 128 or $mask < 0) {
9120 continue; // Nonsense.
9122 if ($mask == 0) {
9123 return true; // Any address.
9125 if ($mask == 128) {
9126 if ($ip === $addr) {
9127 return true;
9129 continue;
9131 $ipparts = explode(':', $ip);
9132 $modulo = $mask % 16;
9133 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9134 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9135 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9136 if ($modulo == 0) {
9137 return true;
9139 $pos = ($mask-$modulo)/16;
9140 $ipnet = hexdec($ipparts[$pos]);
9141 $addrnet = hexdec($addrparts[$pos]);
9142 $mask = 0xffff << (16 - $modulo);
9143 if (($addrnet & $mask) == ($ipnet & $mask)) {
9144 return true;
9148 } else {
9149 // IPv4.
9150 if ($ipv6) {
9151 continue;
9153 if ($mask > 32 or $mask < 0) {
9154 continue; // Nonsense.
9156 if ($mask == 0) {
9157 return true;
9159 if ($mask == 32) {
9160 if ($ip === $addr) {
9161 return true;
9163 continue;
9165 $mask = 0xffffffff << (32 - $mask);
9166 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9167 return true;
9171 } else if (strpos($subnet, '-') !== false) {
9172 // 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.
9173 $parts = explode('-', $subnet);
9174 if (count($parts) != 2) {
9175 continue;
9178 if (strpos($subnet, ':') !== false) {
9179 // IPv6.
9180 if (!$ipv6) {
9181 continue;
9183 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9184 if ($ipstart === null) {
9185 continue;
9187 $ipparts = explode(':', $ipstart);
9188 $start = hexdec(array_pop($ipparts));
9189 $ipparts[] = trim($parts[1]);
9190 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9191 if ($ipend === null) {
9192 continue;
9194 $ipparts[7] = '';
9195 $ipnet = implode(':', $ipparts);
9196 if (strpos($addr, $ipnet) !== 0) {
9197 continue;
9199 $ipparts = explode(':', $ipend);
9200 $end = hexdec($ipparts[7]);
9202 $addrend = hexdec($addrparts[7]);
9204 if (($addrend >= $start) and ($addrend <= $end)) {
9205 return true;
9208 } else {
9209 // IPv4.
9210 if ($ipv6) {
9211 continue;
9213 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9214 if ($ipstart === null) {
9215 continue;
9217 $ipparts = explode('.', $ipstart);
9218 $ipparts[3] = trim($parts[1]);
9219 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9220 if ($ipend === null) {
9221 continue;
9224 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9225 return true;
9229 } else {
9230 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9231 if (strpos($subnet, ':') !== false) {
9232 // IPv6.
9233 if (!$ipv6) {
9234 continue;
9236 $parts = explode(':', $subnet);
9237 $count = count($parts);
9238 if ($parts[$count-1] === '') {
9239 unset($parts[$count-1]); // Trim trailing :'s.
9240 $count--;
9241 $subnet = implode('.', $parts);
9243 $isip = cleanremoteaddr($subnet, false); // Normalise.
9244 if ($isip !== null) {
9245 if ($isip === $addr) {
9246 return true;
9248 continue;
9249 } else if ($count > 8) {
9250 continue;
9252 $zeros = array_fill(0, 8-$count, '0');
9253 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9254 if (address_in_subnet($addr, $subnet)) {
9255 return true;
9258 } else {
9259 // IPv4.
9260 if ($ipv6) {
9261 continue;
9263 $parts = explode('.', $subnet);
9264 $count = count($parts);
9265 if ($parts[$count-1] === '') {
9266 unset($parts[$count-1]); // Trim trailing .
9267 $count--;
9268 $subnet = implode('.', $parts);
9270 if ($count == 4) {
9271 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9272 if ($subnet === $addr) {
9273 return true;
9275 continue;
9276 } else if ($count > 4) {
9277 continue;
9279 $zeros = array_fill(0, 4-$count, '0');
9280 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9281 if (address_in_subnet($addr, $subnet)) {
9282 return true;
9288 return false;
9292 * For outputting debugging info
9294 * @param string $string The string to write
9295 * @param string $eol The end of line char(s) to use
9296 * @param string $sleep Period to make the application sleep
9297 * This ensures any messages have time to display before redirect
9299 function mtrace($string, $eol="\n", $sleep=0) {
9300 global $CFG;
9302 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
9303 $fn = $CFG->mtrace_wrapper;
9304 $fn($string, $eol);
9305 return;
9306 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
9307 // We must explicitly call the add_line function here.
9308 // Uses of fwrite to STDOUT are not picked up by ob_start.
9309 if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
9310 fwrite(STDOUT, $output);
9312 } else {
9313 echo $string . $eol;
9316 // Flush again.
9317 flush();
9319 // Delay to keep message on user's screen in case of subsequent redirect.
9320 if ($sleep) {
9321 sleep($sleep);
9326 * Helper to {@see mtrace()} an exception or throwable, including all relevant information.
9328 * @param Throwable $e the error to ouptput.
9330 function mtrace_exception(Throwable $e): void {
9331 $info = get_exception_info($e);
9333 $message = $info->message;
9334 if ($info->debuginfo) {
9335 $message .= "\n\n" . $info->debuginfo;
9337 if ($info->backtrace) {
9338 $message .= "\n\n" . format_backtrace($info->backtrace, true);
9341 mtrace($message);
9345 * Replace 1 or more slashes or backslashes to 1 slash
9347 * @param string $path The path to strip
9348 * @return string the path with double slashes removed
9350 function cleardoubleslashes ($path) {
9351 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9355 * Is the current ip in a given list?
9357 * @param string $list
9358 * @return bool
9360 function remoteip_in_list($list) {
9361 $clientip = getremoteaddr(null);
9363 if (!$clientip) {
9364 // Ensure access on cli.
9365 return true;
9367 return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
9371 * Returns most reliable client address
9373 * @param string $default If an address can't be determined, then return this
9374 * @return string The remote IP address
9376 function getremoteaddr($default='0.0.0.0') {
9377 global $CFG;
9379 if (!isset($CFG->getremoteaddrconf)) {
9380 // This will happen, for example, before just after the upgrade, as the
9381 // user is redirected to the admin screen.
9382 $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT;
9383 } else {
9384 $variablestoskip = $CFG->getremoteaddrconf;
9386 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9387 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9388 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9389 return $address ? $address : $default;
9392 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9393 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9394 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9396 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9397 global $CFG;
9398 return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
9401 // Multiple proxies can append values to this header including an
9402 // untrusted original request header so we must only trust the last ip.
9403 $address = end($forwardedaddresses);
9405 if (substr_count($address, ":") > 1) {
9406 // Remove port and brackets from IPv6.
9407 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9408 $address = $matches[1];
9410 } else {
9411 // Remove port from IPv4.
9412 if (substr_count($address, ":") == 1) {
9413 $parts = explode(":", $address);
9414 $address = $parts[0];
9418 $address = cleanremoteaddr($address);
9419 return $address ? $address : $default;
9422 if (!empty($_SERVER['REMOTE_ADDR'])) {
9423 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9424 return $address ? $address : $default;
9425 } else {
9426 return $default;
9431 * Cleans an ip address. Internal addresses are now allowed.
9432 * (Originally local addresses were not allowed.)
9434 * @param string $addr IPv4 or IPv6 address
9435 * @param bool $compress use IPv6 address compression
9436 * @return string normalised ip address string, null if error
9438 function cleanremoteaddr($addr, $compress=false) {
9439 $addr = trim($addr);
9441 if (strpos($addr, ':') !== false) {
9442 // Can be only IPv6.
9443 $parts = explode(':', $addr);
9444 $count = count($parts);
9446 if (strpos($parts[$count-1], '.') !== false) {
9447 // Legacy ipv4 notation.
9448 $last = array_pop($parts);
9449 $ipv4 = cleanremoteaddr($last, true);
9450 if ($ipv4 === null) {
9451 return null;
9453 $bits = explode('.', $ipv4);
9454 $parts[] = dechex($bits[0]).dechex($bits[1]);
9455 $parts[] = dechex($bits[2]).dechex($bits[3]);
9456 $count = count($parts);
9457 $addr = implode(':', $parts);
9460 if ($count < 3 or $count > 8) {
9461 return null; // Severly malformed.
9464 if ($count != 8) {
9465 if (strpos($addr, '::') === false) {
9466 return null; // Malformed.
9468 // Uncompress.
9469 $insertat = array_search('', $parts, true);
9470 $missing = array_fill(0, 1 + 8 - $count, '0');
9471 array_splice($parts, $insertat, 1, $missing);
9472 foreach ($parts as $key => $part) {
9473 if ($part === '') {
9474 $parts[$key] = '0';
9479 $adr = implode(':', $parts);
9480 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9481 return null; // Incorrect format - sorry.
9484 // Normalise 0s and case.
9485 $parts = array_map('hexdec', $parts);
9486 $parts = array_map('dechex', $parts);
9488 $result = implode(':', $parts);
9490 if (!$compress) {
9491 return $result;
9494 if ($result === '0:0:0:0:0:0:0:0') {
9495 return '::'; // All addresses.
9498 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9499 if ($compressed !== $result) {
9500 return $compressed;
9503 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9504 if ($compressed !== $result) {
9505 return $compressed;
9508 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9509 if ($compressed !== $result) {
9510 return $compressed;
9513 return $result;
9516 // First get all things that look like IPv4 addresses.
9517 $parts = array();
9518 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9519 return null;
9521 unset($parts[0]);
9523 foreach ($parts as $key => $match) {
9524 if ($match > 255) {
9525 return null;
9527 $parts[$key] = (int)$match; // Normalise 0s.
9530 return implode('.', $parts);
9535 * Is IP address a public address?
9537 * @param string $ip The ip to check
9538 * @return bool true if the ip is public
9540 function ip_is_public($ip) {
9541 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9545 * This function will make a complete copy of anything it's given,
9546 * regardless of whether it's an object or not.
9548 * @param mixed $thing Something you want cloned
9549 * @return mixed What ever it is you passed it
9551 function fullclone($thing) {
9552 return unserialize(serialize($thing));
9556 * Used to make sure that $min <= $value <= $max
9558 * Make sure that value is between min, and max
9560 * @param int $min The minimum value
9561 * @param int $value The value to check
9562 * @param int $max The maximum value
9563 * @return int
9565 function bounded_number($min, $value, $max) {
9566 if ($value < $min) {
9567 return $min;
9569 if ($value > $max) {
9570 return $max;
9572 return $value;
9576 * Check if there is a nested array within the passed array
9578 * @param array $array
9579 * @return bool true if there is a nested array false otherwise
9581 function array_is_nested($array) {
9582 foreach ($array as $value) {
9583 if (is_array($value)) {
9584 return true;
9587 return false;
9591 * get_performance_info() pairs up with init_performance_info()
9592 * loaded in setup.php. Returns an array with 'html' and 'txt'
9593 * values ready for use, and each of the individual stats provided
9594 * separately as well.
9596 * @return array
9598 function get_performance_info() {
9599 global $CFG, $PERF, $DB, $PAGE;
9601 $info = array();
9602 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9604 $info['html'] = '';
9605 if (!empty($CFG->themedesignermode)) {
9606 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9607 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9609 $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
9611 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9613 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9614 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9616 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9617 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9619 if (function_exists('memory_get_usage')) {
9620 $info['memory_total'] = memory_get_usage();
9621 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9622 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9623 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9624 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9627 if (function_exists('memory_get_peak_usage')) {
9628 $info['memory_peak'] = memory_get_peak_usage();
9629 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9630 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9633 $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9634 $inc = get_included_files();
9635 $info['includecount'] = count($inc);
9636 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9637 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9639 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9640 // We can not track more performance before installation or before PAGE init, sorry.
9641 return $info;
9644 $filtermanager = filter_manager::instance();
9645 if (method_exists($filtermanager, 'get_performance_summary')) {
9646 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9647 $info = array_merge($filterinfo, $info);
9648 foreach ($filterinfo as $key => $value) {
9649 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9650 $info['txt'] .= "$key: $value ";
9654 $stringmanager = get_string_manager();
9655 if (method_exists($stringmanager, 'get_performance_summary')) {
9656 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9657 $info = array_merge($filterinfo, $info);
9658 foreach ($filterinfo as $key => $value) {
9659 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9660 $info['txt'] .= "$key: $value ";
9664 $info['dbqueries'] = $DB->perf_get_reads().'/'.$DB->perf_get_writes();
9665 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9666 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9668 if ($DB->want_read_slave()) {
9669 $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9670 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9671 $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9674 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9675 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9676 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9678 if (function_exists('posix_times')) {
9679 $ptimes = posix_times();
9680 if (is_array($ptimes)) {
9681 foreach ($ptimes as $key => $val) {
9682 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9684 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9685 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9686 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9690 // Grab the load average for the last minute.
9691 // /proc will only work under some linux configurations
9692 // while uptime is there under MacOSX/Darwin and other unices.
9693 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9694 list($serverload) = explode(' ', $loadavg[0]);
9695 unset($loadavg);
9696 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9697 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9698 $serverload = $matches[1];
9699 } else {
9700 trigger_error('Could not parse uptime output!');
9703 if (!empty($serverload)) {
9704 $info['serverload'] = $serverload;
9705 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9706 $info['txt'] .= "serverload: {$info['serverload']} ";
9709 // Display size of session if session started.
9710 if ($si = \core\session\manager::get_performance_info()) {
9711 $info['sessionsize'] = $si['size'];
9712 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9713 $info['txt'] .= $si['txt'];
9716 // Display time waiting for session if applicable.
9717 if (!empty($PERF->sessionlock['wait'])) {
9718 $sessionwait = number_format($PERF->sessionlock['wait'], 3) . ' secs';
9719 $info['html'] .= html_writer::tag('li', 'Session wait: ' . $sessionwait, [
9720 'class' => 'sessionwait col-sm-4'
9722 $info['txt'] .= 'sessionwait: ' . $sessionwait . ' ';
9725 $info['html'] .= '</ul>';
9726 $html = '';
9727 if ($stats = cache_helper::get_stats()) {
9729 $table = new html_table();
9730 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9731 $table->head = ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S', 'I/O'];
9732 $table->data = [];
9733 $table->align = ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right', 'right'];
9735 $text = 'Caches used (hits/misses/sets): ';
9736 $hits = 0;
9737 $misses = 0;
9738 $sets = 0;
9739 $maxstores = 0;
9741 // We want to align static caches into their own column.
9742 $hasstatic = false;
9743 foreach ($stats as $definition => $details) {
9744 $numstores = count($details['stores']);
9745 $first = key($details['stores']);
9746 if ($first !== cache_store::STATIC_ACCEL) {
9747 $numstores++; // Add a blank space for the missing static store.
9749 $maxstores = max($maxstores, $numstores);
9752 $storec = 0;
9754 while ($storec++ < ($maxstores - 2)) {
9755 if ($storec == ($maxstores - 2)) {
9756 $table->head[] = get_string('mappingfinal', 'cache');
9757 } else {
9758 $table->head[] = "Store $storec";
9760 $table->align[] = 'left';
9761 $table->align[] = 'right';
9762 $table->align[] = 'right';
9763 $table->align[] = 'right';
9764 $table->align[] = 'right';
9765 $table->head[] = 'H';
9766 $table->head[] = 'M';
9767 $table->head[] = 'S';
9768 $table->head[] = 'I/O';
9771 ksort($stats);
9773 foreach ($stats as $definition => $details) {
9774 switch ($details['mode']) {
9775 case cache_store::MODE_APPLICATION:
9776 $modeclass = 'application';
9777 $mode = ' <span title="application cache">App</span>';
9778 break;
9779 case cache_store::MODE_SESSION:
9780 $modeclass = 'session';
9781 $mode = ' <span title="session cache">Ses</span>';
9782 break;
9783 case cache_store::MODE_REQUEST:
9784 $modeclass = 'request';
9785 $mode = ' <span title="request cache">Req</span>';
9786 break;
9788 $row = [$mode, $definition];
9790 $text .= "$definition {";
9792 $storec = 0;
9793 foreach ($details['stores'] as $store => $data) {
9795 if ($storec == 0 && $store !== cache_store::STATIC_ACCEL) {
9796 $row[] = '';
9797 $row[] = '';
9798 $row[] = '';
9799 $storec++;
9802 $hits += $data['hits'];
9803 $misses += $data['misses'];
9804 $sets += $data['sets'];
9805 if ($data['hits'] == 0 and $data['misses'] > 0) {
9806 $cachestoreclass = 'nohits bg-danger';
9807 } else if ($data['hits'] < $data['misses']) {
9808 $cachestoreclass = 'lowhits bg-warning text-dark';
9809 } else {
9810 $cachestoreclass = 'hihits';
9812 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9813 $cell = new html_table_cell($store);
9814 $cell->attributes = ['class' => $cachestoreclass];
9815 $row[] = $cell;
9816 $cell = new html_table_cell($data['hits']);
9817 $cell->attributes = ['class' => $cachestoreclass];
9818 $row[] = $cell;
9819 $cell = new html_table_cell($data['misses']);
9820 $cell->attributes = ['class' => $cachestoreclass];
9821 $row[] = $cell;
9823 if ($store !== cache_store::STATIC_ACCEL) {
9824 // The static cache is never set.
9825 $cell = new html_table_cell($data['sets']);
9826 $cell->attributes = ['class' => $cachestoreclass];
9827 $row[] = $cell;
9829 if ($data['hits'] || $data['sets']) {
9830 if ($data['iobytes'] === cache_store::IO_BYTES_NOT_SUPPORTED) {
9831 $size = '-';
9832 } else {
9833 $size = display_size($data['iobytes'], 1, 'KB');
9834 if ($data['iobytes'] >= 10 * 1024) {
9835 $cachestoreclass = ' bg-warning text-dark';
9838 } else {
9839 $size = '';
9841 $cell = new html_table_cell($size);
9842 $cell->attributes = ['class' => $cachestoreclass];
9843 $row[] = $cell;
9845 $storec++;
9847 while ($storec++ < $maxstores) {
9848 $row[] = '';
9849 $row[] = '';
9850 $row[] = '';
9851 $row[] = '';
9852 $row[] = '';
9854 $text .= '} ';
9856 $table->data[] = $row;
9859 $html .= html_writer::table($table);
9861 // Now lets also show sub totals for each cache store.
9862 $storetotals = [];
9863 $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9864 foreach ($stats as $definition => $details) {
9865 foreach ($details['stores'] as $store => $data) {
9866 if (!array_key_exists($store, $storetotals)) {
9867 $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9869 $storetotals[$store]['class'] = $data['class'];
9870 $storetotals[$store]['hits'] += $data['hits'];
9871 $storetotals[$store]['misses'] += $data['misses'];
9872 $storetotals[$store]['sets'] += $data['sets'];
9873 $storetotal['hits'] += $data['hits'];
9874 $storetotal['misses'] += $data['misses'];
9875 $storetotal['sets'] += $data['sets'];
9876 if ($data['iobytes'] !== cache_store::IO_BYTES_NOT_SUPPORTED) {
9877 $storetotals[$store]['iobytes'] += $data['iobytes'];
9878 $storetotal['iobytes'] += $data['iobytes'];
9883 $table = new html_table();
9884 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9885 $table->head = [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S', 'I/O'];
9886 $table->data = [];
9887 $table->align = ['left', 'left', 'right', 'right', 'right', 'right'];
9889 ksort($storetotals);
9891 foreach ($storetotals as $store => $data) {
9892 $row = [];
9893 if ($data['hits'] == 0 and $data['misses'] > 0) {
9894 $cachestoreclass = 'nohits bg-danger';
9895 } else if ($data['hits'] < $data['misses']) {
9896 $cachestoreclass = 'lowhits bg-warning text-dark';
9897 } else {
9898 $cachestoreclass = 'hihits';
9900 $cell = new html_table_cell($store);
9901 $cell->attributes = ['class' => $cachestoreclass];
9902 $row[] = $cell;
9903 $cell = new html_table_cell($data['class']);
9904 $cell->attributes = ['class' => $cachestoreclass];
9905 $row[] = $cell;
9906 $cell = new html_table_cell($data['hits']);
9907 $cell->attributes = ['class' => $cachestoreclass];
9908 $row[] = $cell;
9909 $cell = new html_table_cell($data['misses']);
9910 $cell->attributes = ['class' => $cachestoreclass];
9911 $row[] = $cell;
9912 $cell = new html_table_cell($data['sets']);
9913 $cell->attributes = ['class' => $cachestoreclass];
9914 $row[] = $cell;
9915 if ($data['hits'] || $data['sets']) {
9916 if ($data['iobytes']) {
9917 $size = display_size($data['iobytes'], 1, 'KB');
9918 } else {
9919 $size = '-';
9921 } else {
9922 $size = '';
9924 $cell = new html_table_cell($size);
9925 $cell->attributes = ['class' => $cachestoreclass];
9926 $row[] = $cell;
9927 $table->data[] = $row;
9929 if (!empty($storetotal['iobytes'])) {
9930 $size = display_size($storetotal['iobytes'], 1, 'KB');
9931 } else if (!empty($storetotal['hits']) || !empty($storetotal['sets'])) {
9932 $size = '-';
9933 } else {
9934 $size = '';
9936 $row = [
9937 get_string('total'),
9939 $storetotal['hits'],
9940 $storetotal['misses'],
9941 $storetotal['sets'],
9942 $size,
9944 $table->data[] = $row;
9946 $html .= html_writer::table($table);
9948 $info['cachesused'] = "$hits / $misses / $sets";
9949 $info['html'] .= $html;
9950 $info['txt'] .= $text.'. ';
9951 } else {
9952 $info['cachesused'] = '0 / 0 / 0';
9953 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9954 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9957 // Display lock information if any.
9958 if (!empty($PERF->locks)) {
9959 $table = new html_table();
9960 $table->attributes['class'] = 'locktimings table table-dark table-sm w-auto table-bordered';
9961 $table->head = ['Lock', 'Waited (s)', 'Obtained', 'Held for (s)'];
9962 $table->align = ['left', 'right', 'center', 'right'];
9963 $table->data = [];
9964 $text = 'Locks (waited/obtained/held):';
9965 foreach ($PERF->locks as $locktiming) {
9966 $row = [];
9967 $row[] = s($locktiming->type . '/' . $locktiming->resource);
9968 $text .= ' ' . $locktiming->type . '/' . $locktiming->resource . ' (';
9970 // The time we had to wait to get the lock.
9971 $roundedtime = number_format($locktiming->wait, 1);
9972 $cell = new html_table_cell($roundedtime);
9973 if ($locktiming->wait > 0.5) {
9974 $cell->attributes = ['class' => 'bg-warning text-dark'];
9976 $row[] = $cell;
9977 $text .= $roundedtime . '/';
9979 // Show a tick or cross for success.
9980 $row[] = $locktiming->success ? '&#x2713;' : '&#x274c;';
9981 $text .= ($locktiming->success ? 'y' : 'n') . '/';
9983 // If applicable, show how long we held the lock before releasing it.
9984 if (property_exists($locktiming, 'held')) {
9985 $roundedtime = number_format($locktiming->held, 1);
9986 $cell = new html_table_cell($roundedtime);
9987 if ($locktiming->held > 0.5) {
9988 $cell->attributes = ['class' => 'bg-warning text-dark'];
9990 $row[] = $cell;
9991 $text .= $roundedtime;
9992 } else {
9993 $row[] = '-';
9994 $text .= '-';
9996 $text .= ')';
9998 $table->data[] = $row;
10000 $info['html'] .= html_writer::table($table);
10001 $info['txt'] .= $text . '. ';
10004 $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto pt-3">'.$info['html'].'</div>';
10005 return $info;
10009 * Renames a file or directory to a unique name within the same directory.
10011 * This function is designed to avoid any potential race conditions, and select an unused name.
10013 * @param string $filepath Original filepath
10014 * @param string $prefix Prefix to use for the temporary name
10015 * @return string|bool New file path or false if failed
10016 * @since Moodle 3.10
10018 function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
10019 $dir = dirname($filepath);
10020 $basename = $dir . '/' . $prefix;
10021 $limit = 0;
10022 while ($limit < 100) {
10023 // Select a new name based on a random number.
10024 $newfilepath = $basename . md5(mt_rand());
10026 // Attempt a rename to that new name.
10027 if (@rename($filepath, $newfilepath)) {
10028 return $newfilepath;
10031 // The first time, do some sanity checks, maybe it is failing for a good reason and there
10032 // is no point trying 100 times if so.
10033 if ($limit === 0 && (!file_exists($filepath) || !is_writable($dir))) {
10034 return false;
10036 $limit++;
10038 return false;
10042 * Delete directory or only its content
10044 * @param string $dir directory path
10045 * @param bool $contentonly
10046 * @return bool success, true also if dir does not exist
10048 function remove_dir($dir, $contentonly=false) {
10049 if (!is_dir($dir)) {
10050 // Nothing to do.
10051 return true;
10054 if (!$contentonly) {
10055 // Start by renaming the directory; this will guarantee that other processes don't write to it
10056 // while it is in the process of being deleted.
10057 $tempdir = rename_to_unused_name($dir);
10058 if ($tempdir) {
10059 // If the rename was successful then delete the $tempdir instead.
10060 $dir = $tempdir;
10062 // If the rename fails, we will continue through and attempt to delete the directory
10063 // without renaming it since that is likely to at least delete most of the files.
10066 if (!$handle = opendir($dir)) {
10067 return false;
10069 $result = true;
10070 while (false!==($item = readdir($handle))) {
10071 if ($item != '.' && $item != '..') {
10072 if (is_dir($dir.'/'.$item)) {
10073 $result = remove_dir($dir.'/'.$item) && $result;
10074 } else {
10075 $result = unlink($dir.'/'.$item) && $result;
10079 closedir($handle);
10080 if ($contentonly) {
10081 clearstatcache(); // Make sure file stat cache is properly invalidated.
10082 return $result;
10084 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
10085 clearstatcache(); // Make sure file stat cache is properly invalidated.
10086 return $result;
10090 * Detect if an object or a class contains a given property
10091 * will take an actual object or the name of a class
10093 * @param mixed $obj Name of class or real object to test
10094 * @param string $property name of property to find
10095 * @return bool true if property exists
10097 function object_property_exists( $obj, $property ) {
10098 if (is_string( $obj )) {
10099 $properties = get_class_vars( $obj );
10100 } else {
10101 $properties = get_object_vars( $obj );
10103 return array_key_exists( $property, $properties );
10107 * Converts an object into an associative array
10109 * This function converts an object into an associative array by iterating
10110 * over its public properties. Because this function uses the foreach
10111 * construct, Iterators are respected. It works recursively on arrays of objects.
10112 * Arrays and simple values are returned as is.
10114 * If class has magic properties, it can implement IteratorAggregate
10115 * and return all available properties in getIterator()
10117 * @param mixed $var
10118 * @return array
10120 function convert_to_array($var) {
10121 $result = array();
10123 // Loop over elements/properties.
10124 foreach ($var as $key => $value) {
10125 // Recursively convert objects.
10126 if (is_object($value) || is_array($value)) {
10127 $result[$key] = convert_to_array($value);
10128 } else {
10129 // Simple values are untouched.
10130 $result[$key] = $value;
10133 return $result;
10137 * Detect a custom script replacement in the data directory that will
10138 * replace an existing moodle script
10140 * @return string|bool full path name if a custom script exists, false if no custom script exists
10142 function custom_script_path() {
10143 global $CFG, $SCRIPT;
10145 if ($SCRIPT === null) {
10146 // Probably some weird external script.
10147 return false;
10150 $scriptpath = $CFG->customscripts . $SCRIPT;
10152 // Check the custom script exists.
10153 if (file_exists($scriptpath) and is_file($scriptpath)) {
10154 return $scriptpath;
10155 } else {
10156 return false;
10161 * Returns whether or not the user object is a remote MNET user. This function
10162 * is in moodlelib because it does not rely on loading any of the MNET code.
10164 * @param object $user A valid user object
10165 * @return bool True if the user is from a remote Moodle.
10167 function is_mnet_remote_user($user) {
10168 global $CFG;
10170 if (!isset($CFG->mnet_localhost_id)) {
10171 include_once($CFG->dirroot . '/mnet/lib.php');
10172 $env = new mnet_environment();
10173 $env->init();
10174 unset($env);
10177 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
10181 * This function will search for browser prefereed languages, setting Moodle
10182 * to use the best one available if $SESSION->lang is undefined
10184 function setup_lang_from_browser() {
10185 global $CFG, $SESSION, $USER;
10187 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
10188 // Lang is defined in session or user profile, nothing to do.
10189 return;
10192 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
10193 return;
10196 // Extract and clean langs from headers.
10197 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
10198 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
10199 $rawlangs = explode(',', $rawlangs); // Convert to array.
10200 $langs = array();
10202 $order = 1.0;
10203 foreach ($rawlangs as $lang) {
10204 if (strpos($lang, ';') === false) {
10205 $langs[(string)$order] = $lang;
10206 $order = $order-0.01;
10207 } else {
10208 $parts = explode(';', $lang);
10209 $pos = strpos($parts[1], '=');
10210 $langs[substr($parts[1], $pos+1)] = $parts[0];
10213 krsort($langs, SORT_NUMERIC);
10215 // Look for such langs under standard locations.
10216 foreach ($langs as $lang) {
10217 // Clean it properly for include.
10218 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
10219 if (get_string_manager()->translation_exists($lang, false)) {
10220 // Lang exists, set it in session.
10221 $SESSION->lang = $lang;
10222 // We have finished. Go out.
10223 break;
10226 return;
10230 * Check if $url matches anything in proxybypass list
10232 * Any errors just result in the proxy being used (least bad)
10234 * @param string $url url to check
10235 * @return boolean true if we should bypass the proxy
10237 function is_proxybypass( $url ) {
10238 global $CFG;
10240 // Sanity check.
10241 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
10242 return false;
10245 // Get the host part out of the url.
10246 if (!$host = parse_url( $url, PHP_URL_HOST )) {
10247 return false;
10250 // Get the possible bypass hosts into an array.
10251 $matches = explode( ',', $CFG->proxybypass );
10253 // Check for a exact match on the IP or in the domains.
10254 $isdomaininallowedlist = \core\ip_utils::is_domain_in_allowed_list($host, $matches);
10255 $isipinsubnetlist = \core\ip_utils::is_ip_in_subnet_list($host, $CFG->proxybypass, ',');
10257 if ($isdomaininallowedlist || $isipinsubnetlist) {
10258 return true;
10261 // Nothing matched.
10262 return false;
10266 * Check if the passed navigation is of the new style
10268 * @param mixed $navigation
10269 * @return bool true for yes false for no
10271 function is_newnav($navigation) {
10272 if (is_array($navigation) && !empty($navigation['newnav'])) {
10273 return true;
10274 } else {
10275 return false;
10280 * Checks whether the given variable name is defined as a variable within the given object.
10282 * This will NOT work with stdClass objects, which have no class variables.
10284 * @param string $var The variable name
10285 * @param object $object The object to check
10286 * @return boolean
10288 function in_object_vars($var, $object) {
10289 $classvars = get_class_vars(get_class($object));
10290 $classvars = array_keys($classvars);
10291 return in_array($var, $classvars);
10295 * Returns an array without repeated objects.
10296 * This function is similar to array_unique, but for arrays that have objects as values
10298 * @param array $array
10299 * @param bool $keepkeyassoc
10300 * @return array
10302 function object_array_unique($array, $keepkeyassoc = true) {
10303 $duplicatekeys = array();
10304 $tmp = array();
10306 foreach ($array as $key => $val) {
10307 // Convert objects to arrays, in_array() does not support objects.
10308 if (is_object($val)) {
10309 $val = (array)$val;
10312 if (!in_array($val, $tmp)) {
10313 $tmp[] = $val;
10314 } else {
10315 $duplicatekeys[] = $key;
10319 foreach ($duplicatekeys as $key) {
10320 unset($array[$key]);
10323 return $keepkeyassoc ? $array : array_values($array);
10327 * Is a userid the primary administrator?
10329 * @param int $userid int id of user to check
10330 * @return boolean
10332 function is_primary_admin($userid) {
10333 $primaryadmin = get_admin();
10335 if ($userid == $primaryadmin->id) {
10336 return true;
10337 } else {
10338 return false;
10343 * Returns the site identifier
10345 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10347 function get_site_identifier() {
10348 global $CFG;
10349 // Check to see if it is missing. If so, initialise it.
10350 if (empty($CFG->siteidentifier)) {
10351 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10353 // Return it.
10354 return $CFG->siteidentifier;
10358 * Check whether the given password has no more than the specified
10359 * number of consecutive identical characters.
10361 * @param string $password password to be checked against the password policy
10362 * @param integer $maxchars maximum number of consecutive identical characters
10363 * @return bool
10365 function check_consecutive_identical_characters($password, $maxchars) {
10367 if ($maxchars < 1) {
10368 return true; // Zero 0 is to disable this check.
10370 if (strlen($password) <= $maxchars) {
10371 return true; // Too short to fail this test.
10374 $previouschar = '';
10375 $consecutivecount = 1;
10376 foreach (str_split($password) as $char) {
10377 if ($char != $previouschar) {
10378 $consecutivecount = 1;
10379 } else {
10380 $consecutivecount++;
10381 if ($consecutivecount > $maxchars) {
10382 return false; // Check failed already.
10386 $previouschar = $char;
10389 return true;
10393 * Helper function to do partial function binding.
10394 * so we can use it for preg_replace_callback, for example
10395 * this works with php functions, user functions, static methods and class methods
10396 * it returns you a callback that you can pass on like so:
10398 * $callback = partial('somefunction', $arg1, $arg2);
10399 * or
10400 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10401 * or even
10402 * $obj = new someclass();
10403 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10405 * and then the arguments that are passed through at calltime are appended to the argument list.
10407 * @param mixed $function a php callback
10408 * @param mixed $arg1,... $argv arguments to partially bind with
10409 * @return array Array callback
10411 function partial() {
10412 if (!class_exists('partial')) {
10414 * Used to manage function binding.
10415 * @copyright 2009 Penny Leach
10416 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10418 class partial{
10419 /** @var array */
10420 public $values = array();
10421 /** @var string The function to call as a callback. */
10422 public $func;
10424 * Constructor
10425 * @param string $func
10426 * @param array $args
10428 public function __construct($func, $args) {
10429 $this->values = $args;
10430 $this->func = $func;
10433 * Calls the callback function.
10434 * @return mixed
10436 public function method() {
10437 $args = func_get_args();
10438 return call_user_func_array($this->func, array_merge($this->values, $args));
10442 $args = func_get_args();
10443 $func = array_shift($args);
10444 $p = new partial($func, $args);
10445 return array($p, 'method');
10449 * helper function to load up and initialise the mnet environment
10450 * this must be called before you use mnet functions.
10452 * @return mnet_environment the equivalent of old $MNET global
10454 function get_mnet_environment() {
10455 global $CFG;
10456 require_once($CFG->dirroot . '/mnet/lib.php');
10457 static $instance = null;
10458 if (empty($instance)) {
10459 $instance = new mnet_environment();
10460 $instance->init();
10462 return $instance;
10466 * during xmlrpc server code execution, any code wishing to access
10467 * information about the remote peer must use this to get it.
10469 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10471 function get_mnet_remote_client() {
10472 if (!defined('MNET_SERVER')) {
10473 debugging(get_string('notinxmlrpcserver', 'mnet'));
10474 return false;
10476 global $MNET_REMOTE_CLIENT;
10477 if (isset($MNET_REMOTE_CLIENT)) {
10478 return $MNET_REMOTE_CLIENT;
10480 return false;
10484 * during the xmlrpc server code execution, this will be called
10485 * to setup the object returned by {@link get_mnet_remote_client}
10487 * @param mnet_remote_client $client the client to set up
10488 * @throws moodle_exception
10490 function set_mnet_remote_client($client) {
10491 if (!defined('MNET_SERVER')) {
10492 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10494 global $MNET_REMOTE_CLIENT;
10495 $MNET_REMOTE_CLIENT = $client;
10499 * return the jump url for a given remote user
10500 * this is used for rewriting forum post links in emails, etc
10502 * @param stdclass $user the user to get the idp url for
10504 function mnet_get_idp_jump_url($user) {
10505 global $CFG;
10507 static $mnetjumps = array();
10508 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10509 $idp = mnet_get_peer_host($user->mnethostid);
10510 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10511 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10513 return $mnetjumps[$user->mnethostid];
10517 * Gets the homepage to use for the current user
10519 * @return int One of HOMEPAGE_*
10521 function get_home_page() {
10522 global $CFG;
10524 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10525 // If dashboard is disabled, home will be set to default page.
10526 $defaultpage = get_default_home_page();
10527 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10528 if (!empty($CFG->enabledashboard)) {
10529 return HOMEPAGE_MY;
10530 } else {
10531 return $defaultpage;
10533 } else if ($CFG->defaulthomepage == HOMEPAGE_MYCOURSES) {
10534 return HOMEPAGE_MYCOURSES;
10535 } else {
10536 $userhomepage = (int) get_user_preferences('user_home_page_preference', $defaultpage);
10537 if (empty($CFG->enabledashboard) && $userhomepage == HOMEPAGE_MY) {
10538 // If the user was using the dashboard but it's disabled, return the default home page.
10539 $userhomepage = $defaultpage;
10541 return $userhomepage;
10544 return HOMEPAGE_SITE;
10548 * Returns the default home page to display if current one is not defined or can't be applied.
10549 * The default behaviour is to return Dashboard if it's enabled or My courses page if it isn't.
10551 * @return int The default home page.
10553 function get_default_home_page(): int {
10554 global $CFG;
10556 return !empty($CFG->enabledashboard) ? HOMEPAGE_MY : HOMEPAGE_MYCOURSES;
10560 * Gets the name of a course to be displayed when showing a list of courses.
10561 * By default this is just $course->fullname but user can configure it. The
10562 * result of this function should be passed through print_string.
10563 * @param stdClass|core_course_list_element $course Moodle course object
10564 * @return string Display name of course (either fullname or short + fullname)
10566 function get_course_display_name_for_list($course) {
10567 global $CFG;
10568 if (!empty($CFG->courselistshortnames)) {
10569 if (!($course instanceof stdClass)) {
10570 $course = (object)convert_to_array($course);
10572 return get_string('courseextendednamedisplay', '', $course);
10573 } else {
10574 return $course->fullname;
10579 * Safe analogue of unserialize() that can only parse arrays
10581 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10583 * @param string $expression
10584 * @return array|bool either parsed array or false if parsing was impossible.
10586 function unserialize_array($expression) {
10588 // Check the expression is an array.
10589 if (!preg_match('/^a:(\d+):/', $expression)) {
10590 return false;
10593 $values = (array) unserialize_object($expression);
10595 // Callback that returns true if the given value is an unserialized object, executes recursively.
10596 $invalidvaluecallback = static function($value) use (&$invalidvaluecallback): bool {
10597 if (is_array($value)) {
10598 return (bool) array_filter($value, $invalidvaluecallback);
10600 return ($value instanceof stdClass) || ($value instanceof __PHP_Incomplete_Class);
10603 // Iterate over the result to ensure there are no stray objects.
10604 if (array_filter($values, $invalidvaluecallback)) {
10605 return false;
10608 return $values;
10612 * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10614 * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10615 * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10616 * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10618 * @param string $input
10619 * @return stdClass
10621 function unserialize_object(string $input): stdClass {
10622 $instance = (array) unserialize($input, ['allowed_classes' => [stdClass::class]]);
10623 return (object) $instance;
10627 * The lang_string class
10629 * This special class is used to create an object representation of a string request.
10630 * It is special because processing doesn't occur until the object is first used.
10631 * The class was created especially to aid performance in areas where strings were
10632 * required to be generated but were not necessarily used.
10633 * As an example the admin tree when generated uses over 1500 strings, of which
10634 * normally only 1/3 are ever actually printed at any time.
10635 * The performance advantage is achieved by not actually processing strings that
10636 * arn't being used, as such reducing the processing required for the page.
10638 * How to use the lang_string class?
10639 * There are two methods of using the lang_string class, first through the
10640 * forth argument of the get_string function, and secondly directly.
10641 * The following are examples of both.
10642 * 1. Through get_string calls e.g.
10643 * $string = get_string($identifier, $component, $a, true);
10644 * $string = get_string('yes', 'moodle', null, true);
10645 * 2. Direct instantiation
10646 * $string = new lang_string($identifier, $component, $a, $lang);
10647 * $string = new lang_string('yes');
10649 * How do I use a lang_string object?
10650 * The lang_string object makes use of a magic __toString method so that you
10651 * are able to use the object exactly as you would use a string in most cases.
10652 * This means you are able to collect it into a variable and then directly
10653 * echo it, or concatenate it into another string, or similar.
10654 * The other thing you can do is manually get the string by calling the
10655 * lang_strings out method e.g.
10656 * $string = new lang_string('yes');
10657 * $string->out();
10658 * Also worth noting is that the out method can take one argument, $lang which
10659 * allows the developer to change the language on the fly.
10661 * When should I use a lang_string object?
10662 * The lang_string object is designed to be used in any situation where a
10663 * string may not be needed, but needs to be generated.
10664 * The admin tree is a good example of where lang_string objects should be
10665 * used.
10666 * A more practical example would be any class that requries strings that may
10667 * not be printed (after all classes get renderer by renderers and who knows
10668 * what they will do ;))
10670 * When should I not use a lang_string object?
10671 * Don't use lang_strings when you are going to use a string immediately.
10672 * There is no need as it will be processed immediately and there will be no
10673 * advantage, and in fact perhaps a negative hit as a class has to be
10674 * instantiated for a lang_string object, however get_string won't require
10675 * that.
10677 * Limitations:
10678 * 1. You cannot use a lang_string object as an array offset. Doing so will
10679 * result in PHP throwing an error. (You can use it as an object property!)
10681 * @package core
10682 * @category string
10683 * @copyright 2011 Sam Hemelryk
10684 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10686 class lang_string {
10688 /** @var string The strings identifier */
10689 protected $identifier;
10690 /** @var string The strings component. Default '' */
10691 protected $component = '';
10692 /** @var array|stdClass Any arguments required for the string. Default null */
10693 protected $a = null;
10694 /** @var string The language to use when processing the string. Default null */
10695 protected $lang = null;
10697 /** @var string The processed string (once processed) */
10698 protected $string = null;
10701 * A special boolean. If set to true then the object has been woken up and
10702 * cannot be regenerated. If this is set then $this->string MUST be used.
10703 * @var bool
10705 protected $forcedstring = false;
10708 * Constructs a lang_string object
10710 * This function should do as little processing as possible to ensure the best
10711 * performance for strings that won't be used.
10713 * @param string $identifier The strings identifier
10714 * @param string $component The strings component
10715 * @param stdClass|array|mixed $a Any arguments the string requires
10716 * @param string $lang The language to use when processing the string.
10717 * @throws coding_exception
10719 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10720 if (empty($component)) {
10721 $component = 'moodle';
10724 $this->identifier = $identifier;
10725 $this->component = $component;
10726 $this->lang = $lang;
10728 // We MUST duplicate $a to ensure that it if it changes by reference those
10729 // changes are not carried across.
10730 // To do this we always ensure $a or its properties/values are strings
10731 // and that any properties/values that arn't convertable are forgotten.
10732 if ($a !== null) {
10733 if (is_scalar($a)) {
10734 $this->a = $a;
10735 } else if ($a instanceof lang_string) {
10736 $this->a = $a->out();
10737 } else if (is_object($a) or is_array($a)) {
10738 $a = (array)$a;
10739 $this->a = array();
10740 foreach ($a as $key => $value) {
10741 // Make sure conversion errors don't get displayed (results in '').
10742 if (is_array($value)) {
10743 $this->a[$key] = '';
10744 } else if (is_object($value)) {
10745 if (method_exists($value, '__toString')) {
10746 $this->a[$key] = $value->__toString();
10747 } else {
10748 $this->a[$key] = '';
10750 } else {
10751 $this->a[$key] = (string)$value;
10757 if (debugging(false, DEBUG_DEVELOPER)) {
10758 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10759 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10761 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10762 throw new coding_exception('Invalid string compontent. Please check your string definition');
10764 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10765 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10771 * Processes the string.
10773 * This function actually processes the string, stores it in the string property
10774 * and then returns it.
10775 * You will notice that this function is VERY similar to the get_string method.
10776 * That is because it is pretty much doing the same thing.
10777 * However as this function is an upgrade it isn't as tolerant to backwards
10778 * compatibility.
10780 * @return string
10781 * @throws coding_exception
10783 protected function get_string() {
10784 global $CFG;
10786 // Check if we need to process the string.
10787 if ($this->string === null) {
10788 // Check the quality of the identifier.
10789 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10790 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);
10793 // Process the string.
10794 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10795 // Debugging feature lets you display string identifier and component.
10796 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10797 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10800 // Return the string.
10801 return $this->string;
10805 * Returns the string
10807 * @param string $lang The langauge to use when processing the string
10808 * @return string
10810 public function out($lang = null) {
10811 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10812 if ($this->forcedstring) {
10813 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10814 return $this->get_string();
10816 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10817 return $translatedstring->out();
10819 return $this->get_string();
10823 * Magic __toString method for printing a string
10825 * @return string
10827 public function __toString() {
10828 return $this->get_string();
10832 * Magic __set_state method used for var_export
10834 * @param array $array
10835 * @return self
10837 public static function __set_state(array $array): self {
10838 $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10839 $tmp->string = $array['string'];
10840 $tmp->forcedstring = $array['forcedstring'];
10841 return $tmp;
10845 * Prepares the lang_string for sleep and stores only the forcedstring and
10846 * string properties... the string cannot be regenerated so we need to ensure
10847 * it is generated for this.
10849 * @return string
10851 public function __sleep() {
10852 $this->get_string();
10853 $this->forcedstring = true;
10854 return array('forcedstring', 'string', 'lang');
10858 * Returns the identifier.
10860 * @return string
10862 public function get_identifier() {
10863 return $this->identifier;
10867 * Returns the component.
10869 * @return string
10871 public function get_component() {
10872 return $this->component;
10877 * Get human readable name describing the given callable.
10879 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10880 * It does not check if the callable actually exists.
10882 * @param callable|string|array $callable
10883 * @return string|bool Human readable name of callable, or false if not a valid callable.
10885 function get_callable_name($callable) {
10887 if (!is_callable($callable, true, $name)) {
10888 return false;
10890 } else {
10891 return $name;
10896 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10897 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10898 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10899 * such as site registration when $CFG->wwwroot is not publicly accessible.
10900 * Good thing is there is no false negative.
10901 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10903 * @return bool
10905 function site_is_public() {
10906 global $CFG;
10908 // Return early if site admin has forced this setting.
10909 if (isset($CFG->site_is_public)) {
10910 return (bool)$CFG->site_is_public;
10913 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10915 if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10916 $ispublic = false;
10917 } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10918 $ispublic = false;
10919 } else if (($address = \core\ip_utils::get_ip_address($host)) && !ip_is_public($address)) {
10920 $ispublic = false;
10921 } else {
10922 $ispublic = true;
10925 return $ispublic;