on-demand release 4.2dev+
[moodle.git] / lib / moodlelib.php
blobcb23fab7eef9afcd9d75b5169bdf771b167964ac
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;
1321 // No null bytes expected in our data, so let's remove it.
1322 $value = str_replace("\0", '', $value);
1324 // Note: this duplicates min_fix_utf8() intentionally.
1325 static $buggyiconv = null;
1326 if ($buggyiconv === null) {
1327 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1330 if ($buggyiconv) {
1331 if (function_exists('mb_convert_encoding')) {
1332 $subst = mb_substitute_character();
1333 mb_substitute_character('none');
1334 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1335 mb_substitute_character($subst);
1337 } else {
1338 // Warn admins on admin/index.php page.
1339 $result = $value;
1342 } else {
1343 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1346 return $result;
1348 } else if (is_array($value)) {
1349 foreach ($value as $k => $v) {
1350 $value[$k] = fix_utf8($v);
1352 return $value;
1354 } else if (is_object($value)) {
1355 // Do not modify original.
1356 $value = clone($value);
1357 foreach ($value as $k => $v) {
1358 $value->$k = fix_utf8($v);
1360 return $value;
1362 } else {
1363 // This is some other type, no utf-8 here.
1364 return $value;
1369 * Return true if given value is integer or string with integer value
1371 * @param mixed $value String or Int
1372 * @return bool true if number, false if not
1374 function is_number($value) {
1375 if (is_int($value)) {
1376 return true;
1377 } else if (is_string($value)) {
1378 return ((string)(int)$value) === $value;
1379 } else {
1380 return false;
1385 * Returns host part from url.
1387 * @param string $url full url
1388 * @return string host, null if not found
1390 function get_host_from_url($url) {
1391 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1392 if ($matches) {
1393 return $matches[1];
1395 return null;
1399 * Tests whether anything was returned by text editor
1401 * This function is useful for testing whether something you got back from
1402 * the HTML editor actually contains anything. Sometimes the HTML editor
1403 * appear to be empty, but actually you get back a <br> tag or something.
1405 * @param string $string a string containing HTML.
1406 * @return boolean does the string contain any actual content - that is text,
1407 * images, objects, etc.
1409 function html_is_blank($string) {
1410 return trim(strip_tags((string)$string, '<img><object><applet><input><select><textarea><hr>')) == '';
1414 * Set a key in global configuration
1416 * Set a key/value pair in both this session's {@link $CFG} global variable
1417 * and in the 'config' database table for future sessions.
1419 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1420 * In that case it doesn't affect $CFG.
1422 * A NULL value will delete the entry.
1424 * NOTE: this function is called from lib/db/upgrade.php
1426 * @param string $name the key to set
1427 * @param string $value the value to set (without magic quotes)
1428 * @param string $plugin (optional) the plugin scope, default null
1429 * @return bool true or exception
1431 function set_config($name, $value, $plugin = null) {
1432 global $CFG, $DB;
1434 // Redirect to appropriate handler when value is null.
1435 if ($value === null) {
1436 return unset_config($name, $plugin);
1439 // Set variables determining conditions and where to store the new config.
1440 // Plugin config goes to {config_plugins}, core config goes to {config}.
1441 $iscore = empty($plugin);
1442 if ($iscore) {
1443 // If it's for core config.
1444 $table = 'config';
1445 $conditions = ['name' => $name];
1446 $invalidatecachekey = 'core';
1447 } else {
1448 // If it's a plugin.
1449 $table = 'config_plugins';
1450 $conditions = ['name' => $name, 'plugin' => $plugin];
1451 $invalidatecachekey = $plugin;
1454 // DB handling - checks for existing config, updating or inserting only if necessary.
1455 $invalidatecache = true;
1456 $inserted = false;
1457 $record = $DB->get_record($table, $conditions, 'id, value');
1458 if ($record === false) {
1459 // Inserts a new config record.
1460 $config = new stdClass();
1461 $config->name = $name;
1462 $config->value = $value;
1463 if (!$iscore) {
1464 $config->plugin = $plugin;
1466 $inserted = $DB->insert_record($table, $config, false);
1467 } else if ($invalidatecache = ($record->value !== $value)) {
1468 // Record exists - Check and only set new value if it has changed.
1469 $DB->set_field($table, 'value', $value, ['id' => $record->id]);
1472 if ($iscore && !isset($CFG->config_php_settings[$name])) {
1473 // So it's defined for this invocation at least.
1474 // Settings from db are always strings.
1475 $CFG->$name = (string) $value;
1478 // When setting config during a Behat test (in the CLI script, not in the web browser
1479 // requests), remember which ones are set so that we can clear them later.
1480 if ($iscore && $inserted && defined('BEHAT_TEST')) {
1481 $CFG->behat_cli_added_config[$name] = true;
1484 // Update siteidentifier cache, if required.
1485 if ($iscore && $name === 'siteidentifier') {
1486 cache_helper::update_site_identifier($value);
1489 // Invalidate cache, if required.
1490 if ($invalidatecache) {
1491 cache_helper::invalidate_by_definition('core', 'config', [], $invalidatecachekey);
1494 return true;
1498 * Get configuration values from the global config table
1499 * or the config_plugins table.
1501 * If called with one parameter, it will load all the config
1502 * variables for one plugin, and return them as an object.
1504 * If called with 2 parameters it will return a string single
1505 * value or false if the value is not found.
1507 * NOTE: this function is called from lib/db/upgrade.php
1509 * @param string $plugin full component name
1510 * @param string $name default null
1511 * @return mixed hash-like object or single value, return false no config found
1512 * @throws dml_exception
1514 function get_config($plugin, $name = null) {
1515 global $CFG, $DB;
1517 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1518 $forced =& $CFG->config_php_settings;
1519 $iscore = true;
1520 $plugin = 'core';
1521 } else {
1522 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1523 $forced =& $CFG->forced_plugin_settings[$plugin];
1524 } else {
1525 $forced = array();
1527 $iscore = false;
1530 if (!isset($CFG->siteidentifier)) {
1531 try {
1532 // This may throw an exception during installation, which is how we detect the
1533 // need to install the database. For more details see {@see initialise_cfg()}.
1534 $CFG->siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1535 } catch (dml_exception $ex) {
1536 // Set siteidentifier to false. We don't want to trip this continually.
1537 $siteidentifier = false;
1538 throw $ex;
1542 if (!empty($name)) {
1543 if (array_key_exists($name, $forced)) {
1544 return (string)$forced[$name];
1545 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1546 return $CFG->siteidentifier;
1550 $cache = cache::make('core', 'config');
1551 $result = $cache->get($plugin);
1552 if ($result === false) {
1553 // The user is after a recordset.
1554 if (!$iscore) {
1555 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1556 } else {
1557 // This part is not really used any more, but anyway...
1558 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1560 $cache->set($plugin, $result);
1563 if (!empty($name)) {
1564 if (array_key_exists($name, $result)) {
1565 return $result[$name];
1567 return false;
1570 if ($plugin === 'core') {
1571 $result['siteidentifier'] = $CFG->siteidentifier;
1574 foreach ($forced as $key => $value) {
1575 if (is_null($value) or is_array($value) or is_object($value)) {
1576 // We do not want any extra mess here, just real settings that could be saved in db.
1577 unset($result[$key]);
1578 } else {
1579 // Convert to string as if it went through the DB.
1580 $result[$key] = (string)$value;
1584 return (object)$result;
1588 * Removes a key from global configuration.
1590 * NOTE: this function is called from lib/db/upgrade.php
1592 * @param string $name the key to set
1593 * @param string $plugin (optional) the plugin scope
1594 * @return boolean whether the operation succeeded.
1596 function unset_config($name, $plugin=null) {
1597 global $CFG, $DB;
1599 if (empty($plugin)) {
1600 unset($CFG->$name);
1601 $DB->delete_records('config', array('name' => $name));
1602 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1603 } else {
1604 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1605 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1608 return true;
1612 * Remove all the config variables for a given plugin.
1614 * NOTE: this function is called from lib/db/upgrade.php
1616 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1617 * @return boolean whether the operation succeeded.
1619 function unset_all_config_for_plugin($plugin) {
1620 global $DB;
1621 // Delete from the obvious config_plugins first.
1622 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1623 // Next delete any suspect settings from config.
1624 $like = $DB->sql_like('name', '?', true, true, false, '|');
1625 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1626 $DB->delete_records_select('config', $like, $params);
1627 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1628 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1630 return true;
1634 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1636 * All users are verified if they still have the necessary capability.
1638 * @param string $value the value of the config setting.
1639 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1640 * @param bool $includeadmins include administrators.
1641 * @return array of user objects.
1643 function get_users_from_config($value, $capability, $includeadmins = true) {
1644 if (empty($value) or $value === '$@NONE@$') {
1645 return array();
1648 // We have to make sure that users still have the necessary capability,
1649 // it should be faster to fetch them all first and then test if they are present
1650 // instead of validating them one-by-one.
1651 $users = get_users_by_capability(context_system::instance(), $capability);
1652 if ($includeadmins) {
1653 $admins = get_admins();
1654 foreach ($admins as $admin) {
1655 $users[$admin->id] = $admin;
1659 if ($value === '$@ALL@$') {
1660 return $users;
1663 $result = array(); // Result in correct order.
1664 $allowed = explode(',', $value);
1665 foreach ($allowed as $uid) {
1666 if (isset($users[$uid])) {
1667 $user = $users[$uid];
1668 $result[$user->id] = $user;
1672 return $result;
1677 * Invalidates browser caches and cached data in temp.
1679 * @return void
1681 function purge_all_caches() {
1682 purge_caches();
1686 * Selectively invalidate different types of cache.
1688 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1689 * areas alone or in combination.
1691 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1692 * 'muc' Purge MUC caches?
1693 * 'theme' Purge theme cache?
1694 * 'lang' Purge language string cache?
1695 * 'js' Purge javascript cache?
1696 * 'filter' Purge text filter cache?
1697 * 'other' Purge all other caches?
1699 function purge_caches($options = []) {
1700 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1701 if (empty(array_filter($options))) {
1702 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1703 } else {
1704 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1706 if ($options['muc']) {
1707 cache_helper::purge_all();
1709 if ($options['theme']) {
1710 theme_reset_all_caches();
1712 if ($options['lang']) {
1713 get_string_manager()->reset_caches();
1715 if ($options['js']) {
1716 js_reset_all_caches();
1718 if ($options['template']) {
1719 template_reset_all_caches();
1721 if ($options['filter']) {
1722 reset_text_filters_cache();
1724 if ($options['other']) {
1725 purge_other_caches();
1730 * Purge all non-MUC caches not otherwise purged in purge_caches.
1732 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1733 * {@link phpunit_util::reset_dataroot()}
1735 function purge_other_caches() {
1736 global $DB, $CFG;
1737 if (class_exists('core_plugin_manager')) {
1738 core_plugin_manager::reset_caches();
1741 // Bump up cacherev field for all courses.
1742 try {
1743 increment_revision_number('course', 'cacherev', '');
1744 } catch (moodle_exception $e) {
1745 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1748 $DB->reset_caches();
1750 // Purge all other caches: rss, simplepie, etc.
1751 clearstatcache();
1752 remove_dir($CFG->cachedir.'', true);
1754 // Make sure cache dir is writable, throws exception if not.
1755 make_cache_directory('');
1757 // This is the only place where we purge local caches, we are only adding files there.
1758 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1759 remove_dir($CFG->localcachedir, true);
1760 set_config('localcachedirpurged', time());
1761 make_localcache_directory('', true);
1762 \core\task\manager::clear_static_caches();
1766 * Get volatile flags
1768 * @param string $type
1769 * @param int $changedsince default null
1770 * @return array records array
1772 function get_cache_flags($type, $changedsince = null) {
1773 global $DB;
1775 $params = array('type' => $type, 'expiry' => time());
1776 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1777 if ($changedsince !== null) {
1778 $params['changedsince'] = $changedsince;
1779 $sqlwhere .= " AND timemodified > :changedsince";
1781 $cf = array();
1782 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1783 foreach ($flags as $flag) {
1784 $cf[$flag->name] = $flag->value;
1787 return $cf;
1791 * Get volatile flags
1793 * @param string $type
1794 * @param string $name
1795 * @param int $changedsince default null
1796 * @return string|false The cache flag value or false
1798 function get_cache_flag($type, $name, $changedsince=null) {
1799 global $DB;
1801 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1803 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1804 if ($changedsince !== null) {
1805 $params['changedsince'] = $changedsince;
1806 $sqlwhere .= " AND timemodified > :changedsince";
1809 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1813 * Set a volatile flag
1815 * @param string $type the "type" namespace for the key
1816 * @param string $name the key to set
1817 * @param string $value the value to set (without magic quotes) - null will remove the flag
1818 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1819 * @return bool Always returns true
1821 function set_cache_flag($type, $name, $value, $expiry = null) {
1822 global $DB;
1824 $timemodified = time();
1825 if ($expiry === null || $expiry < $timemodified) {
1826 $expiry = $timemodified + 24 * 60 * 60;
1827 } else {
1828 $expiry = (int)$expiry;
1831 if ($value === null) {
1832 unset_cache_flag($type, $name);
1833 return true;
1836 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1837 // This is a potential problem in DEBUG_DEVELOPER.
1838 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1839 return true; // No need to update.
1841 $f->value = $value;
1842 $f->expiry = $expiry;
1843 $f->timemodified = $timemodified;
1844 $DB->update_record('cache_flags', $f);
1845 } else {
1846 $f = new stdClass();
1847 $f->flagtype = $type;
1848 $f->name = $name;
1849 $f->value = $value;
1850 $f->expiry = $expiry;
1851 $f->timemodified = $timemodified;
1852 $DB->insert_record('cache_flags', $f);
1854 return true;
1858 * Removes a single volatile flag
1860 * @param string $type the "type" namespace for the key
1861 * @param string $name the key to set
1862 * @return bool
1864 function unset_cache_flag($type, $name) {
1865 global $DB;
1866 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1867 return true;
1871 * Garbage-collect volatile flags
1873 * @return bool Always returns true
1875 function gc_cache_flags() {
1876 global $DB;
1877 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1878 return true;
1881 // USER PREFERENCE API.
1884 * Refresh user preference cache. This is used most often for $USER
1885 * object that is stored in session, but it also helps with performance in cron script.
1887 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1889 * @package core
1890 * @category preference
1891 * @access public
1892 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1893 * @param int $cachelifetime Cache life time on the current page (in seconds)
1894 * @throws coding_exception
1895 * @return null
1897 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1898 global $DB;
1899 // Static cache, we need to check on each page load, not only every 2 minutes.
1900 static $loadedusers = array();
1902 if (!isset($user->id)) {
1903 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1906 if (empty($user->id) or isguestuser($user->id)) {
1907 // No permanent storage for not-logged-in users and guest.
1908 if (!isset($user->preference)) {
1909 $user->preference = array();
1911 return;
1914 $timenow = time();
1916 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1917 // Already loaded at least once on this page. Are we up to date?
1918 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1919 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1920 return;
1922 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1923 // No change since the lastcheck on this page.
1924 $user->preference['_lastloaded'] = $timenow;
1925 return;
1929 // OK, so we have to reload all preferences.
1930 $loadedusers[$user->id] = true;
1931 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1932 $user->preference['_lastloaded'] = $timenow;
1936 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1938 * NOTE: internal function, do not call from other code.
1940 * @package core
1941 * @access private
1942 * @param integer $userid the user whose prefs were changed.
1944 function mark_user_preferences_changed($userid) {
1945 global $CFG;
1947 if (empty($userid) or isguestuser($userid)) {
1948 // No cache flags for guest and not-logged-in users.
1949 return;
1952 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1956 * Sets a preference for the specified user.
1958 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1960 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1962 * @package core
1963 * @category preference
1964 * @access public
1965 * @param string $name The key to set as preference for the specified user
1966 * @param string $value The value to set for the $name key in the specified user's
1967 * record, null means delete current value.
1968 * @param stdClass|int|null $user A moodle user object or id, null means current user
1969 * @throws coding_exception
1970 * @return bool Always true or exception
1972 function set_user_preference($name, $value, $user = null) {
1973 global $USER, $DB;
1975 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1976 throw new coding_exception('Invalid preference name in set_user_preference() call');
1979 if (is_null($value)) {
1980 // Null means delete current.
1981 return unset_user_preference($name, $user);
1982 } else if (is_object($value)) {
1983 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1984 } else if (is_array($value)) {
1985 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1987 // Value column maximum length is 1333 characters.
1988 $value = (string)$value;
1989 if (core_text::strlen($value) > 1333) {
1990 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1993 if (is_null($user)) {
1994 $user = $USER;
1995 } else if (isset($user->id)) {
1996 // It is a valid object.
1997 } else if (is_numeric($user)) {
1998 $user = (object)array('id' => (int)$user);
1999 } else {
2000 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
2003 check_user_preferences_loaded($user);
2005 if (empty($user->id) or isguestuser($user->id)) {
2006 // No permanent storage for not-logged-in users and guest.
2007 $user->preference[$name] = $value;
2008 return true;
2011 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
2012 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
2013 // Preference already set to this value.
2014 return true;
2016 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
2018 } else {
2019 $preference = new stdClass();
2020 $preference->userid = $user->id;
2021 $preference->name = $name;
2022 $preference->value = $value;
2023 $DB->insert_record('user_preferences', $preference);
2026 // Update value in cache.
2027 $user->preference[$name] = $value;
2028 // Update the $USER in case where we've not a direct reference to $USER.
2029 if ($user !== $USER && $user->id == $USER->id) {
2030 $USER->preference[$name] = $value;
2033 // Set reload flag for other sessions.
2034 mark_user_preferences_changed($user->id);
2036 return true;
2040 * Sets a whole array of preferences for the current user
2042 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2044 * @package core
2045 * @category preference
2046 * @access public
2047 * @param array $prefarray An array of key/value pairs to be set
2048 * @param stdClass|int|null $user A moodle user object or id, null means current user
2049 * @return bool Always true or exception
2051 function set_user_preferences(array $prefarray, $user = null) {
2052 foreach ($prefarray as $name => $value) {
2053 set_user_preference($name, $value, $user);
2055 return true;
2059 * Unsets a preference completely by deleting it from the database
2061 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2063 * @package core
2064 * @category preference
2065 * @access public
2066 * @param string $name The key to unset as preference for the specified user
2067 * @param stdClass|int|null $user A moodle user object or id, null means current user
2068 * @throws coding_exception
2069 * @return bool Always true or exception
2071 function unset_user_preference($name, $user = null) {
2072 global $USER, $DB;
2074 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2075 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2078 if (is_null($user)) {
2079 $user = $USER;
2080 } else if (isset($user->id)) {
2081 // It is a valid object.
2082 } else if (is_numeric($user)) {
2083 $user = (object)array('id' => (int)$user);
2084 } else {
2085 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2088 check_user_preferences_loaded($user);
2090 if (empty($user->id) or isguestuser($user->id)) {
2091 // No permanent storage for not-logged-in user and guest.
2092 unset($user->preference[$name]);
2093 return true;
2096 // Delete from DB.
2097 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2099 // Delete the preference from cache.
2100 unset($user->preference[$name]);
2101 // Update the $USER in case where we've not a direct reference to $USER.
2102 if ($user !== $USER && $user->id == $USER->id) {
2103 unset($USER->preference[$name]);
2106 // Set reload flag for other sessions.
2107 mark_user_preferences_changed($user->id);
2109 return true;
2113 * Used to fetch user preference(s)
2115 * If no arguments are supplied this function will return
2116 * all of the current user preferences as an array.
2118 * If a name is specified then this function
2119 * attempts to return that particular preference value. If
2120 * none is found, then the optional value $default is returned,
2121 * otherwise null.
2123 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2125 * @package core
2126 * @category preference
2127 * @access public
2128 * @param string $name Name of the key to use in finding a preference value
2129 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2130 * @param stdClass|int|null $user A moodle user object or id, null means current user
2131 * @throws coding_exception
2132 * @return string|mixed|null A string containing the value of a single preference. An
2133 * array with all of the preferences or null
2135 function get_user_preferences($name = null, $default = null, $user = null) {
2136 global $USER;
2138 if (is_null($name)) {
2139 // All prefs.
2140 } else if (is_numeric($name) or $name === '_lastloaded') {
2141 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2144 if (is_null($user)) {
2145 $user = $USER;
2146 } else if (isset($user->id)) {
2147 // Is a valid object.
2148 } else if (is_numeric($user)) {
2149 if ($USER->id == $user) {
2150 $user = $USER;
2151 } else {
2152 $user = (object)array('id' => (int)$user);
2154 } else {
2155 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2158 check_user_preferences_loaded($user);
2160 if (empty($name)) {
2161 // All values.
2162 return $user->preference;
2163 } else if (isset($user->preference[$name])) {
2164 // The single string value.
2165 return $user->preference[$name];
2166 } else {
2167 // Default value (null if not specified).
2168 return $default;
2172 // FUNCTIONS FOR HANDLING TIME.
2175 * Given Gregorian date parts in user time produce a GMT timestamp.
2177 * @package core
2178 * @category time
2179 * @param int $year The year part to create timestamp of
2180 * @param int $month The month part to create timestamp of
2181 * @param int $day The day part to create timestamp of
2182 * @param int $hour The hour part to create timestamp of
2183 * @param int $minute The minute part to create timestamp of
2184 * @param int $second The second part to create timestamp of
2185 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2186 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2187 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2188 * applied only if timezone is 99 or string.
2189 * @return int GMT timestamp
2191 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2192 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2193 $date->setDate((int)$year, (int)$month, (int)$day);
2194 $date->setTime((int)$hour, (int)$minute, (int)$second);
2196 $time = $date->getTimestamp();
2198 if ($time === false) {
2199 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2200 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2203 // Moodle BC DST stuff.
2204 if (!$applydst) {
2205 $time += dst_offset_on($time, $timezone);
2208 return $time;
2213 * Format a date/time (seconds) as weeks, days, hours etc as needed
2215 * Given an amount of time in seconds, returns string
2216 * formatted nicely as years, days, hours etc as needed
2218 * @package core
2219 * @category time
2220 * @uses MINSECS
2221 * @uses HOURSECS
2222 * @uses DAYSECS
2223 * @uses YEARSECS
2224 * @param int $totalsecs Time in seconds
2225 * @param stdClass $str Should be a time object
2226 * @return string A nicely formatted date/time string
2228 function format_time($totalsecs, $str = null) {
2230 $totalsecs = abs($totalsecs);
2232 if (!$str) {
2233 // Create the str structure the slow way.
2234 $str = new stdClass();
2235 $str->day = get_string('day');
2236 $str->days = get_string('days');
2237 $str->hour = get_string('hour');
2238 $str->hours = get_string('hours');
2239 $str->min = get_string('min');
2240 $str->mins = get_string('mins');
2241 $str->sec = get_string('sec');
2242 $str->secs = get_string('secs');
2243 $str->year = get_string('year');
2244 $str->years = get_string('years');
2247 $years = floor($totalsecs/YEARSECS);
2248 $remainder = $totalsecs - ($years*YEARSECS);
2249 $days = floor($remainder/DAYSECS);
2250 $remainder = $totalsecs - ($days*DAYSECS);
2251 $hours = floor($remainder/HOURSECS);
2252 $remainder = $remainder - ($hours*HOURSECS);
2253 $mins = floor($remainder/MINSECS);
2254 $secs = $remainder - ($mins*MINSECS);
2256 $ss = ($secs == 1) ? $str->sec : $str->secs;
2257 $sm = ($mins == 1) ? $str->min : $str->mins;
2258 $sh = ($hours == 1) ? $str->hour : $str->hours;
2259 $sd = ($days == 1) ? $str->day : $str->days;
2260 $sy = ($years == 1) ? $str->year : $str->years;
2262 $oyears = '';
2263 $odays = '';
2264 $ohours = '';
2265 $omins = '';
2266 $osecs = '';
2268 if ($years) {
2269 $oyears = $years .' '. $sy;
2271 if ($days) {
2272 $odays = $days .' '. $sd;
2274 if ($hours) {
2275 $ohours = $hours .' '. $sh;
2277 if ($mins) {
2278 $omins = $mins .' '. $sm;
2280 if ($secs) {
2281 $osecs = $secs .' '. $ss;
2284 if ($years) {
2285 return trim($oyears .' '. $odays);
2287 if ($days) {
2288 return trim($odays .' '. $ohours);
2290 if ($hours) {
2291 return trim($ohours .' '. $omins);
2293 if ($mins) {
2294 return trim($omins .' '. $osecs);
2296 if ($secs) {
2297 return $osecs;
2299 return get_string('now');
2303 * Returns a formatted string that represents a date in user time.
2305 * @package core
2306 * @category time
2307 * @param int $date the timestamp in UTC, as obtained from the database.
2308 * @param string $format strftime format. You should probably get this using
2309 * get_string('strftime...', 'langconfig');
2310 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2311 * not 99 then daylight saving will not be added.
2312 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2313 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2314 * If false then the leading zero is maintained.
2315 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2316 * @return string the formatted date/time.
2318 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2319 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2320 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2324 * Returns a html "time" tag with both the exact user date with timezone information
2325 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2327 * @package core
2328 * @category time
2329 * @param int $date the timestamp in UTC, as obtained from the database.
2330 * @param string $format strftime format. You should probably get this using
2331 * get_string('strftime...', 'langconfig');
2332 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2333 * not 99 then daylight saving will not be added.
2334 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2335 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2336 * If false then the leading zero is maintained.
2337 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2338 * @return string the formatted date/time.
2340 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2341 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2342 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2343 return $userdatestr;
2345 $machinedate = new DateTime();
2346 $machinedate->setTimestamp(intval($date));
2347 $machinedate->setTimezone(core_date::get_user_timezone_object());
2349 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2353 * Returns a formatted date ensuring it is UTF-8.
2355 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2356 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2358 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2359 * @param string $format strftime format.
2360 * @param int|float|string $tz the user timezone
2361 * @return string the formatted date/time.
2362 * @since Moodle 2.3.3
2364 function date_format_string($date, $format, $tz = 99) {
2366 date_default_timezone_set(core_date::get_user_timezone($tz));
2368 if (date('A', 0) === date('A', HOURSECS * 18)) {
2369 $datearray = getdate($date);
2370 $format = str_replace([
2371 '%P',
2372 '%p',
2373 ], [
2374 $datearray['hours'] < 12 ? get_string('am', 'langconfig') : get_string('pm', 'langconfig'),
2375 $datearray['hours'] < 12 ? get_string('amcaps', 'langconfig') : get_string('pmcaps', 'langconfig'),
2376 ], $format);
2379 $datestring = core_date::strftime($format, $date);
2380 core_date::set_default_server_timezone();
2382 return $datestring;
2386 * Given a $time timestamp in GMT (seconds since epoch),
2387 * returns an array that represents the Gregorian date in user time
2389 * @package core
2390 * @category time
2391 * @param int $time Timestamp in GMT
2392 * @param float|int|string $timezone user timezone
2393 * @return array An array that represents the date in user time
2395 function usergetdate($time, $timezone=99) {
2396 if ($time === null) {
2397 // PHP8 and PHP7 return different results when getdate(null) is called.
2398 // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
2399 // In the future versions of Moodle we may consider adding a strict typehint.
2400 debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER);
2401 $time = 0;
2404 date_default_timezone_set(core_date::get_user_timezone($timezone));
2405 $result = getdate($time);
2406 core_date::set_default_server_timezone();
2408 return $result;
2412 * Given a GMT timestamp (seconds since epoch), offsets it by
2413 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2415 * NOTE: this function does not include DST properly,
2416 * you should use the PHP date stuff instead!
2418 * @package core
2419 * @category time
2420 * @param int $date Timestamp in GMT
2421 * @param float|int|string $timezone user timezone
2422 * @return int
2424 function usertime($date, $timezone=99) {
2425 $userdate = new DateTime('@' . $date);
2426 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2427 $dst = dst_offset_on($date, $timezone);
2429 return $date - $userdate->getOffset() + $dst;
2433 * Get a formatted string representation of an interval between two unix timestamps.
2435 * E.g.
2436 * $intervalstring = get_time_interval_string(12345600, 12345660);
2437 * Will produce the string:
2438 * '0d 0h 1m'
2440 * @param int $time1 unix timestamp
2441 * @param int $time2 unix timestamp
2442 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2443 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2445 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2446 $dtdate = new DateTime();
2447 $dtdate->setTimeStamp($time1);
2448 $dtdate2 = new DateTime();
2449 $dtdate2->setTimeStamp($time2);
2450 $interval = $dtdate2->diff($dtdate);
2451 $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2452 return $interval->format($format);
2456 * Given a time, return the GMT timestamp of the most recent midnight
2457 * for the current user.
2459 * @package core
2460 * @category time
2461 * @param int $date Timestamp in GMT
2462 * @param float|int|string $timezone user timezone
2463 * @return int Returns a GMT timestamp
2465 function usergetmidnight($date, $timezone=99) {
2467 $userdate = usergetdate($date, $timezone);
2469 // Time of midnight of this user's day, in GMT.
2470 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2475 * Returns a string that prints the user's timezone
2477 * @package core
2478 * @category time
2479 * @param float|int|string $timezone user timezone
2480 * @return string
2482 function usertimezone($timezone=99) {
2483 $tz = core_date::get_user_timezone($timezone);
2484 return core_date::get_localised_timezone($tz);
2488 * Returns a float or a string which denotes the user's timezone
2489 * 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)
2490 * means that for this timezone there are also DST rules to be taken into account
2491 * Checks various settings and picks the most dominant of those which have a value
2493 * @package core
2494 * @category time
2495 * @param float|int|string $tz timezone to calculate GMT time offset before
2496 * calculating user timezone, 99 is default user timezone
2497 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2498 * @return float|string
2500 function get_user_timezone($tz = 99) {
2501 global $USER, $CFG;
2503 $timezones = array(
2504 $tz,
2505 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2506 isset($USER->timezone) ? $USER->timezone : 99,
2507 isset($CFG->timezone) ? $CFG->timezone : 99,
2510 $tz = 99;
2512 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2513 foreach ($timezones as $nextvalue) {
2514 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2515 $tz = $nextvalue;
2518 return is_numeric($tz) ? (float) $tz : $tz;
2522 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2523 * - Note: Daylight saving only works for string timezones and not for float.
2525 * @package core
2526 * @category time
2527 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2528 * @param int|float|string $strtimezone user timezone
2529 * @return int
2531 function dst_offset_on($time, $strtimezone = null) {
2532 $tz = core_date::get_user_timezone($strtimezone);
2533 $date = new DateTime('@' . $time);
2534 $date->setTimezone(new DateTimeZone($tz));
2535 if ($date->format('I') == '1') {
2536 if ($tz === 'Australia/Lord_Howe') {
2537 return 1800;
2539 return 3600;
2541 return 0;
2545 * Calculates when the day appears in specific month
2547 * @package core
2548 * @category time
2549 * @param int $startday starting day of the month
2550 * @param int $weekday The day when week starts (normally taken from user preferences)
2551 * @param int $month The month whose day is sought
2552 * @param int $year The year of the month whose day is sought
2553 * @return int
2555 function find_day_in_month($startday, $weekday, $month, $year) {
2556 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2558 $daysinmonth = days_in_month($month, $year);
2559 $daysinweek = count($calendartype->get_weekdays());
2561 if ($weekday == -1) {
2562 // Don't care about weekday, so return:
2563 // abs($startday) if $startday != -1
2564 // $daysinmonth otherwise.
2565 return ($startday == -1) ? $daysinmonth : abs($startday);
2568 // From now on we 're looking for a specific weekday.
2569 // Give "end of month" its actual value, since we know it.
2570 if ($startday == -1) {
2571 $startday = -1 * $daysinmonth;
2574 // Starting from day $startday, the sign is the direction.
2575 if ($startday < 1) {
2576 $startday = abs($startday);
2577 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2579 // This is the last such weekday of the month.
2580 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2581 if ($lastinmonth > $daysinmonth) {
2582 $lastinmonth -= $daysinweek;
2585 // Find the first such weekday <= $startday.
2586 while ($lastinmonth > $startday) {
2587 $lastinmonth -= $daysinweek;
2590 return $lastinmonth;
2591 } else {
2592 $indexweekday = dayofweek($startday, $month, $year);
2594 $diff = $weekday - $indexweekday;
2595 if ($diff < 0) {
2596 $diff += $daysinweek;
2599 // This is the first such weekday of the month equal to or after $startday.
2600 $firstfromindex = $startday + $diff;
2602 return $firstfromindex;
2607 * Calculate the number of days in a given month
2609 * @package core
2610 * @category time
2611 * @param int $month The month whose day count is sought
2612 * @param int $year The year of the month whose day count is sought
2613 * @return int
2615 function days_in_month($month, $year) {
2616 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2617 return $calendartype->get_num_days_in_month($year, $month);
2621 * Calculate the position in the week of a specific calendar day
2623 * @package core
2624 * @category time
2625 * @param int $day The day of the date whose position in the week is sought
2626 * @param int $month The month of the date whose position in the week is sought
2627 * @param int $year The year of the date whose position in the week is sought
2628 * @return int
2630 function dayofweek($day, $month, $year) {
2631 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2632 return $calendartype->get_weekday($year, $month, $day);
2635 // USER AUTHENTICATION AND LOGIN.
2638 * Returns full login url.
2640 * Any form submissions for authentication to this URL must include username,
2641 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2643 * @return string login url
2645 function get_login_url() {
2646 global $CFG;
2648 return "$CFG->wwwroot/login/index.php";
2652 * This function checks that the current user is logged in and has the
2653 * required privileges
2655 * This function checks that the current user is logged in, and optionally
2656 * whether they are allowed to be in a particular course and view a particular
2657 * course module.
2658 * If they are not logged in, then it redirects them to the site login unless
2659 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2660 * case they are automatically logged in as guests.
2661 * If $courseid is given and the user is not enrolled in that course then the
2662 * user is redirected to the course enrolment page.
2663 * If $cm is given and the course module is hidden and the user is not a teacher
2664 * in the course then the user is redirected to the course home page.
2666 * When $cm parameter specified, this function sets page layout to 'module'.
2667 * You need to change it manually later if some other layout needed.
2669 * @package core_access
2670 * @category access
2672 * @param mixed $courseorid id of the course or course object
2673 * @param bool $autologinguest default true
2674 * @param object $cm course module object
2675 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2676 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2677 * in order to keep redirects working properly. MDL-14495
2678 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2679 * @return mixed Void, exit, and die depending on path
2680 * @throws coding_exception
2681 * @throws require_login_exception
2682 * @throws moodle_exception
2684 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2685 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2687 // Must not redirect when byteserving already started.
2688 if (!empty($_SERVER['HTTP_RANGE'])) {
2689 $preventredirect = true;
2692 if (AJAX_SCRIPT) {
2693 // We cannot redirect for AJAX scripts either.
2694 $preventredirect = true;
2697 // Setup global $COURSE, themes, language and locale.
2698 if (!empty($courseorid)) {
2699 if (is_object($courseorid)) {
2700 $course = $courseorid;
2701 } else if ($courseorid == SITEID) {
2702 $course = clone($SITE);
2703 } else {
2704 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2706 if ($cm) {
2707 if ($cm->course != $course->id) {
2708 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2710 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2711 if (!($cm instanceof cm_info)) {
2712 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2713 // db queries so this is not really a performance concern, however it is obviously
2714 // better if you use get_fast_modinfo to get the cm before calling this.
2715 $modinfo = get_fast_modinfo($course);
2716 $cm = $modinfo->get_cm($cm->id);
2719 } else {
2720 // Do not touch global $COURSE via $PAGE->set_course(),
2721 // the reasons is we need to be able to call require_login() at any time!!
2722 $course = $SITE;
2723 if ($cm) {
2724 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2728 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2729 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2730 // risk leading the user back to the AJAX request URL.
2731 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2732 $setwantsurltome = false;
2735 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2736 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2737 if ($preventredirect) {
2738 throw new require_login_session_timeout_exception();
2739 } else {
2740 if ($setwantsurltome) {
2741 $SESSION->wantsurl = qualified_me();
2743 redirect(get_login_url());
2747 // If the user is not even logged in yet then make sure they are.
2748 if (!isloggedin()) {
2749 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2750 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2751 // Misconfigured site guest, just redirect to login page.
2752 redirect(get_login_url());
2753 exit; // Never reached.
2755 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2756 complete_user_login($guest);
2757 $USER->autologinguest = true;
2758 $SESSION->lang = $lang;
2759 } else {
2760 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2761 if ($preventredirect) {
2762 throw new require_login_exception('You are not logged in');
2765 if ($setwantsurltome) {
2766 $SESSION->wantsurl = qualified_me();
2769 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2770 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
2771 foreach($authsequence as $authname) {
2772 $authplugin = get_auth_plugin($authname);
2773 $authplugin->pre_loginpage_hook();
2774 if (isloggedin()) {
2775 if ($cm) {
2776 $modinfo = get_fast_modinfo($course);
2777 $cm = $modinfo->get_cm($cm->id);
2779 set_access_log_user();
2780 break;
2784 // If we're still not logged in then go to the login page
2785 if (!isloggedin()) {
2786 redirect(get_login_url());
2787 exit; // Never reached.
2792 // Loginas as redirection if needed.
2793 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2794 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2795 if ($USER->loginascontext->instanceid != $course->id) {
2796 throw new \moodle_exception('loginasonecourse', '',
2797 $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2802 // Check whether the user should be changing password (but only if it is REALLY them).
2803 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2804 $userauth = get_auth_plugin($USER->auth);
2805 if ($userauth->can_change_password() and !$preventredirect) {
2806 if ($setwantsurltome) {
2807 $SESSION->wantsurl = qualified_me();
2809 if ($changeurl = $userauth->change_password_url()) {
2810 // Use plugin custom url.
2811 redirect($changeurl);
2812 } else {
2813 // Use moodle internal method.
2814 redirect($CFG->wwwroot .'/login/change_password.php');
2816 } else if ($userauth->can_change_password()) {
2817 throw new moodle_exception('forcepasswordchangenotice');
2818 } else {
2819 throw new moodle_exception('nopasswordchangeforced', 'auth');
2823 // Check that the user account is properly set up. If we can't redirect to
2824 // edit their profile and this is not a WS request, perform just the lax check.
2825 // It will allow them to use filepicker on the profile edit page.
2827 if ($preventredirect && !WS_SERVER) {
2828 $usernotfullysetup = user_not_fully_set_up($USER, false);
2829 } else {
2830 $usernotfullysetup = user_not_fully_set_up($USER, true);
2833 if ($usernotfullysetup) {
2834 if ($preventredirect) {
2835 throw new moodle_exception('usernotfullysetup');
2837 if ($setwantsurltome) {
2838 $SESSION->wantsurl = qualified_me();
2840 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2843 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2844 sesskey();
2846 if (\core\session\manager::is_loggedinas()) {
2847 // During a "logged in as" session we should force all content to be cleaned because the
2848 // logged in user will be viewing potentially malicious user generated content.
2849 // See MDL-63786 for more details.
2850 $CFG->forceclean = true;
2853 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2855 // Do not bother admins with any formalities, except for activities pending deletion.
2856 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2857 // Set the global $COURSE.
2858 if ($cm) {
2859 $PAGE->set_cm($cm, $course);
2860 $PAGE->set_pagelayout('incourse');
2861 } else if (!empty($courseorid)) {
2862 $PAGE->set_course($course);
2864 // Set accesstime or the user will appear offline which messes up messaging.
2865 // Do not update access time for webservice or ajax requests.
2866 if (!WS_SERVER && !AJAX_SCRIPT) {
2867 user_accesstime_log($course->id);
2870 foreach ($afterlogins as $plugintype => $plugins) {
2871 foreach ($plugins as $pluginfunction) {
2872 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2875 return;
2878 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2879 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2880 if (!defined('NO_SITEPOLICY_CHECK')) {
2881 define('NO_SITEPOLICY_CHECK', false);
2884 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2885 // Do not test if the script explicitly asked for skipping the site policies check.
2886 // Or if the user auth type is webservice.
2887 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK && $USER->auth !== 'webservice') {
2888 $manager = new \core_privacy\local\sitepolicy\manager();
2889 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2890 if ($preventredirect) {
2891 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2893 if ($setwantsurltome) {
2894 $SESSION->wantsurl = qualified_me();
2896 redirect($policyurl);
2900 // Fetch the system context, the course context, and prefetch its child contexts.
2901 $sysctx = context_system::instance();
2902 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2903 if ($cm) {
2904 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2905 } else {
2906 $cmcontext = null;
2909 // If the site is currently under maintenance, then print a message.
2910 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2911 if ($preventredirect) {
2912 throw new require_login_exception('Maintenance in progress');
2914 $PAGE->set_context(null);
2915 print_maintenance_message();
2918 // Make sure the course itself is not hidden.
2919 if ($course->id == SITEID) {
2920 // Frontpage can not be hidden.
2921 } else {
2922 if (is_role_switched($course->id)) {
2923 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2924 } else {
2925 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2926 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2927 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2928 if ($preventredirect) {
2929 throw new require_login_exception('Course is hidden');
2931 $PAGE->set_context(null);
2932 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2933 // the navigation will mess up when trying to find it.
2934 navigation_node::override_active_url(new moodle_url('/'));
2935 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2940 // Is the user enrolled?
2941 if ($course->id == SITEID) {
2942 // Everybody is enrolled on the frontpage.
2943 } else {
2944 if (\core\session\manager::is_loggedinas()) {
2945 // Make sure the REAL person can access this course first.
2946 $realuser = \core\session\manager::get_realuser();
2947 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2948 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2949 if ($preventredirect) {
2950 throw new require_login_exception('Invalid course login-as access');
2952 $PAGE->set_context(null);
2953 echo $OUTPUT->header();
2954 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2958 $access = false;
2960 if (is_role_switched($course->id)) {
2961 // Ok, user had to be inside this course before the switch.
2962 $access = true;
2964 } else if (is_viewing($coursecontext, $USER)) {
2965 // Ok, no need to mess with enrol.
2966 $access = true;
2968 } else {
2969 if (isset($USER->enrol['enrolled'][$course->id])) {
2970 if ($USER->enrol['enrolled'][$course->id] > time()) {
2971 $access = true;
2972 if (isset($USER->enrol['tempguest'][$course->id])) {
2973 unset($USER->enrol['tempguest'][$course->id]);
2974 remove_temp_course_roles($coursecontext);
2976 } else {
2977 // Expired.
2978 unset($USER->enrol['enrolled'][$course->id]);
2981 if (isset($USER->enrol['tempguest'][$course->id])) {
2982 if ($USER->enrol['tempguest'][$course->id] == 0) {
2983 $access = true;
2984 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2985 $access = true;
2986 } else {
2987 // Expired.
2988 unset($USER->enrol['tempguest'][$course->id]);
2989 remove_temp_course_roles($coursecontext);
2993 if (!$access) {
2994 // Cache not ok.
2995 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2996 if ($until !== false) {
2997 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2998 if ($until == 0) {
2999 $until = ENROL_MAX_TIMESTAMP;
3001 $USER->enrol['enrolled'][$course->id] = $until;
3002 $access = true;
3004 } else if (core_course_category::can_view_course_info($course)) {
3005 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3006 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3007 $enrols = enrol_get_plugins(true);
3008 // First ask all enabled enrol instances in course if they want to auto enrol user.
3009 foreach ($instances as $instance) {
3010 if (!isset($enrols[$instance->enrol])) {
3011 continue;
3013 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3014 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3015 if ($until !== false) {
3016 if ($until == 0) {
3017 $until = ENROL_MAX_TIMESTAMP;
3019 $USER->enrol['enrolled'][$course->id] = $until;
3020 $access = true;
3021 break;
3024 // If not enrolled yet try to gain temporary guest access.
3025 if (!$access) {
3026 foreach ($instances as $instance) {
3027 if (!isset($enrols[$instance->enrol])) {
3028 continue;
3030 // Get a duration for the guest access, a timestamp in the future or false.
3031 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3032 if ($until !== false and $until > time()) {
3033 $USER->enrol['tempguest'][$course->id] = $until;
3034 $access = true;
3035 break;
3039 } else {
3040 // User is not enrolled and is not allowed to browse courses here.
3041 if ($preventredirect) {
3042 throw new require_login_exception('Course is not available');
3044 $PAGE->set_context(null);
3045 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3046 // the navigation will mess up when trying to find it.
3047 navigation_node::override_active_url(new moodle_url('/'));
3048 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3053 if (!$access) {
3054 if ($preventredirect) {
3055 throw new require_login_exception('Not enrolled');
3057 if ($setwantsurltome) {
3058 $SESSION->wantsurl = qualified_me();
3060 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3064 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3065 if ($cm && $cm->deletioninprogress) {
3066 if ($preventredirect) {
3067 throw new moodle_exception('activityisscheduledfordeletion');
3069 require_once($CFG->dirroot . '/course/lib.php');
3070 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3073 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3074 if ($cm && !$cm->uservisible) {
3075 if ($preventredirect) {
3076 throw new require_login_exception('Activity is hidden');
3078 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3079 $PAGE->set_course($course);
3080 $renderer = $PAGE->get_renderer('course');
3081 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3082 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3085 // Set the global $COURSE.
3086 if ($cm) {
3087 $PAGE->set_cm($cm, $course);
3088 $PAGE->set_pagelayout('incourse');
3089 } else if (!empty($courseorid)) {
3090 $PAGE->set_course($course);
3093 foreach ($afterlogins as $plugintype => $plugins) {
3094 foreach ($plugins as $pluginfunction) {
3095 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3099 // Finally access granted, update lastaccess times.
3100 // Do not update access time for webservice or ajax requests.
3101 if (!WS_SERVER && !AJAX_SCRIPT) {
3102 user_accesstime_log($course->id);
3107 * A convenience function for where we must be logged in as admin
3108 * @return void
3110 function require_admin() {
3111 require_login(null, false);
3112 require_capability('moodle/site:config', context_system::instance());
3116 * This function just makes sure a user is logged out.
3118 * @package core_access
3119 * @category access
3121 function require_logout() {
3122 global $USER, $DB;
3124 if (!isloggedin()) {
3125 // This should not happen often, no need for hooks or events here.
3126 \core\session\manager::terminate_current();
3127 return;
3130 // Execute hooks before action.
3131 $authplugins = array();
3132 $authsequence = get_enabled_auth_plugins();
3133 foreach ($authsequence as $authname) {
3134 $authplugins[$authname] = get_auth_plugin($authname);
3135 $authplugins[$authname]->prelogout_hook();
3138 // Store info that gets removed during logout.
3139 $sid = session_id();
3140 $event = \core\event\user_loggedout::create(
3141 array(
3142 'userid' => $USER->id,
3143 'objectid' => $USER->id,
3144 'other' => array('sessionid' => $sid),
3147 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3148 $event->add_record_snapshot('sessions', $session);
3151 // Clone of $USER object to be used by auth plugins.
3152 $user = fullclone($USER);
3154 // Delete session record and drop $_SESSION content.
3155 \core\session\manager::terminate_current();
3157 // Trigger event AFTER action.
3158 $event->trigger();
3160 // Hook to execute auth plugins redirection after event trigger.
3161 foreach ($authplugins as $authplugin) {
3162 $authplugin->postlogout_hook($user);
3167 * Weaker version of require_login()
3169 * This is a weaker version of {@link require_login()} which only requires login
3170 * when called from within a course rather than the site page, unless
3171 * the forcelogin option is turned on.
3172 * @see require_login()
3174 * @package core_access
3175 * @category access
3177 * @param mixed $courseorid The course object or id in question
3178 * @param bool $autologinguest Allow autologin guests if that is wanted
3179 * @param object $cm Course activity module if known
3180 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3181 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3182 * in order to keep redirects working properly. MDL-14495
3183 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3184 * @return void
3185 * @throws coding_exception
3187 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3188 global $CFG, $PAGE, $SITE;
3189 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3190 or (!is_object($courseorid) and $courseorid == SITEID));
3191 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3192 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3193 // db queries so this is not really a performance concern, however it is obviously
3194 // better if you use get_fast_modinfo to get the cm before calling this.
3195 if (is_object($courseorid)) {
3196 $course = $courseorid;
3197 } else {
3198 $course = clone($SITE);
3200 $modinfo = get_fast_modinfo($course);
3201 $cm = $modinfo->get_cm($cm->id);
3203 if (!empty($CFG->forcelogin)) {
3204 // Login required for both SITE and courses.
3205 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3207 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3208 // Always login for hidden activities.
3209 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3211 } else if (isloggedin() && !isguestuser()) {
3212 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3213 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3215 } else if ($issite) {
3216 // Login for SITE not required.
3217 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3218 if (!empty($courseorid)) {
3219 if (is_object($courseorid)) {
3220 $course = $courseorid;
3221 } else {
3222 $course = clone $SITE;
3224 if ($cm) {
3225 if ($cm->course != $course->id) {
3226 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3228 $PAGE->set_cm($cm, $course);
3229 $PAGE->set_pagelayout('incourse');
3230 } else {
3231 $PAGE->set_course($course);
3233 } else {
3234 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3235 $PAGE->set_course($PAGE->course);
3237 // Do not update access time for webservice or ajax requests.
3238 if (!WS_SERVER && !AJAX_SCRIPT) {
3239 user_accesstime_log(SITEID);
3241 return;
3243 } else {
3244 // Course login always required.
3245 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3250 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3252 * @param string $keyvalue the key value
3253 * @param string $script unique script identifier
3254 * @param int $instance instance id
3255 * @return stdClass the key entry in the user_private_key table
3256 * @since Moodle 3.2
3257 * @throws moodle_exception
3259 function validate_user_key($keyvalue, $script, $instance) {
3260 global $DB;
3262 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3263 throw new \moodle_exception('invalidkey');
3266 if (!empty($key->validuntil) and $key->validuntil < time()) {
3267 throw new \moodle_exception('expiredkey');
3270 if ($key->iprestriction) {
3271 $remoteaddr = getremoteaddr(null);
3272 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3273 throw new \moodle_exception('ipmismatch');
3276 return $key;
3280 * Require key login. Function terminates with error if key not found or incorrect.
3282 * @uses NO_MOODLE_COOKIES
3283 * @uses PARAM_ALPHANUM
3284 * @param string $script unique script identifier
3285 * @param int $instance optional instance id
3286 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3287 * @return int Instance ID
3289 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3290 global $DB;
3292 if (!NO_MOODLE_COOKIES) {
3293 throw new \moodle_exception('sessioncookiesdisable');
3296 // Extra safety.
3297 \core\session\manager::write_close();
3299 if (null === $keyvalue) {
3300 $keyvalue = required_param('key', PARAM_ALPHANUM);
3303 $key = validate_user_key($keyvalue, $script, $instance);
3305 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3306 throw new \moodle_exception('invaliduserid');
3309 core_user::require_active_user($user, true, true);
3311 // Emulate normal session.
3312 enrol_check_plugins($user, false);
3313 \core\session\manager::set_user($user);
3315 // Note we are not using normal login.
3316 if (!defined('USER_KEY_LOGIN')) {
3317 define('USER_KEY_LOGIN', true);
3320 // Return instance id - it might be empty.
3321 return $key->instance;
3325 * Creates a new private user access key.
3327 * @param string $script unique target identifier
3328 * @param int $userid
3329 * @param int $instance optional instance id
3330 * @param string $iprestriction optional ip restricted access
3331 * @param int $validuntil key valid only until given data
3332 * @return string access key value
3334 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3335 global $DB;
3337 $key = new stdClass();
3338 $key->script = $script;
3339 $key->userid = $userid;
3340 $key->instance = $instance;
3341 $key->iprestriction = $iprestriction;
3342 $key->validuntil = $validuntil;
3343 $key->timecreated = time();
3345 // Something long and unique.
3346 $key->value = md5($userid.'_'.time().random_string(40));
3347 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3348 // Must be unique.
3349 $key->value = md5($userid.'_'.time().random_string(40));
3351 $DB->insert_record('user_private_key', $key);
3352 return $key->value;
3356 * Delete the user's new private user access keys for a particular script.
3358 * @param string $script unique target identifier
3359 * @param int $userid
3360 * @return void
3362 function delete_user_key($script, $userid) {
3363 global $DB;
3364 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3368 * Gets a private user access key (and creates one if one doesn't exist).
3370 * @param string $script unique target identifier
3371 * @param int $userid
3372 * @param int $instance optional instance id
3373 * @param string $iprestriction optional ip restricted access
3374 * @param int $validuntil key valid only until given date
3375 * @return string access key value
3377 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3378 global $DB;
3380 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3381 'instance' => $instance, 'iprestriction' => $iprestriction,
3382 'validuntil' => $validuntil))) {
3383 return $key->value;
3384 } else {
3385 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3391 * Modify the user table by setting the currently logged in user's last login to now.
3393 * @return bool Always returns true
3395 function update_user_login_times() {
3396 global $USER, $DB, $SESSION;
3398 if (isguestuser()) {
3399 // Do not update guest access times/ips for performance.
3400 return true;
3403 if (defined('USER_KEY_LOGIN') && USER_KEY_LOGIN === true) {
3404 // Do not update user login time when using user key login.
3405 return true;
3408 $now = time();
3410 $user = new stdClass();
3411 $user->id = $USER->id;
3413 // Make sure all users that logged in have some firstaccess.
3414 if ($USER->firstaccess == 0) {
3415 $USER->firstaccess = $user->firstaccess = $now;
3418 // Store the previous current as lastlogin.
3419 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3421 $USER->currentlogin = $user->currentlogin = $now;
3423 // Function user_accesstime_log() may not update immediately, better do it here.
3424 $USER->lastaccess = $user->lastaccess = $now;
3425 $SESSION->userpreviousip = $USER->lastip;
3426 $USER->lastip = $user->lastip = getremoteaddr();
3428 // Note: do not call user_update_user() here because this is part of the login process,
3429 // the login event means that these fields were updated.
3430 $DB->update_record('user', $user);
3431 return true;
3435 * Determines if a user has completed setting up their account.
3437 * The lax mode (with $strict = false) has been introduced for special cases
3438 * only where we want to skip certain checks intentionally. This is valid in
3439 * certain mnet or ajax scenarios when the user cannot / should not be
3440 * redirected to edit their profile. In most cases, you should perform the
3441 * strict check.
3443 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3444 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3445 * @return bool
3447 function user_not_fully_set_up($user, $strict = true) {
3448 global $CFG, $SESSION, $USER;
3449 require_once($CFG->dirroot.'/user/profile/lib.php');
3451 // If the user is setup then store this in the session to avoid re-checking.
3452 // Some edge cases are when the users email starts to bounce or the
3453 // configuration for custom fields has changed while they are logged in so
3454 // we re-check this fully every hour for the rare cases it has changed.
3455 if (isset($USER->id) && isset($user->id) && $USER->id === $user->id &&
3456 isset($SESSION->fullysetupstrict) && (time() - $SESSION->fullysetupstrict) < HOURSECS) {
3457 return false;
3460 if (isguestuser($user)) {
3461 return false;
3464 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3465 return true;
3468 if ($strict) {
3469 if (empty($user->id)) {
3470 // Strict mode can be used with existing accounts only.
3471 return true;
3473 if (!profile_has_required_custom_fields_set($user->id)) {
3474 return true;
3476 if (isset($USER->id) && isset($user->id) && $USER->id === $user->id) {
3477 $SESSION->fullysetupstrict = time();
3481 return false;
3485 * Check whether the user has exceeded the bounce threshold
3487 * @param stdClass $user A {@link $USER} object
3488 * @return bool true => User has exceeded bounce threshold
3490 function over_bounce_threshold($user) {
3491 global $CFG, $DB;
3493 if (empty($CFG->handlebounces)) {
3494 return false;
3497 if (empty($user->id)) {
3498 // No real (DB) user, nothing to do here.
3499 return false;
3502 // Set sensible defaults.
3503 if (empty($CFG->minbounces)) {
3504 $CFG->minbounces = 10;
3506 if (empty($CFG->bounceratio)) {
3507 $CFG->bounceratio = .20;
3509 $bouncecount = 0;
3510 $sendcount = 0;
3511 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3512 $bouncecount = $bounce->value;
3514 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3515 $sendcount = $send->value;
3517 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3521 * Used to increment or reset email sent count
3523 * @param stdClass $user object containing an id
3524 * @param bool $reset will reset the count to 0
3525 * @return void
3527 function set_send_count($user, $reset=false) {
3528 global $DB;
3530 if (empty($user->id)) {
3531 // No real (DB) user, nothing to do here.
3532 return;
3535 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3536 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3537 $DB->update_record('user_preferences', $pref);
3538 } else if (!empty($reset)) {
3539 // If it's not there and we're resetting, don't bother. Make a new one.
3540 $pref = new stdClass();
3541 $pref->name = 'email_send_count';
3542 $pref->value = 1;
3543 $pref->userid = $user->id;
3544 $DB->insert_record('user_preferences', $pref, false);
3549 * Increment or reset user's email bounce count
3551 * @param stdClass $user object containing an id
3552 * @param bool $reset will reset the count to 0
3554 function set_bounce_count($user, $reset=false) {
3555 global $DB;
3557 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3558 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3559 $DB->update_record('user_preferences', $pref);
3560 } else if (!empty($reset)) {
3561 // If it's not there and we're resetting, don't bother. Make a new one.
3562 $pref = new stdClass();
3563 $pref->name = 'email_bounce_count';
3564 $pref->value = 1;
3565 $pref->userid = $user->id;
3566 $DB->insert_record('user_preferences', $pref, false);
3571 * Determines if the logged in user is currently moving an activity
3573 * @param int $courseid The id of the course being tested
3574 * @return bool
3576 function ismoving($courseid) {
3577 global $USER;
3579 if (!empty($USER->activitycopy)) {
3580 return ($USER->activitycopycourse == $courseid);
3582 return false;
3586 * Returns a persons full name
3588 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3589 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3590 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3591 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3593 * @param stdClass $user A {@link $USER} object to get full name of.
3594 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3595 * @return string
3597 function fullname($user, $override=false) {
3598 global $CFG, $SESSION;
3600 if (!isset($user->firstname) and !isset($user->lastname)) {
3601 return '';
3604 // Get all of the name fields.
3605 $allnames = \core_user\fields::get_name_fields();
3606 if ($CFG->debugdeveloper) {
3607 foreach ($allnames as $allname) {
3608 if (!property_exists($user, $allname)) {
3609 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3610 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3611 // Message has been sent, no point in sending the message multiple times.
3612 break;
3617 if (!$override) {
3618 if (!empty($CFG->forcefirstname)) {
3619 $user->firstname = $CFG->forcefirstname;
3621 if (!empty($CFG->forcelastname)) {
3622 $user->lastname = $CFG->forcelastname;
3626 if (!empty($SESSION->fullnamedisplay)) {
3627 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3630 $template = null;
3631 // If the fullnamedisplay setting is available, set the template to that.
3632 if (isset($CFG->fullnamedisplay)) {
3633 $template = $CFG->fullnamedisplay;
3635 // If the template is empty, or set to language, return the language string.
3636 if ((empty($template) || $template == 'language') && !$override) {
3637 return get_string('fullnamedisplay', null, $user);
3640 // Check to see if we are displaying according to the alternative full name format.
3641 if ($override) {
3642 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3643 // Default to show just the user names according to the fullnamedisplay string.
3644 return get_string('fullnamedisplay', null, $user);
3645 } else {
3646 // If the override is true, then change the template to use the complete name.
3647 $template = $CFG->alternativefullnameformat;
3651 $requirednames = array();
3652 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3653 foreach ($allnames as $allname) {
3654 if (strpos($template, $allname) !== false) {
3655 $requirednames[] = $allname;
3659 $displayname = $template;
3660 // Switch in the actual data into the template.
3661 foreach ($requirednames as $altname) {
3662 if (isset($user->$altname)) {
3663 // Using empty() on the below if statement causes breakages.
3664 if ((string)$user->$altname == '') {
3665 $displayname = str_replace($altname, 'EMPTY', $displayname);
3666 } else {
3667 $displayname = str_replace($altname, $user->$altname, $displayname);
3669 } else {
3670 $displayname = str_replace($altname, 'EMPTY', $displayname);
3673 // Tidy up any misc. characters (Not perfect, but gets most characters).
3674 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3675 // katakana and parenthesis.
3676 $patterns = array();
3677 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3678 // filled in by a user.
3679 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3680 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3681 // This regular expression is to remove any double spaces in the display name.
3682 $patterns[] = '/\s{2,}/u';
3683 foreach ($patterns as $pattern) {
3684 $displayname = preg_replace($pattern, ' ', $displayname);
3687 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3688 $displayname = trim($displayname);
3689 if (empty($displayname)) {
3690 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3691 // people in general feel is a good setting to fall back on.
3692 $displayname = $user->firstname;
3694 return $displayname;
3698 * Reduces lines of duplicated code for getting user name fields.
3700 * See also {@link user_picture::unalias()}
3702 * @param object $addtoobject Object to add user name fields to.
3703 * @param object $secondobject Object that contains user name field information.
3704 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3705 * @param array $additionalfields Additional fields to be matched with data in the second object.
3706 * The key can be set to the user table field name.
3707 * @return object User name fields.
3709 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3710 $fields = [];
3711 foreach (\core_user\fields::get_name_fields() as $field) {
3712 $fields[$field] = $prefix . $field;
3714 if ($additionalfields) {
3715 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3716 // the key is a number and then sets the key to the array value.
3717 foreach ($additionalfields as $key => $value) {
3718 if (is_numeric($key)) {
3719 $additionalfields[$value] = $prefix . $value;
3720 unset($additionalfields[$key]);
3721 } else {
3722 $additionalfields[$key] = $prefix . $value;
3725 $fields = array_merge($fields, $additionalfields);
3727 foreach ($fields as $key => $field) {
3728 // Important that we have all of the user name fields present in the object that we are sending back.
3729 $addtoobject->$key = '';
3730 if (isset($secondobject->$field)) {
3731 $addtoobject->$key = $secondobject->$field;
3734 return $addtoobject;
3738 * Returns an array of values in order of occurance in a provided string.
3739 * The key in the result is the character postion in the string.
3741 * @param array $values Values to be found in the string format
3742 * @param string $stringformat The string which may contain values being searched for.
3743 * @return array An array of values in order according to placement in the string format.
3745 function order_in_string($values, $stringformat) {
3746 $valuearray = array();
3747 foreach ($values as $value) {
3748 $pattern = "/$value\b/";
3749 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3750 if (preg_match($pattern, $stringformat)) {
3751 $replacement = "thing";
3752 // Replace the value with something more unique to ensure we get the right position when using strpos().
3753 $newformat = preg_replace($pattern, $replacement, $stringformat);
3754 $position = strpos($newformat, $replacement);
3755 $valuearray[$position] = $value;
3758 ksort($valuearray);
3759 return $valuearray;
3763 * Returns whether a given authentication plugin exists.
3765 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3766 * @return boolean Whether the plugin is available.
3768 function exists_auth_plugin($auth) {
3769 global $CFG;
3771 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3772 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3774 return false;
3778 * Checks if a given plugin is in the list of enabled authentication plugins.
3780 * @param string $auth Authentication plugin.
3781 * @return boolean Whether the plugin is enabled.
3783 function is_enabled_auth($auth) {
3784 if (empty($auth)) {
3785 return false;
3788 $enabled = get_enabled_auth_plugins();
3790 return in_array($auth, $enabled);
3794 * Returns an authentication plugin instance.
3796 * @param string $auth name of authentication plugin
3797 * @return auth_plugin_base An instance of the required authentication plugin.
3799 function get_auth_plugin($auth) {
3800 global $CFG;
3802 // Check the plugin exists first.
3803 if (! exists_auth_plugin($auth)) {
3804 throw new \moodle_exception('authpluginnotfound', 'debug', '', $auth);
3807 // Return auth plugin instance.
3808 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3809 $class = "auth_plugin_$auth";
3810 return new $class;
3814 * Returns array of active auth plugins.
3816 * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
3817 * @return array
3819 function get_enabled_auth_plugins($fix=false) {
3820 global $CFG;
3822 $default = array('manual', 'nologin');
3824 if (empty($CFG->auth)) {
3825 $auths = array();
3826 } else {
3827 $auths = explode(',', $CFG->auth);
3830 $auths = array_unique($auths);
3831 $oldauthconfig = implode(',', $auths);
3832 foreach ($auths as $k => $authname) {
3833 if (in_array($authname, $default)) {
3834 // The manual and nologin plugin never need to be stored.
3835 unset($auths[$k]);
3836 } else if (!exists_auth_plugin($authname)) {
3837 debugging(get_string('authpluginnotfound', 'debug', $authname));
3838 unset($auths[$k]);
3842 // Ideally only explicit interaction from a human admin should trigger a
3843 // change in auth config, see MDL-70424 for details.
3844 if ($fix) {
3845 $newconfig = implode(',', $auths);
3846 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3847 add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
3848 set_config('auth', $newconfig);
3852 return (array_merge($default, $auths));
3856 * Returns true if an internal authentication method is being used.
3857 * if method not specified then, global default is assumed
3859 * @param string $auth Form of authentication required
3860 * @return bool
3862 function is_internal_auth($auth) {
3863 // Throws error if bad $auth.
3864 $authplugin = get_auth_plugin($auth);
3865 return $authplugin->is_internal();
3869 * Returns true if the user is a 'restored' one.
3871 * Used in the login process to inform the user and allow him/her to reset the password
3873 * @param string $username username to be checked
3874 * @return bool
3876 function is_restored_user($username) {
3877 global $CFG, $DB;
3879 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3883 * Returns an array of user fields
3885 * @return array User field/column names
3887 function get_user_fieldnames() {
3888 global $DB;
3890 $fieldarray = $DB->get_columns('user');
3891 unset($fieldarray['id']);
3892 $fieldarray = array_keys($fieldarray);
3894 return $fieldarray;
3898 * Returns the string of the language for the new user.
3900 * @return string language for the new user
3902 function get_newuser_language() {
3903 global $CFG, $SESSION;
3904 return (!empty($CFG->autolangusercreation) && !empty($SESSION->lang)) ? $SESSION->lang : $CFG->lang;
3908 * Creates a bare-bones user record
3910 * @todo Outline auth types and provide code example
3912 * @param string $username New user's username to add to record
3913 * @param string $password New user's password to add to record
3914 * @param string $auth Form of authentication required
3915 * @return stdClass A complete user object
3917 function create_user_record($username, $password, $auth = 'manual') {
3918 global $CFG, $DB, $SESSION;
3919 require_once($CFG->dirroot.'/user/profile/lib.php');
3920 require_once($CFG->dirroot.'/user/lib.php');
3922 // Just in case check text case.
3923 $username = trim(core_text::strtolower($username));
3925 $authplugin = get_auth_plugin($auth);
3926 $customfields = $authplugin->get_custom_user_profile_fields();
3927 $newuser = new stdClass();
3928 if ($newinfo = $authplugin->get_userinfo($username)) {
3929 $newinfo = truncate_userinfo($newinfo);
3930 foreach ($newinfo as $key => $value) {
3931 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3932 $newuser->$key = $value;
3937 if (!empty($newuser->email)) {
3938 if (email_is_not_allowed($newuser->email)) {
3939 unset($newuser->email);
3943 $newuser->auth = $auth;
3944 $newuser->username = $username;
3946 // Fix for MDL-8480
3947 // user CFG lang for user if $newuser->lang is empty
3948 // or $user->lang is not an installed language.
3949 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3950 $newuser->lang = get_newuser_language();
3952 $newuser->confirmed = 1;
3953 $newuser->lastip = getremoteaddr();
3954 $newuser->timecreated = time();
3955 $newuser->timemodified = $newuser->timecreated;
3956 $newuser->mnethostid = $CFG->mnet_localhost_id;
3958 $newuser->id = user_create_user($newuser, false, false);
3960 // Save user profile data.
3961 profile_save_data($newuser);
3963 $user = get_complete_user_data('id', $newuser->id);
3964 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3965 set_user_preference('auth_forcepasswordchange', 1, $user);
3967 // Set the password.
3968 update_internal_user_password($user, $password);
3970 // Trigger event.
3971 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3973 return $user;
3977 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3979 * @param string $username user's username to update the record
3980 * @return stdClass A complete user object
3982 function update_user_record($username) {
3983 global $DB, $CFG;
3984 // Just in case check text case.
3985 $username = trim(core_text::strtolower($username));
3987 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3988 return update_user_record_by_id($oldinfo->id);
3992 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3994 * @param int $id user id
3995 * @return stdClass A complete user object
3997 function update_user_record_by_id($id) {
3998 global $DB, $CFG;
3999 require_once($CFG->dirroot."/user/profile/lib.php");
4000 require_once($CFG->dirroot.'/user/lib.php');
4002 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
4003 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
4005 $newuser = array();
4006 $userauth = get_auth_plugin($oldinfo->auth);
4008 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4009 $newinfo = truncate_userinfo($newinfo);
4010 $customfields = $userauth->get_custom_user_profile_fields();
4012 foreach ($newinfo as $key => $value) {
4013 $iscustom = in_array($key, $customfields);
4014 if (!$iscustom) {
4015 $key = strtolower($key);
4017 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4018 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4019 // Unknown or must not be changed.
4020 continue;
4022 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
4023 continue;
4025 $confval = $userauth->config->{'field_updatelocal_' . $key};
4026 $lockval = $userauth->config->{'field_lock_' . $key};
4027 if ($confval === 'onlogin') {
4028 // MDL-4207 Don't overwrite modified user profile values with
4029 // empty LDAP values when 'unlocked if empty' is set. The purpose
4030 // of the setting 'unlocked if empty' is to allow the user to fill
4031 // in a value for the selected field _if LDAP is giving
4032 // nothing_ for this field. Thus it makes sense to let this value
4033 // stand in until LDAP is giving a value for this field.
4034 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4035 if ($iscustom || (in_array($key, $userauth->userfields) &&
4036 ((string)$oldinfo->$key !== (string)$value))) {
4037 $newuser[$key] = (string)$value;
4042 if ($newuser) {
4043 $newuser['id'] = $oldinfo->id;
4044 $newuser['timemodified'] = time();
4045 user_update_user((object) $newuser, false, false);
4047 // Save user profile data.
4048 profile_save_data((object) $newuser);
4050 // Trigger event.
4051 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4055 return get_complete_user_data('id', $oldinfo->id);
4059 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4061 * @param array $info Array of user properties to truncate if needed
4062 * @return array The now truncated information that was passed in
4064 function truncate_userinfo(array $info) {
4065 // Define the limits.
4066 $limit = array(
4067 'username' => 100,
4068 'idnumber' => 255,
4069 'firstname' => 100,
4070 'lastname' => 100,
4071 'email' => 100,
4072 'phone1' => 20,
4073 'phone2' => 20,
4074 'institution' => 255,
4075 'department' => 255,
4076 'address' => 255,
4077 'city' => 120,
4078 'country' => 2,
4081 // Apply where needed.
4082 foreach (array_keys($info) as $key) {
4083 if (!empty($limit[$key])) {
4084 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4088 return $info;
4092 * Marks user deleted in internal user database and notifies the auth plugin.
4093 * Also unenrols user from all roles and does other cleanup.
4095 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4097 * @param stdClass $user full user object before delete
4098 * @return boolean success
4099 * @throws coding_exception if invalid $user parameter detected
4101 function delete_user(stdClass $user) {
4102 global $CFG, $DB, $SESSION;
4103 require_once($CFG->libdir.'/grouplib.php');
4104 require_once($CFG->libdir.'/gradelib.php');
4105 require_once($CFG->dirroot.'/message/lib.php');
4106 require_once($CFG->dirroot.'/user/lib.php');
4108 // Make sure nobody sends bogus record type as parameter.
4109 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4110 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4113 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4114 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4115 debugging('Attempt to delete unknown user account.');
4116 return false;
4119 // There must be always exactly one guest record, originally the guest account was identified by username only,
4120 // now we use $CFG->siteguest for performance reasons.
4121 if ($user->username === 'guest' or isguestuser($user)) {
4122 debugging('Guest user account can not be deleted.');
4123 return false;
4126 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4127 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4128 if ($user->auth === 'manual' and is_siteadmin($user)) {
4129 debugging('Local administrator accounts can not be deleted.');
4130 return false;
4133 // Allow plugins to use this user object before we completely delete it.
4134 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4135 foreach ($pluginsfunction as $plugintype => $plugins) {
4136 foreach ($plugins as $pluginfunction) {
4137 $pluginfunction($user);
4142 // Keep user record before updating it, as we have to pass this to user_deleted event.
4143 $olduser = clone $user;
4145 // Keep a copy of user context, we need it for event.
4146 $usercontext = context_user::instance($user->id);
4148 // Delete all grades - backup is kept in grade_grades_history table.
4149 grade_user_delete($user->id);
4151 // TODO: remove from cohorts using standard API here.
4153 // Remove user tags.
4154 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4156 // Unconditionally unenrol from all courses.
4157 enrol_user_delete($user);
4159 // Unenrol from all roles in all contexts.
4160 // This might be slow but it is really needed - modules might do some extra cleanup!
4161 role_unassign_all(array('userid' => $user->id));
4163 // Notify the competency subsystem.
4164 \core_competency\api::hook_user_deleted($user->id);
4166 // Now do a brute force cleanup.
4168 // Delete all user events and subscription events.
4169 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
4171 // Now, delete all calendar subscription from the user.
4172 $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
4174 // Remove from all cohorts.
4175 $DB->delete_records('cohort_members', array('userid' => $user->id));
4177 // Remove from all groups.
4178 $DB->delete_records('groups_members', array('userid' => $user->id));
4180 // Brute force unenrol from all courses.
4181 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4183 // Purge user preferences.
4184 $DB->delete_records('user_preferences', array('userid' => $user->id));
4186 // Purge user extra profile info.
4187 $DB->delete_records('user_info_data', array('userid' => $user->id));
4189 // Purge log of previous password hashes.
4190 $DB->delete_records('user_password_history', array('userid' => $user->id));
4192 // Last course access not necessary either.
4193 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4194 // Remove all user tokens.
4195 $DB->delete_records('external_tokens', array('userid' => $user->id));
4197 // Unauthorise the user for all services.
4198 $DB->delete_records('external_services_users', array('userid' => $user->id));
4200 // Remove users private keys.
4201 $DB->delete_records('user_private_key', array('userid' => $user->id));
4203 // Remove users customised pages.
4204 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4206 // Remove user's oauth2 refresh tokens, if present.
4207 $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id));
4209 // Delete user from $SESSION->bulk_users.
4210 if (isset($SESSION->bulk_users[$user->id])) {
4211 unset($SESSION->bulk_users[$user->id]);
4214 // Force logout - may fail if file based sessions used, sorry.
4215 \core\session\manager::kill_user_sessions($user->id);
4217 // Generate username from email address, or a fake email.
4218 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4220 $deltime = time();
4221 $deltimelength = core_text::strlen((string) $deltime);
4223 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4224 $delname = clean_param($delemail, PARAM_USERNAME);
4225 $delname = core_text::substr($delname, 0, 100 - ($deltimelength + 1)) . ".{$deltime}";
4227 // Workaround for bulk deletes of users with the same email address.
4228 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4229 $delname++;
4232 // Mark internal user record as "deleted".
4233 $updateuser = new stdClass();
4234 $updateuser->id = $user->id;
4235 $updateuser->deleted = 1;
4236 $updateuser->username = $delname; // Remember it just in case.
4237 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4238 $updateuser->idnumber = ''; // Clear this field to free it up.
4239 $updateuser->picture = 0;
4240 $updateuser->timemodified = $deltime;
4242 // Don't trigger update event, as user is being deleted.
4243 user_update_user($updateuser, false, false);
4245 // Delete all content associated with the user context, but not the context itself.
4246 $usercontext->delete_content();
4248 // Delete any search data.
4249 \core_search\manager::context_deleted($usercontext);
4251 // Any plugin that needs to cleanup should register this event.
4252 // Trigger event.
4253 $event = \core\event\user_deleted::create(
4254 array(
4255 'objectid' => $user->id,
4256 'relateduserid' => $user->id,
4257 'context' => $usercontext,
4258 'other' => array(
4259 'username' => $user->username,
4260 'email' => $user->email,
4261 'idnumber' => $user->idnumber,
4262 'picture' => $user->picture,
4263 'mnethostid' => $user->mnethostid
4267 $event->add_record_snapshot('user', $olduser);
4268 $event->trigger();
4270 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4271 // should know about this updated property persisted to the user's table.
4272 $user->timemodified = $updateuser->timemodified;
4274 // Notify auth plugin - do not block the delete even when plugin fails.
4275 $authplugin = get_auth_plugin($user->auth);
4276 $authplugin->user_delete($user);
4278 return true;
4282 * Retrieve the guest user object.
4284 * @return stdClass A {@link $USER} object
4286 function guest_user() {
4287 global $CFG, $DB;
4289 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4290 $newuser->confirmed = 1;
4291 $newuser->lang = get_newuser_language();
4292 $newuser->lastip = getremoteaddr();
4295 return $newuser;
4299 * Authenticates a user against the chosen authentication mechanism
4301 * Given a username and password, this function looks them
4302 * up using the currently selected authentication mechanism,
4303 * and if the authentication is successful, it returns a
4304 * valid $user object from the 'user' table.
4306 * Uses auth_ functions from the currently active auth module
4308 * After authenticate_user_login() returns success, you will need to
4309 * log that the user has logged in, and call complete_user_login() to set
4310 * the session up.
4312 * Note: this function works only with non-mnet accounts!
4314 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4315 * @param string $password User's password
4316 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4317 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4318 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4319 * @return stdClass|false A {@link $USER} object or false if error
4321 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4322 global $CFG, $DB, $PAGE;
4323 require_once("$CFG->libdir/authlib.php");
4325 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4326 // we have found the user
4328 } else if (!empty($CFG->authloginviaemail)) {
4329 if ($email = clean_param($username, PARAM_EMAIL)) {
4330 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4331 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4332 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4333 if (count($users) === 1) {
4334 // Use email for login only if unique.
4335 $user = reset($users);
4336 $user = get_complete_user_data('id', $user->id);
4337 $username = $user->username;
4339 unset($users);
4343 // Make sure this request came from the login form.
4344 if (!\core\session\manager::validate_login_token($logintoken)) {
4345 $failurereason = AUTH_LOGIN_FAILED;
4347 // Trigger login failed event (specifying the ID of the found user, if available).
4348 \core\event\user_login_failed::create([
4349 'userid' => ($user->id ?? 0),
4350 'other' => [
4351 'username' => $username,
4352 'reason' => $failurereason,
4354 ])->trigger();
4356 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4357 return false;
4360 $authsenabled = get_enabled_auth_plugins();
4362 if ($user) {
4363 // Use manual if auth not set.
4364 $auth = empty($user->auth) ? 'manual' : $user->auth;
4366 if (in_array($user->auth, $authsenabled)) {
4367 $authplugin = get_auth_plugin($user->auth);
4368 $authplugin->pre_user_login_hook($user);
4371 if (!empty($user->suspended)) {
4372 $failurereason = AUTH_LOGIN_SUSPENDED;
4374 // Trigger login failed event.
4375 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4376 'other' => array('username' => $username, 'reason' => $failurereason)));
4377 $event->trigger();
4378 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4379 return false;
4381 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4382 // Legacy way to suspend user.
4383 $failurereason = AUTH_LOGIN_SUSPENDED;
4385 // Trigger login failed event.
4386 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4387 'other' => array('username' => $username, 'reason' => $failurereason)));
4388 $event->trigger();
4389 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4390 return false;
4392 $auths = array($auth);
4394 } else {
4395 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4396 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4397 $failurereason = AUTH_LOGIN_NOUSER;
4399 // Trigger login failed event.
4400 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4401 'reason' => $failurereason)));
4402 $event->trigger();
4403 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4404 return false;
4407 // User does not exist.
4408 $auths = $authsenabled;
4409 $user = new stdClass();
4410 $user->id = 0;
4413 if ($ignorelockout) {
4414 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4415 // or this function is called from a SSO script.
4416 } else if ($user->id) {
4417 // Verify login lockout after other ways that may prevent user login.
4418 if (login_is_lockedout($user)) {
4419 $failurereason = AUTH_LOGIN_LOCKOUT;
4421 // Trigger login failed event.
4422 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4423 'other' => array('username' => $username, 'reason' => $failurereason)));
4424 $event->trigger();
4426 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4427 return false;
4429 } else {
4430 // We can not lockout non-existing accounts.
4433 foreach ($auths as $auth) {
4434 $authplugin = get_auth_plugin($auth);
4436 // On auth fail fall through to the next plugin.
4437 if (!$authplugin->user_login($username, $password)) {
4438 continue;
4441 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4442 if (!empty($CFG->passwordpolicycheckonlogin)) {
4443 $errmsg = '';
4444 $passed = check_password_policy($password, $errmsg, $user);
4445 if (!$passed) {
4446 // First trigger event for failure.
4447 $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
4448 $failedevent->trigger();
4450 // If able to change password, set flag and move on.
4451 if ($authplugin->can_change_password()) {
4452 // Check if we are on internal change password page, or service is external, don't show notification.
4453 $internalchangeurl = new moodle_url('/login/change_password.php');
4454 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
4455 \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
4457 set_user_preference('auth_forcepasswordchange', 1, $user);
4458 } else if ($authplugin->can_reset_password()) {
4459 // Else force a reset if possible.
4460 \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
4461 redirect(new moodle_url('/login/forgot_password.php'));
4462 } else {
4463 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4464 // If support page is set, add link for help.
4465 if (!empty($CFG->supportpage)) {
4466 $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
4467 $link = \html_writer::tag('p', $link);
4468 $notifymsg .= $link;
4471 // If no change or reset is possible, add a notification for user.
4472 \core\notification::error($notifymsg);
4477 // Successful authentication.
4478 if ($user->id) {
4479 // User already exists in database.
4480 if (empty($user->auth)) {
4481 // For some reason auth isn't set yet.
4482 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4483 $user->auth = $auth;
4486 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4487 // the current hash algorithm while we have access to the user's password.
4488 update_internal_user_password($user, $password);
4490 if ($authplugin->is_synchronised_with_external()) {
4491 // Update user record from external DB.
4492 $user = update_user_record_by_id($user->id);
4494 } else {
4495 // The user is authenticated but user creation may be disabled.
4496 if (!empty($CFG->authpreventaccountcreation)) {
4497 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4499 // Trigger login failed event.
4500 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4501 'reason' => $failurereason)));
4502 $event->trigger();
4504 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4505 $_SERVER['HTTP_USER_AGENT']);
4506 return false;
4507 } else {
4508 $user = create_user_record($username, $password, $auth);
4512 $authplugin->sync_roles($user);
4514 foreach ($authsenabled as $hau) {
4515 $hauth = get_auth_plugin($hau);
4516 $hauth->user_authenticated_hook($user, $username, $password);
4519 if (empty($user->id)) {
4520 $failurereason = AUTH_LOGIN_NOUSER;
4521 // Trigger login failed event.
4522 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4523 'reason' => $failurereason)));
4524 $event->trigger();
4525 return false;
4528 if (!empty($user->suspended)) {
4529 // Just in case some auth plugin suspended account.
4530 $failurereason = AUTH_LOGIN_SUSPENDED;
4531 // Trigger login failed event.
4532 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4533 'other' => array('username' => $username, 'reason' => $failurereason)));
4534 $event->trigger();
4535 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4536 return false;
4539 login_attempt_valid($user);
4540 $failurereason = AUTH_LOGIN_OK;
4541 return $user;
4544 // Failed if all the plugins have failed.
4545 if (debugging('', DEBUG_ALL)) {
4546 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4549 if ($user->id) {
4550 login_attempt_failed($user);
4551 $failurereason = AUTH_LOGIN_FAILED;
4552 // Trigger login failed event.
4553 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4554 'other' => array('username' => $username, 'reason' => $failurereason)));
4555 $event->trigger();
4556 } else {
4557 $failurereason = AUTH_LOGIN_NOUSER;
4558 // Trigger login failed event.
4559 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4560 'reason' => $failurereason)));
4561 $event->trigger();
4564 return false;
4568 * Call to complete the user login process after authenticate_user_login()
4569 * has succeeded. It will setup the $USER variable and other required bits
4570 * and pieces.
4572 * NOTE:
4573 * - It will NOT log anything -- up to the caller to decide what to log.
4574 * - this function does not set any cookies any more!
4576 * @param stdClass $user
4577 * @param array $extrauserinfo
4578 * @return stdClass A {@link $USER} object - BC only, do not use
4580 function complete_user_login($user, array $extrauserinfo = []) {
4581 global $CFG, $DB, $USER, $SESSION;
4583 \core\session\manager::login_user($user);
4585 // Reload preferences from DB.
4586 unset($USER->preference);
4587 check_user_preferences_loaded($USER);
4589 // Update login times.
4590 update_user_login_times();
4592 // Extra session prefs init.
4593 set_login_session_preferences();
4595 // Trigger login event.
4596 $event = \core\event\user_loggedin::create(
4597 array(
4598 'userid' => $USER->id,
4599 'objectid' => $USER->id,
4600 'other' => [
4601 'username' => $USER->username,
4602 'extrauserinfo' => $extrauserinfo
4606 $event->trigger();
4608 // Check if the user is using a new browser or session (a new MoodleSession cookie is set in that case).
4609 // If the user is accessing from the same IP, ignore everything (most of the time will be a new session in the same browser).
4610 // Skip Web Service requests, CLI scripts, AJAX scripts, and request from the mobile app itself.
4611 $loginip = getremoteaddr();
4612 $isnewip = isset($SESSION->userpreviousip) && $SESSION->userpreviousip != $loginip;
4613 $isvalidenv = (!WS_SERVER && !CLI_SCRIPT && !NO_MOODLE_COOKIES) || PHPUNIT_TEST;
4615 if (!empty($SESSION->isnewsessioncookie) && $isnewip && $isvalidenv && !\core_useragent::is_moodle_app()) {
4617 $logintime = time();
4618 $ismoodleapp = false;
4619 $useragent = \core_useragent::get_user_agent_string();
4621 // Schedule adhoc task to sent a login notification to the user.
4622 $task = new \core\task\send_login_notifications();
4623 $task->set_userid($USER->id);
4624 $task->set_custom_data(compact('ismoodleapp', 'useragent', 'loginip', 'logintime'));
4625 $task->set_component('core');
4626 \core\task\manager::queue_adhoc_task($task);
4629 // Queue migrating the messaging data, if we need to.
4630 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4631 // Check if there are any legacy messages to migrate.
4632 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4633 \core_message\task\migrate_message_data::queue_task($USER->id);
4634 } else {
4635 set_user_preference('core_message_migrate_data', true, $USER->id);
4639 if (isguestuser()) {
4640 // No need to continue when user is THE guest.
4641 return $USER;
4644 if (CLI_SCRIPT) {
4645 // We can redirect to password change URL only in browser.
4646 return $USER;
4649 // Select password change url.
4650 $userauth = get_auth_plugin($USER->auth);
4652 // Check whether the user should be changing password.
4653 if (get_user_preferences('auth_forcepasswordchange', false)) {
4654 if ($userauth->can_change_password()) {
4655 if ($changeurl = $userauth->change_password_url()) {
4656 redirect($changeurl);
4657 } else {
4658 require_once($CFG->dirroot . '/login/lib.php');
4659 $SESSION->wantsurl = core_login_get_return_url();
4660 redirect($CFG->wwwroot.'/login/change_password.php');
4662 } else {
4663 throw new \moodle_exception('nopasswordchangeforced', 'auth');
4666 return $USER;
4670 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4672 * @param string $password String to check.
4673 * @return boolean True if the $password matches the format of an md5 sum.
4675 function password_is_legacy_hash($password) {
4676 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4680 * Compare password against hash stored in user object to determine if it is valid.
4682 * If necessary it also updates the stored hash to the current format.
4684 * @param stdClass $user (Password property may be updated).
4685 * @param string $password Plain text password.
4686 * @return bool True if password is valid.
4688 function validate_internal_user_password($user, $password) {
4689 global $CFG;
4691 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4692 // Internal password is not used at all, it can not validate.
4693 return false;
4696 // If hash isn't a legacy (md5) hash, validate using the library function.
4697 if (!password_is_legacy_hash($user->password)) {
4698 return password_verify($password, $user->password);
4701 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4702 // is valid we can then update it to the new algorithm.
4704 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4705 $validated = false;
4707 if ($user->password === md5($password.$sitesalt)
4708 or $user->password === md5($password)
4709 or $user->password === md5(addslashes($password).$sitesalt)
4710 or $user->password === md5(addslashes($password))) {
4711 // Note: we are intentionally using the addslashes() here because we
4712 // need to accept old password hashes of passwords with magic quotes.
4713 $validated = true;
4715 } else {
4716 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4717 $alt = 'passwordsaltalt'.$i;
4718 if (!empty($CFG->$alt)) {
4719 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4720 $validated = true;
4721 break;
4727 if ($validated) {
4728 // If the password matches the existing md5 hash, update to the
4729 // current hash algorithm while we have access to the user's password.
4730 update_internal_user_password($user, $password);
4733 return $validated;
4737 * Calculate hash for a plain text password.
4739 * @param string $password Plain text password to be hashed.
4740 * @param bool $fasthash If true, use a low cost factor when generating the hash
4741 * This is much faster to generate but makes the hash
4742 * less secure. It is used when lots of hashes need to
4743 * be generated quickly.
4744 * @return string The hashed password.
4746 * @throws moodle_exception If a problem occurs while generating the hash.
4748 function hash_internal_user_password($password, $fasthash = false) {
4749 global $CFG;
4751 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4752 $options = ($fasthash) ? array('cost' => 4) : array();
4754 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4756 if ($generatedhash === false || $generatedhash === null) {
4757 throw new moodle_exception('Failed to generate password hash.');
4760 return $generatedhash;
4764 * Update password hash in user object (if necessary).
4766 * The password is updated if:
4767 * 1. The password has changed (the hash of $user->password is different
4768 * to the hash of $password).
4769 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4770 * md5 algorithm).
4772 * Updating the password will modify the $user object and the database
4773 * record to use the current hashing algorithm.
4774 * It will remove Web Services user tokens too.
4776 * @param stdClass $user User object (password property may be updated).
4777 * @param string $password Plain text password.
4778 * @param bool $fasthash If true, use a low cost factor when generating the hash
4779 * This is much faster to generate but makes the hash
4780 * less secure. It is used when lots of hashes need to
4781 * be generated quickly.
4782 * @return bool Always returns true.
4784 function update_internal_user_password($user, $password, $fasthash = false) {
4785 global $CFG, $DB;
4787 // Figure out what the hashed password should be.
4788 if (!isset($user->auth)) {
4789 debugging('User record in update_internal_user_password() must include field auth',
4790 DEBUG_DEVELOPER);
4791 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4793 $authplugin = get_auth_plugin($user->auth);
4794 if ($authplugin->prevent_local_passwords()) {
4795 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4796 } else {
4797 $hashedpassword = hash_internal_user_password($password, $fasthash);
4800 $algorithmchanged = false;
4802 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4803 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4804 $passwordchanged = ($user->password !== $hashedpassword);
4806 } else if (isset($user->password)) {
4807 // If verification fails then it means the password has changed.
4808 $passwordchanged = !password_verify($password, $user->password);
4809 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4810 } else {
4811 // While creating new user, password in unset in $user object, to avoid
4812 // saving it with user_create()
4813 $passwordchanged = true;
4816 if ($passwordchanged || $algorithmchanged) {
4817 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4818 $user->password = $hashedpassword;
4820 // Trigger event.
4821 $user = $DB->get_record('user', array('id' => $user->id));
4822 \core\event\user_password_updated::create_from_user($user)->trigger();
4824 // Remove WS user tokens.
4825 if (!empty($CFG->passwordchangetokendeletion)) {
4826 require_once($CFG->dirroot.'/webservice/lib.php');
4827 webservice::delete_user_ws_tokens($user->id);
4831 return true;
4835 * Get a complete user record, which includes all the info in the user record.
4837 * Intended for setting as $USER session variable
4839 * @param string $field The user field to be checked for a given value.
4840 * @param string $value The value to match for $field.
4841 * @param int $mnethostid
4842 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4843 * found. Otherwise, it will just return false.
4844 * @return mixed False, or A {@link $USER} object.
4846 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4847 global $CFG, $DB;
4849 if (!$field || !$value) {
4850 return false;
4853 // Change the field to lowercase.
4854 $field = core_text::strtolower($field);
4856 // List of case insensitive fields.
4857 $caseinsensitivefields = ['email'];
4859 // Username input is forced to lowercase and should be case sensitive.
4860 if ($field == 'username') {
4861 $value = core_text::strtolower($value);
4864 // Build the WHERE clause for an SQL query.
4865 $params = array('fieldval' => $value);
4867 // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4868 // such as MySQL by pre-filtering users with accent-insensitive subselect.
4869 if (in_array($field, $caseinsensitivefields)) {
4870 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4871 $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4872 $params['fieldval2'] = $value;
4873 } else {
4874 $fieldselect = "$field = :fieldval";
4875 $idsubselect = '';
4877 $constraints = "$fieldselect AND deleted <> 1";
4879 // If we are loading user data based on anything other than id,
4880 // we must also restrict our search based on mnet host.
4881 if ($field != 'id') {
4882 if (empty($mnethostid)) {
4883 // If empty, we restrict to local users.
4884 $mnethostid = $CFG->mnet_localhost_id;
4887 if (!empty($mnethostid)) {
4888 $params['mnethostid'] = $mnethostid;
4889 $constraints .= " AND mnethostid = :mnethostid";
4892 if ($idsubselect) {
4893 $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4896 // Get all the basic user data.
4897 try {
4898 // Make sure that there's only a single record that matches our query.
4899 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4900 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4901 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4902 } catch (dml_exception $exception) {
4903 if ($throwexception) {
4904 throw $exception;
4905 } else {
4906 // Return false when no records or multiple records were found.
4907 return false;
4911 // Get various settings and preferences.
4913 // Preload preference cache.
4914 check_user_preferences_loaded($user);
4916 // Load course enrolment related stuff.
4917 $user->lastcourseaccess = array(); // During last session.
4918 $user->currentcourseaccess = array(); // During current session.
4919 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4920 foreach ($lastaccesses as $lastaccess) {
4921 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4925 // Add cohort theme.
4926 if (!empty($CFG->allowcohortthemes)) {
4927 require_once($CFG->dirroot . '/cohort/lib.php');
4928 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4929 $user->cohorttheme = $cohorttheme;
4933 // Add the custom profile fields to the user record.
4934 $user->profile = array();
4935 if (!isguestuser($user)) {
4936 require_once($CFG->dirroot.'/user/profile/lib.php');
4937 profile_load_custom_fields($user);
4940 // Rewrite some variables if necessary.
4941 if (!empty($user->description)) {
4942 // No need to cart all of it around.
4943 $user->description = true;
4945 if (isguestuser($user)) {
4946 // Guest language always same as site.
4947 $user->lang = get_newuser_language();
4948 // Name always in current language.
4949 $user->firstname = get_string('guestuser');
4950 $user->lastname = ' ';
4953 return $user;
4957 * Validate a password against the configured password policy
4959 * @param string $password the password to be checked against the password policy
4960 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4961 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
4963 * @return bool true if the password is valid according to the policy. false otherwise.
4965 function check_password_policy($password, &$errmsg, $user = null) {
4966 global $CFG;
4968 if (!empty($CFG->passwordpolicy)) {
4969 $errmsg = '';
4970 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4971 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4973 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4974 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4976 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4977 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4979 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4980 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4982 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4983 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4985 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4986 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4989 // Fire any additional password policy functions from plugins.
4990 // Plugin functions should output an error message string or empty string for success.
4991 $pluginsfunction = get_plugins_with_function('check_password_policy');
4992 foreach ($pluginsfunction as $plugintype => $plugins) {
4993 foreach ($plugins as $pluginfunction) {
4994 $pluginerr = $pluginfunction($password, $user);
4995 if ($pluginerr) {
4996 $errmsg .= '<div>'. $pluginerr .'</div>';
5002 if ($errmsg == '') {
5003 return true;
5004 } else {
5005 return false;
5011 * When logging in, this function is run to set certain preferences for the current SESSION.
5013 function set_login_session_preferences() {
5014 global $SESSION;
5016 $SESSION->justloggedin = true;
5018 unset($SESSION->lang);
5019 unset($SESSION->forcelang);
5020 unset($SESSION->load_navigation_admin);
5025 * Delete a course, including all related data from the database, and any associated files.
5027 * @param mixed $courseorid The id of the course or course object to delete.
5028 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5029 * @return bool true if all the removals succeeded. false if there were any failures. If this
5030 * method returns false, some of the removals will probably have succeeded, and others
5031 * failed, but you have no way of knowing which.
5033 function delete_course($courseorid, $showfeedback = true) {
5034 global $DB;
5036 if (is_object($courseorid)) {
5037 $courseid = $courseorid->id;
5038 $course = $courseorid;
5039 } else {
5040 $courseid = $courseorid;
5041 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5042 return false;
5045 $context = context_course::instance($courseid);
5047 // Frontpage course can not be deleted!!
5048 if ($courseid == SITEID) {
5049 return false;
5052 // Allow plugins to use this course before we completely delete it.
5053 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5054 foreach ($pluginsfunction as $plugintype => $plugins) {
5055 foreach ($plugins as $pluginfunction) {
5056 $pluginfunction($course);
5061 // Tell the search manager we are about to delete a course. This prevents us sending updates
5062 // for each individual context being deleted.
5063 \core_search\manager::course_deleting_start($courseid);
5065 $handler = core_course\customfield\course_handler::create();
5066 $handler->delete_instance($courseid);
5068 // Make the course completely empty.
5069 remove_course_contents($courseid, $showfeedback);
5071 // Delete the course and related context instance.
5072 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5074 $DB->delete_records("course", array("id" => $courseid));
5075 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5077 // Reset all course related caches here.
5078 core_courseformat\base::reset_course_cache($courseid);
5080 // Tell search that we have deleted the course so it can delete course data from the index.
5081 \core_search\manager::course_deleting_finish($courseid);
5083 // Trigger a course deleted event.
5084 $event = \core\event\course_deleted::create(array(
5085 'objectid' => $course->id,
5086 'context' => $context,
5087 'other' => array(
5088 'shortname' => $course->shortname,
5089 'fullname' => $course->fullname,
5090 'idnumber' => $course->idnumber
5093 $event->add_record_snapshot('course', $course);
5094 $event->trigger();
5096 return true;
5100 * Clear a course out completely, deleting all content but don't delete the course itself.
5102 * This function does not verify any permissions.
5104 * Please note this function also deletes all user enrolments,
5105 * enrolment instances and role assignments by default.
5107 * $options:
5108 * - 'keep_roles_and_enrolments' - false by default
5109 * - 'keep_groups_and_groupings' - false by default
5111 * @param int $courseid The id of the course that is being deleted
5112 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5113 * @param array $options extra options
5114 * @return bool true if all the removals succeeded. false if there were any failures. If this
5115 * method returns false, some of the removals will probably have succeeded, and others
5116 * failed, but you have no way of knowing which.
5118 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5119 global $CFG, $DB, $OUTPUT;
5121 require_once($CFG->libdir.'/badgeslib.php');
5122 require_once($CFG->libdir.'/completionlib.php');
5123 require_once($CFG->libdir.'/questionlib.php');
5124 require_once($CFG->libdir.'/gradelib.php');
5125 require_once($CFG->dirroot.'/group/lib.php');
5126 require_once($CFG->dirroot.'/comment/lib.php');
5127 require_once($CFG->dirroot.'/rating/lib.php');
5128 require_once($CFG->dirroot.'/notes/lib.php');
5130 // Handle course badges.
5131 badges_handle_course_deletion($courseid);
5133 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5134 $strdeleted = get_string('deleted').' - ';
5136 // Some crazy wishlist of stuff we should skip during purging of course content.
5137 $options = (array)$options;
5139 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5140 $coursecontext = context_course::instance($courseid);
5141 $fs = get_file_storage();
5143 // Delete course completion information, this has to be done before grades and enrols.
5144 $cc = new completion_info($course);
5145 $cc->clear_criteria();
5146 if ($showfeedback) {
5147 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5150 // Remove all data from gradebook - this needs to be done before course modules
5151 // because while deleting this information, the system may need to reference
5152 // the course modules that own the grades.
5153 remove_course_grades($courseid, $showfeedback);
5154 remove_grade_letters($coursecontext, $showfeedback);
5156 // Delete course blocks in any all child contexts,
5157 // they may depend on modules so delete them first.
5158 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5159 foreach ($childcontexts as $childcontext) {
5160 blocks_delete_all_for_context($childcontext->id);
5162 unset($childcontexts);
5163 blocks_delete_all_for_context($coursecontext->id);
5164 if ($showfeedback) {
5165 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5168 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
5169 rebuild_course_cache($courseid, true);
5171 // Get the list of all modules that are properly installed.
5172 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5174 // Delete every instance of every module,
5175 // this has to be done before deleting of course level stuff.
5176 $locations = core_component::get_plugin_list('mod');
5177 foreach ($locations as $modname => $moddir) {
5178 if ($modname === 'NEWMODULE') {
5179 continue;
5181 if (array_key_exists($modname, $allmodules)) {
5182 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5183 FROM {".$modname."} m
5184 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5185 WHERE m.course = :courseid";
5186 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5187 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5189 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5190 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5192 if ($instances) {
5193 foreach ($instances as $cm) {
5194 if ($cm->id) {
5195 // Delete activity context questions and question categories.
5196 question_delete_activity($cm);
5197 // Notify the competency subsystem.
5198 \core_competency\api::hook_course_module_deleted($cm);
5200 // Delete all tag instances associated with the instance of this module.
5201 core_tag_tag::delete_instances("mod_{$modname}", null, context_module::instance($cm->id)->id);
5202 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
5204 if (function_exists($moddelete)) {
5205 // This purges all module data in related tables, extra user prefs, settings, etc.
5206 $moddelete($cm->modinstance);
5207 } else {
5208 // NOTE: we should not allow installation of modules with missing delete support!
5209 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5210 $DB->delete_records($modname, array('id' => $cm->modinstance));
5213 if ($cm->id) {
5214 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5215 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5216 $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id]);
5217 $DB->delete_records('course_modules_viewed', ['coursemoduleid' => $cm->id]);
5218 $DB->delete_records('course_modules', array('id' => $cm->id));
5219 rebuild_course_cache($cm->course, true);
5223 if ($instances and $showfeedback) {
5224 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5226 } else {
5227 // Ooops, this module is not properly installed, force-delete it in the next block.
5231 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5233 // Delete completion defaults.
5234 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5236 // Remove all data from availability and completion tables that is associated
5237 // with course-modules belonging to this course. Note this is done even if the
5238 // features are not enabled now, in case they were enabled previously.
5239 $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
5240 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5241 $DB->delete_records_subquery('course_modules_viewed', 'coursemoduleid', 'id',
5242 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5244 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5245 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5246 $allmodulesbyid = array_flip($allmodules);
5247 foreach ($cms as $cm) {
5248 if (array_key_exists($cm->module, $allmodulesbyid)) {
5249 try {
5250 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5251 } catch (Exception $e) {
5252 // Ignore weird or missing table problems.
5255 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5256 $DB->delete_records('course_modules', array('id' => $cm->id));
5257 rebuild_course_cache($cm->course, true);
5260 if ($showfeedback) {
5261 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5264 // Delete questions and question categories.
5265 question_delete_course($course);
5266 if ($showfeedback) {
5267 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5270 // Delete content bank contents.
5271 $cb = new \core_contentbank\contentbank();
5272 $cbdeleted = $cb->delete_contents($coursecontext);
5273 if ($showfeedback && $cbdeleted) {
5274 echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5277 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5278 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5279 foreach ($childcontexts as $childcontext) {
5280 $childcontext->delete();
5282 unset($childcontexts);
5284 // Remove roles and enrolments by default.
5285 if (empty($options['keep_roles_and_enrolments'])) {
5286 // This hack is used in restore when deleting contents of existing course.
5287 // During restore, we should remove only enrolment related data that the user performing the restore has a
5288 // permission to remove.
5289 $userid = $options['userid'] ?? null;
5290 enrol_course_delete($course, $userid);
5291 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5292 if ($showfeedback) {
5293 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5297 // Delete any groups, removing members and grouping/course links first.
5298 if (empty($options['keep_groups_and_groupings'])) {
5299 groups_delete_groupings($course->id, $showfeedback);
5300 groups_delete_groups($course->id, $showfeedback);
5303 // Filters be gone!
5304 filter_delete_all_for_context($coursecontext->id);
5306 // Notes, you shall not pass!
5307 note_delete_all($course->id);
5309 // Die comments!
5310 comment::delete_comments($coursecontext->id);
5312 // Ratings are history too.
5313 $delopt = new stdclass();
5314 $delopt->contextid = $coursecontext->id;
5315 $rm = new rating_manager();
5316 $rm->delete_ratings($delopt);
5318 // Delete course tags.
5319 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5321 // Give the course format the opportunity to remove its obscure data.
5322 $format = course_get_format($course);
5323 $format->delete_format_data();
5325 // Notify the competency subsystem.
5326 \core_competency\api::hook_course_deleted($course);
5328 // Delete calendar events.
5329 $DB->delete_records('event', array('courseid' => $course->id));
5330 $fs->delete_area_files($coursecontext->id, 'calendar');
5332 // Delete all related records in other core tables that may have a courseid
5333 // This array stores the tables that need to be cleared, as
5334 // table_name => column_name that contains the course id.
5335 $tablestoclear = array(
5336 'backup_courses' => 'courseid', // Scheduled backup stuff.
5337 'user_lastaccess' => 'courseid', // User access info.
5339 foreach ($tablestoclear as $table => $col) {
5340 $DB->delete_records($table, array($col => $course->id));
5343 // Delete all course backup files.
5344 $fs->delete_area_files($coursecontext->id, 'backup');
5346 // Cleanup course record - remove links to deleted stuff.
5347 $oldcourse = new stdClass();
5348 $oldcourse->id = $course->id;
5349 $oldcourse->summary = '';
5350 $oldcourse->cacherev = 0;
5351 $oldcourse->legacyfiles = 0;
5352 if (!empty($options['keep_groups_and_groupings'])) {
5353 $oldcourse->defaultgroupingid = 0;
5355 $DB->update_record('course', $oldcourse);
5357 // Delete course sections.
5358 $DB->delete_records('course_sections', array('course' => $course->id));
5360 // Delete legacy, section and any other course files.
5361 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5363 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5364 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5365 // Easy, do not delete the context itself...
5366 $coursecontext->delete_content();
5367 } else {
5368 // Hack alert!!!!
5369 // We can not drop all context stuff because it would bork enrolments and roles,
5370 // there might be also files used by enrol plugins...
5373 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5374 // also some non-standard unsupported plugins may try to store something there.
5375 fulldelete($CFG->dataroot.'/'.$course->id);
5377 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5378 course_modinfo::purge_course_cache($courseid);
5380 // Trigger a course content deleted event.
5381 $event = \core\event\course_content_deleted::create(array(
5382 'objectid' => $course->id,
5383 'context' => $coursecontext,
5384 'other' => array('shortname' => $course->shortname,
5385 'fullname' => $course->fullname,
5386 'options' => $options) // Passing this for legacy reasons.
5388 $event->add_record_snapshot('course', $course);
5389 $event->trigger();
5391 return true;
5395 * Change dates in module - used from course reset.
5397 * @param string $modname forum, assignment, etc
5398 * @param array $fields array of date fields from mod table
5399 * @param int $timeshift time difference
5400 * @param int $courseid
5401 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5402 * @return bool success
5404 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5405 global $CFG, $DB;
5406 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5408 $return = true;
5409 $params = array($timeshift, $courseid);
5410 foreach ($fields as $field) {
5411 $updatesql = "UPDATE {".$modname."}
5412 SET $field = $field + ?
5413 WHERE course=? AND $field<>0";
5414 if ($modid) {
5415 $updatesql .= ' AND id=?';
5416 $params[] = $modid;
5418 $return = $DB->execute($updatesql, $params) && $return;
5421 return $return;
5425 * This function will empty a course of user data.
5426 * It will retain the activities and the structure of the course.
5428 * @param object $data an object containing all the settings including courseid (without magic quotes)
5429 * @return array status array of array component, item, error
5431 function reset_course_userdata($data) {
5432 global $CFG, $DB;
5433 require_once($CFG->libdir.'/gradelib.php');
5434 require_once($CFG->libdir.'/completionlib.php');
5435 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5436 require_once($CFG->dirroot.'/group/lib.php');
5438 $data->courseid = $data->id;
5439 $context = context_course::instance($data->courseid);
5441 $eventparams = array(
5442 'context' => $context,
5443 'courseid' => $data->id,
5444 'other' => array(
5445 'reset_options' => (array) $data
5448 $event = \core\event\course_reset_started::create($eventparams);
5449 $event->trigger();
5451 // Calculate the time shift of dates.
5452 if (!empty($data->reset_start_date)) {
5453 // Time part of course startdate should be zero.
5454 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5455 } else {
5456 $data->timeshift = 0;
5459 // Result array: component, item, error.
5460 $status = array();
5462 // Start the resetting.
5463 $componentstr = get_string('general');
5465 // Move the course start time.
5466 if (!empty($data->reset_start_date) and $data->timeshift) {
5467 // Change course start data.
5468 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5469 // Update all course and group events - do not move activity events.
5470 $updatesql = "UPDATE {event}
5471 SET timestart = timestart + ?
5472 WHERE courseid=? AND instance=0";
5473 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5475 // Update any date activity restrictions.
5476 if ($CFG->enableavailability) {
5477 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5480 // Update completion expected dates.
5481 if ($CFG->enablecompletion) {
5482 $modinfo = get_fast_modinfo($data->courseid);
5483 $changed = false;
5484 foreach ($modinfo->get_cms() as $cm) {
5485 if ($cm->completion && !empty($cm->completionexpected)) {
5486 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5487 array('id' => $cm->id));
5488 $changed = true;
5492 // Clear course cache if changes made.
5493 if ($changed) {
5494 rebuild_course_cache($data->courseid, true);
5497 // Update course date completion criteria.
5498 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5501 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5504 if (!empty($data->reset_end_date)) {
5505 // If the user set a end date value respect it.
5506 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5507 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5508 // If there is a time shift apply it to the end date as well.
5509 $enddate = $data->reset_end_date_old + $data->timeshift;
5510 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5513 if (!empty($data->reset_events)) {
5514 $DB->delete_records('event', array('courseid' => $data->courseid));
5515 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5518 if (!empty($data->reset_notes)) {
5519 require_once($CFG->dirroot.'/notes/lib.php');
5520 note_delete_all($data->courseid);
5521 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5524 if (!empty($data->delete_blog_associations)) {
5525 require_once($CFG->dirroot.'/blog/lib.php');
5526 blog_remove_associations_for_course($data->courseid);
5527 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5530 if (!empty($data->reset_completion)) {
5531 // Delete course and activity completion information.
5532 $course = $DB->get_record('course', array('id' => $data->courseid));
5533 $cc = new completion_info($course);
5534 $cc->delete_all_completion_data();
5535 $status[] = array('component' => $componentstr,
5536 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5539 if (!empty($data->reset_competency_ratings)) {
5540 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5541 $status[] = array('component' => $componentstr,
5542 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5545 $componentstr = get_string('roles');
5547 if (!empty($data->reset_roles_overrides)) {
5548 $children = $context->get_child_contexts();
5549 foreach ($children as $child) {
5550 $child->delete_capabilities();
5552 $context->delete_capabilities();
5553 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5556 if (!empty($data->reset_roles_local)) {
5557 $children = $context->get_child_contexts();
5558 foreach ($children as $child) {
5559 role_unassign_all(array('contextid' => $child->id));
5561 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5564 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5565 $data->unenrolled = array();
5566 if (!empty($data->unenrol_users)) {
5567 $plugins = enrol_get_plugins(true);
5568 $instances = enrol_get_instances($data->courseid, true);
5569 foreach ($instances as $key => $instance) {
5570 if (!isset($plugins[$instance->enrol])) {
5571 unset($instances[$key]);
5572 continue;
5576 $usersroles = enrol_get_course_users_roles($data->courseid);
5577 foreach ($data->unenrol_users as $withroleid) {
5578 if ($withroleid) {
5579 $sql = "SELECT ue.*
5580 FROM {user_enrolments} ue
5581 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5582 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5583 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5584 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5586 } else {
5587 // Without any role assigned at course context.
5588 $sql = "SELECT ue.*
5589 FROM {user_enrolments} ue
5590 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5591 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5592 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5593 WHERE ra.id IS null";
5594 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5597 $rs = $DB->get_recordset_sql($sql, $params);
5598 foreach ($rs as $ue) {
5599 if (!isset($instances[$ue->enrolid])) {
5600 continue;
5602 $instance = $instances[$ue->enrolid];
5603 $plugin = $plugins[$instance->enrol];
5604 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5605 continue;
5608 if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5609 // If we don't remove all roles and user has more than one role, just remove this role.
5610 role_unassign($withroleid, $ue->userid, $context->id);
5612 unset($usersroles[$ue->userid][$withroleid]);
5613 } else {
5614 // If we remove all roles or user has only one role, unenrol user from course.
5615 $plugin->unenrol_user($instance, $ue->userid);
5617 $data->unenrolled[$ue->userid] = $ue->userid;
5619 $rs->close();
5622 if (!empty($data->unenrolled)) {
5623 $status[] = array(
5624 'component' => $componentstr,
5625 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5626 'error' => false
5630 $componentstr = get_string('groups');
5632 // Remove all group members.
5633 if (!empty($data->reset_groups_members)) {
5634 groups_delete_group_members($data->courseid);
5635 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5638 // Remove all groups.
5639 if (!empty($data->reset_groups_remove)) {
5640 groups_delete_groups($data->courseid, false);
5641 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5644 // Remove all grouping members.
5645 if (!empty($data->reset_groupings_members)) {
5646 groups_delete_groupings_groups($data->courseid, false);
5647 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5650 // Remove all groupings.
5651 if (!empty($data->reset_groupings_remove)) {
5652 groups_delete_groupings($data->courseid, false);
5653 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5656 // Look in every instance of every module for data to delete.
5657 $unsupportedmods = array();
5658 if ($allmods = $DB->get_records('modules') ) {
5659 foreach ($allmods as $mod) {
5660 $modname = $mod->name;
5661 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5662 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5663 if (file_exists($modfile)) {
5664 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5665 continue; // Skip mods with no instances.
5667 include_once($modfile);
5668 if (function_exists($moddeleteuserdata)) {
5669 $modstatus = $moddeleteuserdata($data);
5670 if (is_array($modstatus)) {
5671 $status = array_merge($status, $modstatus);
5672 } else {
5673 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5675 } else {
5676 $unsupportedmods[] = $mod;
5678 } else {
5679 debugging('Missing lib.php in '.$modname.' module!');
5681 // Update calendar events for all modules.
5682 course_module_bulk_update_calendar_events($modname, $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 $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 string|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 * @return array with [plugintype][plugin] = functionname
7833 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7834 global $CFG;
7836 if (during_initial_install() || isset($CFG->upgraderunning)) {
7837 // API functions _must not_ be called during an installation or upgrade.
7838 return [];
7841 $cache = \cache::make('core', 'plugin_functions');
7843 // Including both although I doubt that we will find two functions definitions with the same name.
7844 // Clean the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7845 $pluginfunctions = false;
7846 if (!empty($CFG->allversionshash)) {
7847 $key = $CFG->allversionshash . '_' . $function . '_' . clean_param($file, PARAM_ALPHA);
7848 $pluginfunctions = $cache->get($key);
7850 $dirty = false;
7852 // Use the plugin manager to check that plugins are currently installed.
7853 $pluginmanager = \core_plugin_manager::instance();
7855 if ($pluginfunctions !== false) {
7857 // Checking that the files are still available.
7858 foreach ($pluginfunctions as $plugintype => $plugins) {
7860 $allplugins = \core_component::get_plugin_list($plugintype);
7861 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7862 foreach ($plugins as $plugin => $function) {
7863 if (!isset($installedplugins[$plugin])) {
7864 // Plugin code is still present on disk but it is not installed.
7865 $dirty = true;
7866 break 2;
7869 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7870 if (empty($allplugins[$plugin])) {
7871 $dirty = true;
7872 break 2;
7875 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7876 if ($include && $fileexists) {
7877 // Include the files if it was requested.
7878 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7879 } else if (!$fileexists) {
7880 // If the file is not available any more it should not be returned.
7881 $dirty = true;
7882 break 2;
7885 // Check if the function still exists in the file.
7886 if ($include && !function_exists($function)) {
7887 $dirty = true;
7888 break 2;
7893 // If the cache is dirty, we should fall through and let it rebuild.
7894 if (!$dirty) {
7895 return $pluginfunctions;
7899 $pluginfunctions = array();
7901 // To fill the cached. Also, everything should continue working with cache disabled.
7902 $plugintypes = \core_component::get_plugin_types();
7903 foreach ($plugintypes as $plugintype => $unused) {
7905 // We need to include files here.
7906 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7907 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7908 foreach ($pluginswithfile as $plugin => $notused) {
7910 if (!isset($installedplugins[$plugin])) {
7911 continue;
7914 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7916 $pluginfunction = false;
7917 if (function_exists($fullfunction)) {
7918 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7919 $pluginfunction = $fullfunction;
7921 } else if ($plugintype === 'mod') {
7922 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7923 $shortfunction = $plugin . '_' . $function;
7924 if (function_exists($shortfunction)) {
7925 $pluginfunction = $shortfunction;
7929 if ($pluginfunction) {
7930 if (empty($pluginfunctions[$plugintype])) {
7931 $pluginfunctions[$plugintype] = array();
7933 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7938 if (!empty($CFG->allversionshash)) {
7939 $cache->set($key, $pluginfunctions);
7942 return $pluginfunctions;
7947 * Lists plugin-like directories within specified directory
7949 * This function was originally used for standard Moodle plugins, please use
7950 * new core_component::get_plugin_list() now.
7952 * This function is used for general directory listing and backwards compatility.
7954 * @param string $directory relative directory from root
7955 * @param string $exclude dir name to exclude from the list (defaults to none)
7956 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7957 * @return array Sorted array of directory names found under the requested parameters
7959 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7960 global $CFG;
7962 $plugins = array();
7964 if (empty($basedir)) {
7965 $basedir = $CFG->dirroot .'/'. $directory;
7967 } else {
7968 $basedir = $basedir .'/'. $directory;
7971 if ($CFG->debugdeveloper and empty($exclude)) {
7972 // Make sure devs do not use this to list normal plugins,
7973 // this is intended for general directories that are not plugins!
7975 $subtypes = core_component::get_plugin_types();
7976 if (in_array($basedir, $subtypes)) {
7977 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7979 unset($subtypes);
7982 $ignorelist = array_flip(array_filter([
7983 'CVS',
7984 '_vti_cnf',
7985 'amd',
7986 'classes',
7987 'simpletest',
7988 'tests',
7989 'templates',
7990 'yui',
7991 $exclude,
7992 ]));
7994 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7995 if (!$dirhandle = opendir($basedir)) {
7996 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7997 return array();
7999 while (false !== ($dir = readdir($dirhandle))) {
8000 if (strpos($dir, '.') === 0) {
8001 // Ignore directories starting with .
8002 // These are treated as hidden directories.
8003 continue;
8005 if (array_key_exists($dir, $ignorelist)) {
8006 // This directory features on the ignore list.
8007 continue;
8009 if (filetype($basedir .'/'. $dir) != 'dir') {
8010 continue;
8012 $plugins[] = $dir;
8014 closedir($dirhandle);
8016 if ($plugins) {
8017 asort($plugins);
8019 return $plugins;
8023 * Invoke plugin's callback functions
8025 * @param string $type plugin type e.g. 'mod'
8026 * @param string $name plugin name
8027 * @param string $feature feature name
8028 * @param string $action feature's action
8029 * @param array $params parameters of callback function, should be an array
8030 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
8031 * @return mixed
8033 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
8035 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
8036 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
8040 * Invoke component's callback functions
8042 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8043 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8044 * @param array $params parameters of callback function
8045 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
8046 * @return mixed
8048 function component_callback($component, $function, array $params = array(), $default = null) {
8050 $functionname = component_callback_exists($component, $function);
8052 if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
8053 // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
8054 // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
8055 // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
8056 // This check can be removed when minimum PHP version for Moodle is raised to 8.
8057 debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
8058 DEBUG_DEVELOPER);
8059 $params = array_values($params);
8062 if ($functionname) {
8063 // Function exists, so just return function result.
8064 $ret = call_user_func_array($functionname, $params);
8065 if (is_null($ret)) {
8066 return $default;
8067 } else {
8068 return $ret;
8071 return $default;
8075 * Determine if a component callback exists and return the function name to call. Note that this
8076 * function will include the required library files so that the functioname returned can be
8077 * called directly.
8079 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8080 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8081 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
8082 * @throws coding_exception if invalid component specfied
8084 function component_callback_exists($component, $function) {
8085 global $CFG; // This is needed for the inclusions.
8087 $cleancomponent = clean_param($component, PARAM_COMPONENT);
8088 if (empty($cleancomponent)) {
8089 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8091 $component = $cleancomponent;
8093 list($type, $name) = core_component::normalize_component($component);
8094 $component = $type . '_' . $name;
8096 $oldfunction = $name.'_'.$function;
8097 $function = $component.'_'.$function;
8099 $dir = core_component::get_component_directory($component);
8100 if (empty($dir)) {
8101 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8104 // Load library and look for function.
8105 if (file_exists($dir.'/lib.php')) {
8106 require_once($dir.'/lib.php');
8109 if (!function_exists($function) and function_exists($oldfunction)) {
8110 if ($type !== 'mod' and $type !== 'core') {
8111 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
8113 $function = $oldfunction;
8116 if (function_exists($function)) {
8117 return $function;
8119 return false;
8123 * Call the specified callback method on the provided class.
8125 * If the callback returns null, then the default value is returned instead.
8126 * If the class does not exist, then the default value is returned.
8128 * @param string $classname The name of the class to call upon.
8129 * @param string $methodname The name of the staticically defined method on the class.
8130 * @param array $params The arguments to pass into the method.
8131 * @param mixed $default The default value.
8132 * @return mixed The return value.
8134 function component_class_callback($classname, $methodname, array $params, $default = null) {
8135 if (!class_exists($classname)) {
8136 return $default;
8139 if (!method_exists($classname, $methodname)) {
8140 return $default;
8143 $fullfunction = $classname . '::' . $methodname;
8144 $result = call_user_func_array($fullfunction, $params);
8146 if (null === $result) {
8147 return $default;
8148 } else {
8149 return $result;
8154 * Checks whether a plugin supports a specified feature.
8156 * @param string $type Plugin type e.g. 'mod'
8157 * @param string $name Plugin name e.g. 'forum'
8158 * @param string $feature Feature code (FEATURE_xx constant)
8159 * @param mixed $default default value if feature support unknown
8160 * @return mixed Feature result (false if not supported, null if feature is unknown,
8161 * otherwise usually true but may have other feature-specific value such as array)
8162 * @throws coding_exception
8164 function plugin_supports($type, $name, $feature, $default = null) {
8165 global $CFG;
8167 if ($type === 'mod' and $name === 'NEWMODULE') {
8168 // Somebody forgot to rename the module template.
8169 return false;
8172 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8173 if (empty($component)) {
8174 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8177 $function = null;
8179 if ($type === 'mod') {
8180 // We need this special case because we support subplugins in modules,
8181 // otherwise it would end up in infinite loop.
8182 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8183 include_once("$CFG->dirroot/mod/$name/lib.php");
8184 $function = $component.'_supports';
8185 if (!function_exists($function)) {
8186 // Legacy non-frankenstyle function name.
8187 $function = $name.'_supports';
8191 } else {
8192 if (!$path = core_component::get_plugin_directory($type, $name)) {
8193 // Non existent plugin type.
8194 return false;
8196 if (file_exists("$path/lib.php")) {
8197 include_once("$path/lib.php");
8198 $function = $component.'_supports';
8202 if ($function and function_exists($function)) {
8203 $supports = $function($feature);
8204 if (is_null($supports)) {
8205 // Plugin does not know - use default.
8206 return $default;
8207 } else {
8208 return $supports;
8212 // Plugin does not care, so use default.
8213 return $default;
8217 * Returns true if the current version of PHP is greater that the specified one.
8219 * @todo Check PHP version being required here is it too low?
8221 * @param string $version The version of php being tested.
8222 * @return bool
8224 function check_php_version($version='5.2.4') {
8225 return (version_compare(phpversion(), $version) >= 0);
8229 * Determine if moodle installation requires update.
8231 * Checks version numbers of main code and all plugins to see
8232 * if there are any mismatches.
8234 * @return bool
8236 function moodle_needs_upgrading() {
8237 global $CFG;
8239 if (empty($CFG->version)) {
8240 return true;
8243 // There is no need to purge plugininfo caches here because
8244 // these caches are not used during upgrade and they are purged after
8245 // every upgrade.
8247 if (empty($CFG->allversionshash)) {
8248 return true;
8251 $hash = core_component::get_all_versions_hash();
8253 return ($hash !== $CFG->allversionshash);
8257 * Returns the major version of this site
8259 * Moodle version numbers consist of three numbers separated by a dot, for
8260 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8261 * called major version. This function extracts the major version from either
8262 * $CFG->release (default) or eventually from the $release variable defined in
8263 * the main version.php.
8265 * @param bool $fromdisk should the version if source code files be used
8266 * @return string|false the major version like '2.3', false if could not be determined
8268 function moodle_major_version($fromdisk = false) {
8269 global $CFG;
8271 if ($fromdisk) {
8272 $release = null;
8273 require($CFG->dirroot.'/version.php');
8274 if (empty($release)) {
8275 return false;
8278 } else {
8279 if (empty($CFG->release)) {
8280 return false;
8282 $release = $CFG->release;
8285 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8286 return $matches[0];
8287 } else {
8288 return false;
8292 // MISCELLANEOUS.
8295 * Gets the system locale
8297 * @return string Retuns the current locale.
8299 function moodle_getlocale() {
8300 global $CFG;
8302 // Fetch the correct locale based on ostype.
8303 if ($CFG->ostype == 'WINDOWS') {
8304 $stringtofetch = 'localewin';
8305 } else {
8306 $stringtofetch = 'locale';
8309 if (!empty($CFG->locale)) { // Override locale for all language packs.
8310 return $CFG->locale;
8313 return get_string($stringtofetch, 'langconfig');
8317 * Sets the system locale
8319 * @category string
8320 * @param string $locale Can be used to force a locale
8322 function moodle_setlocale($locale='') {
8323 global $CFG;
8325 static $currentlocale = ''; // Last locale caching.
8327 $oldlocale = $currentlocale;
8329 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8330 if (!empty($locale)) {
8331 $currentlocale = $locale;
8332 } else {
8333 $currentlocale = moodle_getlocale();
8336 // Do nothing if locale already set up.
8337 if ($oldlocale == $currentlocale) {
8338 return;
8341 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8342 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8343 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8345 // Get current values.
8346 $monetary= setlocale (LC_MONETARY, 0);
8347 $numeric = setlocale (LC_NUMERIC, 0);
8348 $ctype = setlocale (LC_CTYPE, 0);
8349 if ($CFG->ostype != 'WINDOWS') {
8350 $messages= setlocale (LC_MESSAGES, 0);
8352 // Set locale to all.
8353 $result = setlocale (LC_ALL, $currentlocale);
8354 // If setting of locale fails try the other utf8 or utf-8 variant,
8355 // some operating systems support both (Debian), others just one (OSX).
8356 if ($result === false) {
8357 if (stripos($currentlocale, '.UTF-8') !== false) {
8358 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8359 setlocale (LC_ALL, $newlocale);
8360 } else if (stripos($currentlocale, '.UTF8') !== false) {
8361 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8362 setlocale (LC_ALL, $newlocale);
8365 // Set old values.
8366 setlocale (LC_MONETARY, $monetary);
8367 setlocale (LC_NUMERIC, $numeric);
8368 if ($CFG->ostype != 'WINDOWS') {
8369 setlocale (LC_MESSAGES, $messages);
8371 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8372 // To workaround a well-known PHP problem with Turkish letter Ii.
8373 setlocale (LC_CTYPE, $ctype);
8378 * Count words in a string.
8380 * Words are defined as things between whitespace.
8382 * @category string
8383 * @param string $string The text to be searched for words. May be HTML.
8384 * @return int The count of words in the specified string
8386 function count_words($string) {
8387 // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8388 // Also, br is a special case because it definitely delimits a word, but has no close tag.
8389 $string = preg_replace('~
8390 ( # Capture the tag we match.
8391 </ # Start of close tag.
8392 (?! # Do not match any of these specific close tag names.
8393 a> | b> | del> | em> | i> |
8394 ins> | s> | small> | span> |
8395 strong> | sub> | sup> | u>
8397 \w+ # But, apart from those execptions, match any tag name.
8398 > # End of close tag.
8400 <br> | <br\s*/> # Special cases that are not close tags.
8402 ~x', '$1 ', $string); // Add a space after the close tag.
8403 // Now remove HTML tags.
8404 $string = strip_tags($string);
8405 // Decode HTML entities.
8406 $string = html_entity_decode($string, ENT_COMPAT);
8408 // Now, the word count is the number of blocks of characters separated
8409 // by any sort of space. That seems to be the definition used by all other systems.
8410 // To be precise about what is considered to separate words:
8411 // * Anything that Unicode considers a 'Separator'
8412 // * Anything that Unicode considers a 'Control character'
8413 // * An em- or en- dash.
8414 return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY));
8418 * Count letters in a string.
8420 * Letters are defined as chars not in tags and different from whitespace.
8422 * @category string
8423 * @param string $string The text to be searched for letters. May be HTML.
8424 * @return int The count of letters in the specified text.
8426 function count_letters($string) {
8427 $string = strip_tags($string); // Tags are out now.
8428 $string = html_entity_decode($string, ENT_COMPAT);
8429 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8431 return core_text::strlen($string);
8435 * Generate and return a random string of the specified length.
8437 * @param int $length The length of the string to be created.
8438 * @return string
8440 function random_string($length=15) {
8441 $randombytes = random_bytes_emulate($length);
8442 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8443 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8444 $pool .= '0123456789';
8445 $poollen = strlen($pool);
8446 $string = '';
8447 for ($i = 0; $i < $length; $i++) {
8448 $rand = ord($randombytes[$i]);
8449 $string .= substr($pool, ($rand%($poollen)), 1);
8451 return $string;
8455 * Generate a complex random string (useful for md5 salts)
8457 * This function is based on the above {@link random_string()} however it uses a
8458 * larger pool of characters and generates a string between 24 and 32 characters
8460 * @param int $length Optional if set generates a string to exactly this length
8461 * @return string
8463 function complex_random_string($length=null) {
8464 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8465 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8466 $poollen = strlen($pool);
8467 if ($length===null) {
8468 $length = floor(rand(24, 32));
8470 $randombytes = random_bytes_emulate($length);
8471 $string = '';
8472 for ($i = 0; $i < $length; $i++) {
8473 $rand = ord($randombytes[$i]);
8474 $string .= $pool[($rand%$poollen)];
8476 return $string;
8480 * Try to generates cryptographically secure pseudo-random bytes.
8482 * Note this is achieved by fallbacking between:
8483 * - PHP 7 random_bytes().
8484 * - OpenSSL openssl_random_pseudo_bytes().
8485 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8487 * @param int $length requested length in bytes
8488 * @return string binary data
8490 function random_bytes_emulate($length) {
8491 global $CFG;
8492 if ($length <= 0) {
8493 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8494 return '';
8496 if (function_exists('random_bytes')) {
8497 // Use PHP 7 goodness.
8498 $hash = @random_bytes($length);
8499 if ($hash !== false) {
8500 return $hash;
8503 if (function_exists('openssl_random_pseudo_bytes')) {
8504 // If you have the openssl extension enabled.
8505 $hash = openssl_random_pseudo_bytes($length);
8506 if ($hash !== false) {
8507 return $hash;
8511 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8512 $staticdata = serialize($CFG) . serialize($_SERVER);
8513 $hash = '';
8514 do {
8515 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8516 } while (strlen($hash) < $length);
8518 return substr($hash, 0, $length);
8522 * Given some text (which may contain HTML) and an ideal length,
8523 * this function truncates the text neatly on a word boundary if possible
8525 * @category string
8526 * @param string $text text to be shortened
8527 * @param int $ideal ideal string length
8528 * @param boolean $exact if false, $text will not be cut mid-word
8529 * @param string $ending The string to append if the passed string is truncated
8530 * @return string $truncate shortened string
8532 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8533 // If the plain text is shorter than the maximum length, return the whole text.
8534 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8535 return $text;
8538 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8539 // and only tag in its 'line'.
8540 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8542 $totallength = core_text::strlen($ending);
8543 $truncate = '';
8545 // This array stores information about open and close tags and their position
8546 // in the truncated string. Each item in the array is an object with fields
8547 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8548 // (byte position in truncated text).
8549 $tagdetails = array();
8551 foreach ($lines as $linematchings) {
8552 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8553 if (!empty($linematchings[1])) {
8554 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8555 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8556 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8557 // Record closing tag.
8558 $tagdetails[] = (object) array(
8559 'open' => false,
8560 'tag' => core_text::strtolower($tagmatchings[1]),
8561 'pos' => core_text::strlen($truncate),
8564 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8565 // Record opening tag.
8566 $tagdetails[] = (object) array(
8567 'open' => true,
8568 'tag' => core_text::strtolower($tagmatchings[1]),
8569 'pos' => core_text::strlen($truncate),
8571 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8572 $tagdetails[] = (object) array(
8573 'open' => true,
8574 'tag' => core_text::strtolower('if'),
8575 'pos' => core_text::strlen($truncate),
8577 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8578 $tagdetails[] = (object) array(
8579 'open' => false,
8580 'tag' => core_text::strtolower('if'),
8581 'pos' => core_text::strlen($truncate),
8585 // Add html-tag to $truncate'd text.
8586 $truncate .= $linematchings[1];
8589 // Calculate the length of the plain text part of the line; handle entities as one character.
8590 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8591 if ($totallength + $contentlength > $ideal) {
8592 // The number of characters which are left.
8593 $left = $ideal - $totallength;
8594 $entitieslength = 0;
8595 // Search for html entities.
8596 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)) {
8597 // Calculate the real length of all entities in the legal range.
8598 foreach ($entities[0] as $entity) {
8599 if ($entity[1]+1-$entitieslength <= $left) {
8600 $left--;
8601 $entitieslength += core_text::strlen($entity[0]);
8602 } else {
8603 // No more characters left.
8604 break;
8608 $breakpos = $left + $entitieslength;
8610 // If the words shouldn't be cut in the middle...
8611 if (!$exact) {
8612 // Search the last occurence of a space.
8613 for (; $breakpos > 0; $breakpos--) {
8614 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8615 if ($char === '.' or $char === ' ') {
8616 $breakpos += 1;
8617 break;
8618 } else if (strlen($char) > 2) {
8619 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8620 $breakpos += 1;
8621 break;
8626 if ($breakpos == 0) {
8627 // This deals with the test_shorten_text_no_spaces case.
8628 $breakpos = $left + $entitieslength;
8629 } else if ($breakpos > $left + $entitieslength) {
8630 // This deals with the previous for loop breaking on the first char.
8631 $breakpos = $left + $entitieslength;
8634 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8635 // Maximum length is reached, so get off the loop.
8636 break;
8637 } else {
8638 $truncate .= $linematchings[2];
8639 $totallength += $contentlength;
8642 // If the maximum length is reached, get off the loop.
8643 if ($totallength >= $ideal) {
8644 break;
8648 // Add the defined ending to the text.
8649 $truncate .= $ending;
8651 // Now calculate the list of open html tags based on the truncate position.
8652 $opentags = array();
8653 foreach ($tagdetails as $taginfo) {
8654 if ($taginfo->open) {
8655 // Add tag to the beginning of $opentags list.
8656 array_unshift($opentags, $taginfo->tag);
8657 } else {
8658 // Can have multiple exact same open tags, close the last one.
8659 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8660 if ($pos !== false) {
8661 unset($opentags[$pos]);
8666 // Close all unclosed html-tags.
8667 foreach ($opentags as $tag) {
8668 if ($tag === 'if') {
8669 $truncate .= '<!--<![endif]-->';
8670 } else {
8671 $truncate .= '</' . $tag . '>';
8675 return $truncate;
8679 * Shortens a given filename by removing characters positioned after the ideal string length.
8680 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8681 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8683 * @param string $filename file name
8684 * @param int $length ideal string length
8685 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8686 * @return string $shortened shortened file name
8688 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8689 $shortened = $filename;
8690 // Extract a part of the filename if it's char size exceeds the ideal string length.
8691 if (core_text::strlen($filename) > $length) {
8692 // Exclude extension if present in filename.
8693 $mimetypes = get_mimetypes_array();
8694 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8695 if ($extension && !empty($mimetypes[$extension])) {
8696 $basename = pathinfo($filename, PATHINFO_FILENAME);
8697 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8698 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8699 $shortened .= '.' . $extension;
8700 } else {
8701 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8702 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8705 return $shortened;
8709 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8711 * @param array $path The paths to reduce the length.
8712 * @param int $length Ideal string length
8713 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8714 * @return array $result Shortened paths in array.
8716 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8717 $result = null;
8719 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8720 $carry[] = shorten_filename($singlepath, $length, $includehash);
8721 return $carry;
8722 }, []);
8724 return $result;
8728 * Given dates in seconds, how many weeks is the date from startdate
8729 * The first week is 1, the second 2 etc ...
8731 * @param int $startdate Timestamp for the start date
8732 * @param int $thedate Timestamp for the end date
8733 * @return string
8735 function getweek ($startdate, $thedate) {
8736 if ($thedate < $startdate) {
8737 return 0;
8740 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8744 * Returns a randomly generated password of length $maxlen. inspired by
8746 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8747 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8749 * @param int $maxlen The maximum size of the password being generated.
8750 * @return string
8752 function generate_password($maxlen=10) {
8753 global $CFG;
8755 if (empty($CFG->passwordpolicy)) {
8756 $fillers = PASSWORD_DIGITS;
8757 $wordlist = file($CFG->wordlist);
8758 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8759 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8760 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8761 $password = $word1 . $filler1 . $word2;
8762 } else {
8763 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8764 $digits = $CFG->minpassworddigits;
8765 $lower = $CFG->minpasswordlower;
8766 $upper = $CFG->minpasswordupper;
8767 $nonalphanum = $CFG->minpasswordnonalphanum;
8768 $total = $lower + $upper + $digits + $nonalphanum;
8769 // Var minlength should be the greater one of the two ( $minlen and $total ).
8770 $minlen = $minlen < $total ? $total : $minlen;
8771 // Var maxlen can never be smaller than minlen.
8772 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8773 $additional = $maxlen - $total;
8775 // Make sure we have enough characters to fulfill
8776 // complexity requirements.
8777 $passworddigits = PASSWORD_DIGITS;
8778 while ($digits > strlen($passworddigits)) {
8779 $passworddigits .= PASSWORD_DIGITS;
8781 $passwordlower = PASSWORD_LOWER;
8782 while ($lower > strlen($passwordlower)) {
8783 $passwordlower .= PASSWORD_LOWER;
8785 $passwordupper = PASSWORD_UPPER;
8786 while ($upper > strlen($passwordupper)) {
8787 $passwordupper .= PASSWORD_UPPER;
8789 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8790 while ($nonalphanum > strlen($passwordnonalphanum)) {
8791 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8794 // Now mix and shuffle it all.
8795 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8796 substr(str_shuffle ($passwordupper), 0, $upper) .
8797 substr(str_shuffle ($passworddigits), 0, $digits) .
8798 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8799 substr(str_shuffle ($passwordlower .
8800 $passwordupper .
8801 $passworddigits .
8802 $passwordnonalphanum), 0 , $additional));
8805 return substr ($password, 0, $maxlen);
8809 * Given a float, prints it nicely.
8810 * Localized floats must not be used in calculations!
8812 * The stripzeros feature is intended for making numbers look nicer in small
8813 * areas where it is not necessary to indicate the degree of accuracy by showing
8814 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8815 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8817 * @param float $float The float to print
8818 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8819 * @param bool $localized use localized decimal separator
8820 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8821 * the decimal point are always striped if $decimalpoints is -1.
8822 * @return string locale float
8824 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8825 if (is_null($float)) {
8826 return '';
8828 if ($localized) {
8829 $separator = get_string('decsep', 'langconfig');
8830 } else {
8831 $separator = '.';
8833 if ($decimalpoints == -1) {
8834 // The following counts the number of decimals.
8835 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8836 $floatval = floatval($float);
8837 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
8840 $result = number_format($float, $decimalpoints, $separator, '');
8841 if ($stripzeros && $decimalpoints > 0) {
8842 // Remove zeros and final dot if not needed.
8843 // However, only do this if there is a decimal point!
8844 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8846 return $result;
8850 * Converts locale specific floating point/comma number back to standard PHP float value
8851 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8853 * @param string $localefloat locale aware float representation
8854 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8855 * @return mixed float|bool - false or the parsed float.
8857 function unformat_float($localefloat, $strict = false) {
8858 $localefloat = trim((string)$localefloat);
8860 if ($localefloat == '') {
8861 return null;
8864 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8865 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8867 if ($strict && !is_numeric($localefloat)) {
8868 return false;
8871 return (float)$localefloat;
8875 * Given a simple array, this shuffles it up just like shuffle()
8876 * Unlike PHP's shuffle() this function works on any machine.
8878 * @param array $array The array to be rearranged
8879 * @return array
8881 function swapshuffle($array) {
8883 $last = count($array) - 1;
8884 for ($i = 0; $i <= $last; $i++) {
8885 $from = rand(0, $last);
8886 $curr = $array[$i];
8887 $array[$i] = $array[$from];
8888 $array[$from] = $curr;
8890 return $array;
8894 * Like {@link swapshuffle()}, but works on associative arrays
8896 * @param array $array The associative array to be rearranged
8897 * @return array
8899 function swapshuffle_assoc($array) {
8901 $newarray = array();
8902 $newkeys = swapshuffle(array_keys($array));
8904 foreach ($newkeys as $newkey) {
8905 $newarray[$newkey] = $array[$newkey];
8907 return $newarray;
8911 * Given an arbitrary array, and a number of draws,
8912 * this function returns an array with that amount
8913 * of items. The indexes are retained.
8915 * @todo Finish documenting this function
8917 * @param array $array
8918 * @param int $draws
8919 * @return array
8921 function draw_rand_array($array, $draws) {
8923 $return = array();
8925 $last = count($array);
8927 if ($draws > $last) {
8928 $draws = $last;
8931 while ($draws > 0) {
8932 $last--;
8934 $keys = array_keys($array);
8935 $rand = rand(0, $last);
8937 $return[$keys[$rand]] = $array[$keys[$rand]];
8938 unset($array[$keys[$rand]]);
8940 $draws--;
8943 return $return;
8947 * Calculate the difference between two microtimes
8949 * @param string $a The first Microtime
8950 * @param string $b The second Microtime
8951 * @return string
8953 function microtime_diff($a, $b) {
8954 list($adec, $asec) = explode(' ', $a);
8955 list($bdec, $bsec) = explode(' ', $b);
8956 return $bsec - $asec + $bdec - $adec;
8960 * Given a list (eg a,b,c,d,e) this function returns
8961 * an array of 1->a, 2->b, 3->c etc
8963 * @param string $list The string to explode into array bits
8964 * @param string $separator The separator used within the list string
8965 * @return array The now assembled array
8967 function make_menu_from_list($list, $separator=',') {
8969 $array = array_reverse(explode($separator, $list), true);
8970 foreach ($array as $key => $item) {
8971 $outarray[$key+1] = trim($item);
8973 return $outarray;
8977 * Creates an array that represents all the current grades that
8978 * can be chosen using the given grading type.
8980 * Negative numbers
8981 * are scales, zero is no grade, and positive numbers are maximum
8982 * grades.
8984 * @todo Finish documenting this function or better deprecated this completely!
8986 * @param int $gradingtype
8987 * @return array
8989 function make_grades_menu($gradingtype) {
8990 global $DB;
8992 $grades = array();
8993 if ($gradingtype < 0) {
8994 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8995 return make_menu_from_list($scale->scale);
8997 } else if ($gradingtype > 0) {
8998 for ($i=$gradingtype; $i>=0; $i--) {
8999 $grades[$i] = $i .' / '. $gradingtype;
9001 return $grades;
9003 return $grades;
9007 * make_unique_id_code
9009 * @todo Finish documenting this function
9011 * @uses $_SERVER
9012 * @param string $extra Extra string to append to the end of the code
9013 * @return string
9015 function make_unique_id_code($extra = '') {
9017 $hostname = 'unknownhost';
9018 if (!empty($_SERVER['HTTP_HOST'])) {
9019 $hostname = $_SERVER['HTTP_HOST'];
9020 } else if (!empty($_ENV['HTTP_HOST'])) {
9021 $hostname = $_ENV['HTTP_HOST'];
9022 } else if (!empty($_SERVER['SERVER_NAME'])) {
9023 $hostname = $_SERVER['SERVER_NAME'];
9024 } else if (!empty($_ENV['SERVER_NAME'])) {
9025 $hostname = $_ENV['SERVER_NAME'];
9028 $date = gmdate("ymdHis");
9030 $random = random_string(6);
9032 if ($extra) {
9033 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
9034 } else {
9035 return $hostname .'+'. $date .'+'. $random;
9041 * Function to check the passed address is within the passed subnet
9043 * The parameter is a comma separated string of subnet definitions.
9044 * Subnet strings can be in one of three formats:
9045 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
9046 * 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)
9047 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
9048 * Code for type 1 modified from user posted comments by mediator at
9049 * {@link http://au.php.net/manual/en/function.ip2long.php}
9051 * @param string $addr The address you are checking
9052 * @param string $subnetstr The string of subnet addresses
9053 * @return bool
9055 function address_in_subnet($addr, $subnetstr) {
9057 if ($addr == '0.0.0.0') {
9058 return false;
9060 $subnets = explode(',', $subnetstr);
9061 $found = false;
9062 $addr = trim($addr);
9063 $addr = cleanremoteaddr($addr, false); // Normalise.
9064 if ($addr === null) {
9065 return false;
9067 $addrparts = explode(':', $addr);
9069 $ipv6 = strpos($addr, ':');
9071 foreach ($subnets as $subnet) {
9072 $subnet = trim($subnet);
9073 if ($subnet === '') {
9074 continue;
9077 if (strpos($subnet, '/') !== false) {
9078 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
9079 list($ip, $mask) = explode('/', $subnet);
9080 $mask = trim($mask);
9081 if (!is_number($mask)) {
9082 continue; // Incorect mask number, eh?
9084 $ip = cleanremoteaddr($ip, false); // Normalise.
9085 if ($ip === null) {
9086 continue;
9088 if (strpos($ip, ':') !== false) {
9089 // IPv6.
9090 if (!$ipv6) {
9091 continue;
9093 if ($mask > 128 or $mask < 0) {
9094 continue; // Nonsense.
9096 if ($mask == 0) {
9097 return true; // Any address.
9099 if ($mask == 128) {
9100 if ($ip === $addr) {
9101 return true;
9103 continue;
9105 $ipparts = explode(':', $ip);
9106 $modulo = $mask % 16;
9107 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9108 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9109 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9110 if ($modulo == 0) {
9111 return true;
9113 $pos = ($mask-$modulo)/16;
9114 $ipnet = hexdec($ipparts[$pos]);
9115 $addrnet = hexdec($addrparts[$pos]);
9116 $mask = 0xffff << (16 - $modulo);
9117 if (($addrnet & $mask) == ($ipnet & $mask)) {
9118 return true;
9122 } else {
9123 // IPv4.
9124 if ($ipv6) {
9125 continue;
9127 if ($mask > 32 or $mask < 0) {
9128 continue; // Nonsense.
9130 if ($mask == 0) {
9131 return true;
9133 if ($mask == 32) {
9134 if ($ip === $addr) {
9135 return true;
9137 continue;
9139 $mask = 0xffffffff << (32 - $mask);
9140 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9141 return true;
9145 } else if (strpos($subnet, '-') !== false) {
9146 // 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.
9147 $parts = explode('-', $subnet);
9148 if (count($parts) != 2) {
9149 continue;
9152 if (strpos($subnet, ':') !== false) {
9153 // IPv6.
9154 if (!$ipv6) {
9155 continue;
9157 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9158 if ($ipstart === null) {
9159 continue;
9161 $ipparts = explode(':', $ipstart);
9162 $start = hexdec(array_pop($ipparts));
9163 $ipparts[] = trim($parts[1]);
9164 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9165 if ($ipend === null) {
9166 continue;
9168 $ipparts[7] = '';
9169 $ipnet = implode(':', $ipparts);
9170 if (strpos($addr, $ipnet) !== 0) {
9171 continue;
9173 $ipparts = explode(':', $ipend);
9174 $end = hexdec($ipparts[7]);
9176 $addrend = hexdec($addrparts[7]);
9178 if (($addrend >= $start) and ($addrend <= $end)) {
9179 return true;
9182 } else {
9183 // IPv4.
9184 if ($ipv6) {
9185 continue;
9187 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9188 if ($ipstart === null) {
9189 continue;
9191 $ipparts = explode('.', $ipstart);
9192 $ipparts[3] = trim($parts[1]);
9193 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9194 if ($ipend === null) {
9195 continue;
9198 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9199 return true;
9203 } else {
9204 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9205 if (strpos($subnet, ':') !== false) {
9206 // IPv6.
9207 if (!$ipv6) {
9208 continue;
9210 $parts = explode(':', $subnet);
9211 $count = count($parts);
9212 if ($parts[$count-1] === '') {
9213 unset($parts[$count-1]); // Trim trailing :'s.
9214 $count--;
9215 $subnet = implode('.', $parts);
9217 $isip = cleanremoteaddr($subnet, false); // Normalise.
9218 if ($isip !== null) {
9219 if ($isip === $addr) {
9220 return true;
9222 continue;
9223 } else if ($count > 8) {
9224 continue;
9226 $zeros = array_fill(0, 8-$count, '0');
9227 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9228 if (address_in_subnet($addr, $subnet)) {
9229 return true;
9232 } else {
9233 // IPv4.
9234 if ($ipv6) {
9235 continue;
9237 $parts = explode('.', $subnet);
9238 $count = count($parts);
9239 if ($parts[$count-1] === '') {
9240 unset($parts[$count-1]); // Trim trailing .
9241 $count--;
9242 $subnet = implode('.', $parts);
9244 if ($count == 4) {
9245 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9246 if ($subnet === $addr) {
9247 return true;
9249 continue;
9250 } else if ($count > 4) {
9251 continue;
9253 $zeros = array_fill(0, 4-$count, '0');
9254 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9255 if (address_in_subnet($addr, $subnet)) {
9256 return true;
9262 return false;
9266 * For outputting debugging info
9268 * @param string $string The string to write
9269 * @param string $eol The end of line char(s) to use
9270 * @param string $sleep Period to make the application sleep
9271 * This ensures any messages have time to display before redirect
9273 function mtrace($string, $eol="\n", $sleep=0) {
9274 global $CFG;
9276 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
9277 $fn = $CFG->mtrace_wrapper;
9278 $fn($string, $eol);
9279 return;
9280 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
9281 // We must explicitly call the add_line function here.
9282 // Uses of fwrite to STDOUT are not picked up by ob_start.
9283 if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
9284 fwrite(STDOUT, $output);
9286 } else {
9287 echo $string . $eol;
9290 // Flush again.
9291 flush();
9293 // Delay to keep message on user's screen in case of subsequent redirect.
9294 if ($sleep) {
9295 sleep($sleep);
9300 * Helper to {@see mtrace()} an exception or throwable, including all relevant information.
9302 * @param Throwable $e the error to ouptput.
9304 function mtrace_exception(Throwable $e): void {
9305 $info = get_exception_info($e);
9307 $message = $info->message;
9308 if ($info->debuginfo) {
9309 $message .= "\n\n" . $info->debuginfo;
9311 if ($info->backtrace) {
9312 $message .= "\n\n" . format_backtrace($info->backtrace, true);
9315 mtrace($message);
9319 * Replace 1 or more slashes or backslashes to 1 slash
9321 * @param string $path The path to strip
9322 * @return string the path with double slashes removed
9324 function cleardoubleslashes ($path) {
9325 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9329 * Is the current ip in a given list?
9331 * @param string $list
9332 * @return bool
9334 function remoteip_in_list($list) {
9335 $clientip = getremoteaddr(null);
9337 if (!$clientip) {
9338 // Ensure access on cli.
9339 return true;
9341 return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
9345 * Returns most reliable client address
9347 * @param string $default If an address can't be determined, then return this
9348 * @return string The remote IP address
9350 function getremoteaddr($default='0.0.0.0') {
9351 global $CFG;
9353 if (!isset($CFG->getremoteaddrconf)) {
9354 // This will happen, for example, before just after the upgrade, as the
9355 // user is redirected to the admin screen.
9356 $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT;
9357 } else {
9358 $variablestoskip = $CFG->getremoteaddrconf;
9360 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9361 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9362 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9363 return $address ? $address : $default;
9366 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9367 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9368 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9370 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9371 global $CFG;
9372 return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
9375 // Multiple proxies can append values to this header including an
9376 // untrusted original request header so we must only trust the last ip.
9377 $address = end($forwardedaddresses);
9379 if (substr_count($address, ":") > 1) {
9380 // Remove port and brackets from IPv6.
9381 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9382 $address = $matches[1];
9384 } else {
9385 // Remove port from IPv4.
9386 if (substr_count($address, ":") == 1) {
9387 $parts = explode(":", $address);
9388 $address = $parts[0];
9392 $address = cleanremoteaddr($address);
9393 return $address ? $address : $default;
9396 if (!empty($_SERVER['REMOTE_ADDR'])) {
9397 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9398 return $address ? $address : $default;
9399 } else {
9400 return $default;
9405 * Cleans an ip address. Internal addresses are now allowed.
9406 * (Originally local addresses were not allowed.)
9408 * @param string $addr IPv4 or IPv6 address
9409 * @param bool $compress use IPv6 address compression
9410 * @return string normalised ip address string, null if error
9412 function cleanremoteaddr($addr, $compress=false) {
9413 $addr = trim($addr);
9415 if (strpos($addr, ':') !== false) {
9416 // Can be only IPv6.
9417 $parts = explode(':', $addr);
9418 $count = count($parts);
9420 if (strpos($parts[$count-1], '.') !== false) {
9421 // Legacy ipv4 notation.
9422 $last = array_pop($parts);
9423 $ipv4 = cleanremoteaddr($last, true);
9424 if ($ipv4 === null) {
9425 return null;
9427 $bits = explode('.', $ipv4);
9428 $parts[] = dechex($bits[0]).dechex($bits[1]);
9429 $parts[] = dechex($bits[2]).dechex($bits[3]);
9430 $count = count($parts);
9431 $addr = implode(':', $parts);
9434 if ($count < 3 or $count > 8) {
9435 return null; // Severly malformed.
9438 if ($count != 8) {
9439 if (strpos($addr, '::') === false) {
9440 return null; // Malformed.
9442 // Uncompress.
9443 $insertat = array_search('', $parts, true);
9444 $missing = array_fill(0, 1 + 8 - $count, '0');
9445 array_splice($parts, $insertat, 1, $missing);
9446 foreach ($parts as $key => $part) {
9447 if ($part === '') {
9448 $parts[$key] = '0';
9453 $adr = implode(':', $parts);
9454 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9455 return null; // Incorrect format - sorry.
9458 // Normalise 0s and case.
9459 $parts = array_map('hexdec', $parts);
9460 $parts = array_map('dechex', $parts);
9462 $result = implode(':', $parts);
9464 if (!$compress) {
9465 return $result;
9468 if ($result === '0:0:0:0:0:0:0:0') {
9469 return '::'; // All addresses.
9472 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9473 if ($compressed !== $result) {
9474 return $compressed;
9477 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9478 if ($compressed !== $result) {
9479 return $compressed;
9482 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9483 if ($compressed !== $result) {
9484 return $compressed;
9487 return $result;
9490 // First get all things that look like IPv4 addresses.
9491 $parts = array();
9492 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9493 return null;
9495 unset($parts[0]);
9497 foreach ($parts as $key => $match) {
9498 if ($match > 255) {
9499 return null;
9501 $parts[$key] = (int)$match; // Normalise 0s.
9504 return implode('.', $parts);
9509 * Is IP address a public address?
9511 * @param string $ip The ip to check
9512 * @return bool true if the ip is public
9514 function ip_is_public($ip) {
9515 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9519 * This function will make a complete copy of anything it's given,
9520 * regardless of whether it's an object or not.
9522 * @param mixed $thing Something you want cloned
9523 * @return mixed What ever it is you passed it
9525 function fullclone($thing) {
9526 return unserialize(serialize($thing));
9530 * Used to make sure that $min <= $value <= $max
9532 * Make sure that value is between min, and max
9534 * @param int $min The minimum value
9535 * @param int $value The value to check
9536 * @param int $max The maximum value
9537 * @return int
9539 function bounded_number($min, $value, $max) {
9540 if ($value < $min) {
9541 return $min;
9543 if ($value > $max) {
9544 return $max;
9546 return $value;
9550 * Check if there is a nested array within the passed array
9552 * @param array $array
9553 * @return bool true if there is a nested array false otherwise
9555 function array_is_nested($array) {
9556 foreach ($array as $value) {
9557 if (is_array($value)) {
9558 return true;
9561 return false;
9565 * get_performance_info() pairs up with init_performance_info()
9566 * loaded in setup.php. Returns an array with 'html' and 'txt'
9567 * values ready for use, and each of the individual stats provided
9568 * separately as well.
9570 * @return array
9572 function get_performance_info() {
9573 global $CFG, $PERF, $DB, $PAGE;
9575 $info = array();
9576 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9578 $info['html'] = '';
9579 if (!empty($CFG->themedesignermode)) {
9580 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9581 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9583 $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
9585 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9587 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9588 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9590 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9591 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9593 if (function_exists('memory_get_usage')) {
9594 $info['memory_total'] = memory_get_usage();
9595 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9596 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9597 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9598 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9601 if (function_exists('memory_get_peak_usage')) {
9602 $info['memory_peak'] = memory_get_peak_usage();
9603 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9604 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9607 $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9608 $inc = get_included_files();
9609 $info['includecount'] = count($inc);
9610 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9611 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9613 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9614 // We can not track more performance before installation or before PAGE init, sorry.
9615 return $info;
9618 $filtermanager = filter_manager::instance();
9619 if (method_exists($filtermanager, 'get_performance_summary')) {
9620 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9621 $info = array_merge($filterinfo, $info);
9622 foreach ($filterinfo as $key => $value) {
9623 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9624 $info['txt'] .= "$key: $value ";
9628 $stringmanager = get_string_manager();
9629 if (method_exists($stringmanager, 'get_performance_summary')) {
9630 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9631 $info = array_merge($filterinfo, $info);
9632 foreach ($filterinfo as $key => $value) {
9633 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9634 $info['txt'] .= "$key: $value ";
9638 if (!empty($PERF->logwrites)) {
9639 $info['logwrites'] = $PERF->logwrites;
9640 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9641 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9644 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9645 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9646 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9648 if ($DB->want_read_slave()) {
9649 $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9650 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9651 $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9654 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9655 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9656 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9658 if (function_exists('posix_times')) {
9659 $ptimes = posix_times();
9660 if (is_array($ptimes)) {
9661 foreach ($ptimes as $key => $val) {
9662 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9664 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9665 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9666 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9670 // Grab the load average for the last minute.
9671 // /proc will only work under some linux configurations
9672 // while uptime is there under MacOSX/Darwin and other unices.
9673 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9674 list($serverload) = explode(' ', $loadavg[0]);
9675 unset($loadavg);
9676 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9677 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9678 $serverload = $matches[1];
9679 } else {
9680 trigger_error('Could not parse uptime output!');
9683 if (!empty($serverload)) {
9684 $info['serverload'] = $serverload;
9685 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9686 $info['txt'] .= "serverload: {$info['serverload']} ";
9689 // Display size of session if session started.
9690 if ($si = \core\session\manager::get_performance_info()) {
9691 $info['sessionsize'] = $si['size'];
9692 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9693 $info['txt'] .= $si['txt'];
9696 // Display time waiting for session if applicable.
9697 if (!empty($PERF->sessionlock['wait'])) {
9698 $sessionwait = number_format($PERF->sessionlock['wait'], 3) . ' secs';
9699 $info['html'] .= html_writer::tag('li', 'Session wait: ' . $sessionwait, [
9700 'class' => 'sessionwait col-sm-4'
9702 $info['txt'] .= 'sessionwait: ' . $sessionwait . ' ';
9705 $info['html'] .= '</ul>';
9706 $html = '';
9707 if ($stats = cache_helper::get_stats()) {
9709 $table = new html_table();
9710 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9711 $table->head = ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S', 'I/O'];
9712 $table->data = [];
9713 $table->align = ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right', 'right'];
9715 $text = 'Caches used (hits/misses/sets): ';
9716 $hits = 0;
9717 $misses = 0;
9718 $sets = 0;
9719 $maxstores = 0;
9721 // We want to align static caches into their own column.
9722 $hasstatic = false;
9723 foreach ($stats as $definition => $details) {
9724 $numstores = count($details['stores']);
9725 $first = key($details['stores']);
9726 if ($first !== cache_store::STATIC_ACCEL) {
9727 $numstores++; // Add a blank space for the missing static store.
9729 $maxstores = max($maxstores, $numstores);
9732 $storec = 0;
9734 while ($storec++ < ($maxstores - 2)) {
9735 if ($storec == ($maxstores - 2)) {
9736 $table->head[] = get_string('mappingfinal', 'cache');
9737 } else {
9738 $table->head[] = "Store $storec";
9740 $table->align[] = 'left';
9741 $table->align[] = 'right';
9742 $table->align[] = 'right';
9743 $table->align[] = 'right';
9744 $table->align[] = 'right';
9745 $table->head[] = 'H';
9746 $table->head[] = 'M';
9747 $table->head[] = 'S';
9748 $table->head[] = 'I/O';
9751 ksort($stats);
9753 foreach ($stats as $definition => $details) {
9754 switch ($details['mode']) {
9755 case cache_store::MODE_APPLICATION:
9756 $modeclass = 'application';
9757 $mode = ' <span title="application cache">App</span>';
9758 break;
9759 case cache_store::MODE_SESSION:
9760 $modeclass = 'session';
9761 $mode = ' <span title="session cache">Ses</span>';
9762 break;
9763 case cache_store::MODE_REQUEST:
9764 $modeclass = 'request';
9765 $mode = ' <span title="request cache">Req</span>';
9766 break;
9768 $row = [$mode, $definition];
9770 $text .= "$definition {";
9772 $storec = 0;
9773 foreach ($details['stores'] as $store => $data) {
9775 if ($storec == 0 && $store !== cache_store::STATIC_ACCEL) {
9776 $row[] = '';
9777 $row[] = '';
9778 $row[] = '';
9779 $storec++;
9782 $hits += $data['hits'];
9783 $misses += $data['misses'];
9784 $sets += $data['sets'];
9785 if ($data['hits'] == 0 and $data['misses'] > 0) {
9786 $cachestoreclass = 'nohits bg-danger';
9787 } else if ($data['hits'] < $data['misses']) {
9788 $cachestoreclass = 'lowhits bg-warning text-dark';
9789 } else {
9790 $cachestoreclass = 'hihits';
9792 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9793 $cell = new html_table_cell($store);
9794 $cell->attributes = ['class' => $cachestoreclass];
9795 $row[] = $cell;
9796 $cell = new html_table_cell($data['hits']);
9797 $cell->attributes = ['class' => $cachestoreclass];
9798 $row[] = $cell;
9799 $cell = new html_table_cell($data['misses']);
9800 $cell->attributes = ['class' => $cachestoreclass];
9801 $row[] = $cell;
9803 if ($store !== cache_store::STATIC_ACCEL) {
9804 // The static cache is never set.
9805 $cell = new html_table_cell($data['sets']);
9806 $cell->attributes = ['class' => $cachestoreclass];
9807 $row[] = $cell;
9809 if ($data['hits'] || $data['sets']) {
9810 if ($data['iobytes'] === cache_store::IO_BYTES_NOT_SUPPORTED) {
9811 $size = '-';
9812 } else {
9813 $size = display_size($data['iobytes'], 1, 'KB');
9814 if ($data['iobytes'] >= 10 * 1024) {
9815 $cachestoreclass = ' bg-warning text-dark';
9818 } else {
9819 $size = '';
9821 $cell = new html_table_cell($size);
9822 $cell->attributes = ['class' => $cachestoreclass];
9823 $row[] = $cell;
9825 $storec++;
9827 while ($storec++ < $maxstores) {
9828 $row[] = '';
9829 $row[] = '';
9830 $row[] = '';
9831 $row[] = '';
9832 $row[] = '';
9834 $text .= '} ';
9836 $table->data[] = $row;
9839 $html .= html_writer::table($table);
9841 // Now lets also show sub totals for each cache store.
9842 $storetotals = [];
9843 $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9844 foreach ($stats as $definition => $details) {
9845 foreach ($details['stores'] as $store => $data) {
9846 if (!array_key_exists($store, $storetotals)) {
9847 $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9849 $storetotals[$store]['class'] = $data['class'];
9850 $storetotals[$store]['hits'] += $data['hits'];
9851 $storetotals[$store]['misses'] += $data['misses'];
9852 $storetotals[$store]['sets'] += $data['sets'];
9853 $storetotal['hits'] += $data['hits'];
9854 $storetotal['misses'] += $data['misses'];
9855 $storetotal['sets'] += $data['sets'];
9856 if ($data['iobytes'] !== cache_store::IO_BYTES_NOT_SUPPORTED) {
9857 $storetotals[$store]['iobytes'] += $data['iobytes'];
9858 $storetotal['iobytes'] += $data['iobytes'];
9863 $table = new html_table();
9864 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9865 $table->head = [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S', 'I/O'];
9866 $table->data = [];
9867 $table->align = ['left', 'left', 'right', 'right', 'right', 'right'];
9869 ksort($storetotals);
9871 foreach ($storetotals as $store => $data) {
9872 $row = [];
9873 if ($data['hits'] == 0 and $data['misses'] > 0) {
9874 $cachestoreclass = 'nohits bg-danger';
9875 } else if ($data['hits'] < $data['misses']) {
9876 $cachestoreclass = 'lowhits bg-warning text-dark';
9877 } else {
9878 $cachestoreclass = 'hihits';
9880 $cell = new html_table_cell($store);
9881 $cell->attributes = ['class' => $cachestoreclass];
9882 $row[] = $cell;
9883 $cell = new html_table_cell($data['class']);
9884 $cell->attributes = ['class' => $cachestoreclass];
9885 $row[] = $cell;
9886 $cell = new html_table_cell($data['hits']);
9887 $cell->attributes = ['class' => $cachestoreclass];
9888 $row[] = $cell;
9889 $cell = new html_table_cell($data['misses']);
9890 $cell->attributes = ['class' => $cachestoreclass];
9891 $row[] = $cell;
9892 $cell = new html_table_cell($data['sets']);
9893 $cell->attributes = ['class' => $cachestoreclass];
9894 $row[] = $cell;
9895 if ($data['hits'] || $data['sets']) {
9896 if ($data['iobytes']) {
9897 $size = display_size($data['iobytes'], 1, 'KB');
9898 } else {
9899 $size = '-';
9901 } else {
9902 $size = '';
9904 $cell = new html_table_cell($size);
9905 $cell->attributes = ['class' => $cachestoreclass];
9906 $row[] = $cell;
9907 $table->data[] = $row;
9909 if (!empty($storetotal['iobytes'])) {
9910 $size = display_size($storetotal['iobytes'], 1, 'KB');
9911 } else if (!empty($storetotal['hits']) || !empty($storetotal['sets'])) {
9912 $size = '-';
9913 } else {
9914 $size = '';
9916 $row = [
9917 get_string('total'),
9919 $storetotal['hits'],
9920 $storetotal['misses'],
9921 $storetotal['sets'],
9922 $size,
9924 $table->data[] = $row;
9926 $html .= html_writer::table($table);
9928 $info['cachesused'] = "$hits / $misses / $sets";
9929 $info['html'] .= $html;
9930 $info['txt'] .= $text.'. ';
9931 } else {
9932 $info['cachesused'] = '0 / 0 / 0';
9933 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9934 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9937 // Display lock information if any.
9938 if (!empty($PERF->locks)) {
9939 $table = new html_table();
9940 $table->attributes['class'] = 'locktimings table table-dark table-sm w-auto table-bordered';
9941 $table->head = ['Lock', 'Waited (s)', 'Obtained', 'Held for (s)'];
9942 $table->align = ['left', 'right', 'center', 'right'];
9943 $table->data = [];
9944 $text = 'Locks (waited/obtained/held):';
9945 foreach ($PERF->locks as $locktiming) {
9946 $row = [];
9947 $row[] = s($locktiming->type . '/' . $locktiming->resource);
9948 $text .= ' ' . $locktiming->type . '/' . $locktiming->resource . ' (';
9950 // The time we had to wait to get the lock.
9951 $roundedtime = number_format($locktiming->wait, 1);
9952 $cell = new html_table_cell($roundedtime);
9953 if ($locktiming->wait > 0.5) {
9954 $cell->attributes = ['class' => 'bg-warning text-dark'];
9956 $row[] = $cell;
9957 $text .= $roundedtime . '/';
9959 // Show a tick or cross for success.
9960 $row[] = $locktiming->success ? '&#x2713;' : '&#x274c;';
9961 $text .= ($locktiming->success ? 'y' : 'n') . '/';
9963 // If applicable, show how long we held the lock before releasing it.
9964 if (property_exists($locktiming, 'held')) {
9965 $roundedtime = number_format($locktiming->held, 1);
9966 $cell = new html_table_cell($roundedtime);
9967 if ($locktiming->held > 0.5) {
9968 $cell->attributes = ['class' => 'bg-warning text-dark'];
9970 $row[] = $cell;
9971 $text .= $roundedtime;
9972 } else {
9973 $row[] = '-';
9974 $text .= '-';
9976 $text .= ')';
9978 $table->data[] = $row;
9980 $info['html'] .= html_writer::table($table);
9981 $info['txt'] .= $text . '. ';
9984 $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto pt-3">'.$info['html'].'</div>';
9985 return $info;
9989 * Renames a file or directory to a unique name within the same directory.
9991 * This function is designed to avoid any potential race conditions, and select an unused name.
9993 * @param string $filepath Original filepath
9994 * @param string $prefix Prefix to use for the temporary name
9995 * @return string|bool New file path or false if failed
9996 * @since Moodle 3.10
9998 function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
9999 $dir = dirname($filepath);
10000 $basename = $dir . '/' . $prefix;
10001 $limit = 0;
10002 while ($limit < 100) {
10003 // Select a new name based on a random number.
10004 $newfilepath = $basename . md5(mt_rand());
10006 // Attempt a rename to that new name.
10007 if (@rename($filepath, $newfilepath)) {
10008 return $newfilepath;
10011 // The first time, do some sanity checks, maybe it is failing for a good reason and there
10012 // is no point trying 100 times if so.
10013 if ($limit === 0 && (!file_exists($filepath) || !is_writable($dir))) {
10014 return false;
10016 $limit++;
10018 return false;
10022 * Delete directory or only its content
10024 * @param string $dir directory path
10025 * @param bool $contentonly
10026 * @return bool success, true also if dir does not exist
10028 function remove_dir($dir, $contentonly=false) {
10029 if (!is_dir($dir)) {
10030 // Nothing to do.
10031 return true;
10034 if (!$contentonly) {
10035 // Start by renaming the directory; this will guarantee that other processes don't write to it
10036 // while it is in the process of being deleted.
10037 $tempdir = rename_to_unused_name($dir);
10038 if ($tempdir) {
10039 // If the rename was successful then delete the $tempdir instead.
10040 $dir = $tempdir;
10042 // If the rename fails, we will continue through and attempt to delete the directory
10043 // without renaming it since that is likely to at least delete most of the files.
10046 if (!$handle = opendir($dir)) {
10047 return false;
10049 $result = true;
10050 while (false!==($item = readdir($handle))) {
10051 if ($item != '.' && $item != '..') {
10052 if (is_dir($dir.'/'.$item)) {
10053 $result = remove_dir($dir.'/'.$item) && $result;
10054 } else {
10055 $result = unlink($dir.'/'.$item) && $result;
10059 closedir($handle);
10060 if ($contentonly) {
10061 clearstatcache(); // Make sure file stat cache is properly invalidated.
10062 return $result;
10064 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
10065 clearstatcache(); // Make sure file stat cache is properly invalidated.
10066 return $result;
10070 * Detect if an object or a class contains a given property
10071 * will take an actual object or the name of a class
10073 * @param mix $obj Name of class or real object to test
10074 * @param string $property name of property to find
10075 * @return bool true if property exists
10077 function object_property_exists( $obj, $property ) {
10078 if (is_string( $obj )) {
10079 $properties = get_class_vars( $obj );
10080 } else {
10081 $properties = get_object_vars( $obj );
10083 return array_key_exists( $property, $properties );
10087 * Converts an object into an associative array
10089 * This function converts an object into an associative array by iterating
10090 * over its public properties. Because this function uses the foreach
10091 * construct, Iterators are respected. It works recursively on arrays of objects.
10092 * Arrays and simple values are returned as is.
10094 * If class has magic properties, it can implement IteratorAggregate
10095 * and return all available properties in getIterator()
10097 * @param mixed $var
10098 * @return array
10100 function convert_to_array($var) {
10101 $result = array();
10103 // Loop over elements/properties.
10104 foreach ($var as $key => $value) {
10105 // Recursively convert objects.
10106 if (is_object($value) || is_array($value)) {
10107 $result[$key] = convert_to_array($value);
10108 } else {
10109 // Simple values are untouched.
10110 $result[$key] = $value;
10113 return $result;
10117 * Detect a custom script replacement in the data directory that will
10118 * replace an existing moodle script
10120 * @return string|bool full path name if a custom script exists, false if no custom script exists
10122 function custom_script_path() {
10123 global $CFG, $SCRIPT;
10125 if ($SCRIPT === null) {
10126 // Probably some weird external script.
10127 return false;
10130 $scriptpath = $CFG->customscripts . $SCRIPT;
10132 // Check the custom script exists.
10133 if (file_exists($scriptpath) and is_file($scriptpath)) {
10134 return $scriptpath;
10135 } else {
10136 return false;
10141 * Returns whether or not the user object is a remote MNET user. This function
10142 * is in moodlelib because it does not rely on loading any of the MNET code.
10144 * @param object $user A valid user object
10145 * @return bool True if the user is from a remote Moodle.
10147 function is_mnet_remote_user($user) {
10148 global $CFG;
10150 if (!isset($CFG->mnet_localhost_id)) {
10151 include_once($CFG->dirroot . '/mnet/lib.php');
10152 $env = new mnet_environment();
10153 $env->init();
10154 unset($env);
10157 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
10161 * This function will search for browser prefereed languages, setting Moodle
10162 * to use the best one available if $SESSION->lang is undefined
10164 function setup_lang_from_browser() {
10165 global $CFG, $SESSION, $USER;
10167 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
10168 // Lang is defined in session or user profile, nothing to do.
10169 return;
10172 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
10173 return;
10176 // Extract and clean langs from headers.
10177 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
10178 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
10179 $rawlangs = explode(',', $rawlangs); // Convert to array.
10180 $langs = array();
10182 $order = 1.0;
10183 foreach ($rawlangs as $lang) {
10184 if (strpos($lang, ';') === false) {
10185 $langs[(string)$order] = $lang;
10186 $order = $order-0.01;
10187 } else {
10188 $parts = explode(';', $lang);
10189 $pos = strpos($parts[1], '=');
10190 $langs[substr($parts[1], $pos+1)] = $parts[0];
10193 krsort($langs, SORT_NUMERIC);
10195 // Look for such langs under standard locations.
10196 foreach ($langs as $lang) {
10197 // Clean it properly for include.
10198 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
10199 if (get_string_manager()->translation_exists($lang, false)) {
10200 // Lang exists, set it in session.
10201 $SESSION->lang = $lang;
10202 // We have finished. Go out.
10203 break;
10206 return;
10210 * Check if $url matches anything in proxybypass list
10212 * Any errors just result in the proxy being used (least bad)
10214 * @param string $url url to check
10215 * @return boolean true if we should bypass the proxy
10217 function is_proxybypass( $url ) {
10218 global $CFG;
10220 // Sanity check.
10221 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
10222 return false;
10225 // Get the host part out of the url.
10226 if (!$host = parse_url( $url, PHP_URL_HOST )) {
10227 return false;
10230 // Get the possible bypass hosts into an array.
10231 $matches = explode( ',', $CFG->proxybypass );
10233 // Check for a match.
10234 // (IPs need to match the left hand side and hosts the right of the url,
10235 // but we can recklessly check both as there can't be a false +ve).
10236 foreach ($matches as $match) {
10237 $match = trim($match);
10239 // Try for IP match (Left side).
10240 $lhs = substr($host, 0, strlen($match));
10241 if (strcasecmp($match, $lhs)==0) {
10242 return true;
10245 // Try for host match (Right side).
10246 $rhs = substr($host, -strlen($match));
10247 if (strcasecmp($match, $rhs)==0) {
10248 return true;
10252 // Nothing matched.
10253 return false;
10257 * Check if the passed navigation is of the new style
10259 * @param mixed $navigation
10260 * @return bool true for yes false for no
10262 function is_newnav($navigation) {
10263 if (is_array($navigation) && !empty($navigation['newnav'])) {
10264 return true;
10265 } else {
10266 return false;
10271 * Checks whether the given variable name is defined as a variable within the given object.
10273 * This will NOT work with stdClass objects, which have no class variables.
10275 * @param string $var The variable name
10276 * @param object $object The object to check
10277 * @return boolean
10279 function in_object_vars($var, $object) {
10280 $classvars = get_class_vars(get_class($object));
10281 $classvars = array_keys($classvars);
10282 return in_array($var, $classvars);
10286 * Returns an array without repeated objects.
10287 * This function is similar to array_unique, but for arrays that have objects as values
10289 * @param array $array
10290 * @param bool $keepkeyassoc
10291 * @return array
10293 function object_array_unique($array, $keepkeyassoc = true) {
10294 $duplicatekeys = array();
10295 $tmp = array();
10297 foreach ($array as $key => $val) {
10298 // Convert objects to arrays, in_array() does not support objects.
10299 if (is_object($val)) {
10300 $val = (array)$val;
10303 if (!in_array($val, $tmp)) {
10304 $tmp[] = $val;
10305 } else {
10306 $duplicatekeys[] = $key;
10310 foreach ($duplicatekeys as $key) {
10311 unset($array[$key]);
10314 return $keepkeyassoc ? $array : array_values($array);
10318 * Is a userid the primary administrator?
10320 * @param int $userid int id of user to check
10321 * @return boolean
10323 function is_primary_admin($userid) {
10324 $primaryadmin = get_admin();
10326 if ($userid == $primaryadmin->id) {
10327 return true;
10328 } else {
10329 return false;
10334 * Returns the site identifier
10336 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10338 function get_site_identifier() {
10339 global $CFG;
10340 // Check to see if it is missing. If so, initialise it.
10341 if (empty($CFG->siteidentifier)) {
10342 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10344 // Return it.
10345 return $CFG->siteidentifier;
10349 * Check whether the given password has no more than the specified
10350 * number of consecutive identical characters.
10352 * @param string $password password to be checked against the password policy
10353 * @param integer $maxchars maximum number of consecutive identical characters
10354 * @return bool
10356 function check_consecutive_identical_characters($password, $maxchars) {
10358 if ($maxchars < 1) {
10359 return true; // Zero 0 is to disable this check.
10361 if (strlen($password) <= $maxchars) {
10362 return true; // Too short to fail this test.
10365 $previouschar = '';
10366 $consecutivecount = 1;
10367 foreach (str_split($password) as $char) {
10368 if ($char != $previouschar) {
10369 $consecutivecount = 1;
10370 } else {
10371 $consecutivecount++;
10372 if ($consecutivecount > $maxchars) {
10373 return false; // Check failed already.
10377 $previouschar = $char;
10380 return true;
10384 * Helper function to do partial function binding.
10385 * so we can use it for preg_replace_callback, for example
10386 * this works with php functions, user functions, static methods and class methods
10387 * it returns you a callback that you can pass on like so:
10389 * $callback = partial('somefunction', $arg1, $arg2);
10390 * or
10391 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10392 * or even
10393 * $obj = new someclass();
10394 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10396 * and then the arguments that are passed through at calltime are appended to the argument list.
10398 * @param mixed $function a php callback
10399 * @param mixed $arg1,... $argv arguments to partially bind with
10400 * @return array Array callback
10402 function partial() {
10403 if (!class_exists('partial')) {
10405 * Used to manage function binding.
10406 * @copyright 2009 Penny Leach
10407 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10409 class partial{
10410 /** @var array */
10411 public $values = array();
10412 /** @var string The function to call as a callback. */
10413 public $func;
10415 * Constructor
10416 * @param string $func
10417 * @param array $args
10419 public function __construct($func, $args) {
10420 $this->values = $args;
10421 $this->func = $func;
10424 * Calls the callback function.
10425 * @return mixed
10427 public function method() {
10428 $args = func_get_args();
10429 return call_user_func_array($this->func, array_merge($this->values, $args));
10433 $args = func_get_args();
10434 $func = array_shift($args);
10435 $p = new partial($func, $args);
10436 return array($p, 'method');
10440 * helper function to load up and initialise the mnet environment
10441 * this must be called before you use mnet functions.
10443 * @return mnet_environment the equivalent of old $MNET global
10445 function get_mnet_environment() {
10446 global $CFG;
10447 require_once($CFG->dirroot . '/mnet/lib.php');
10448 static $instance = null;
10449 if (empty($instance)) {
10450 $instance = new mnet_environment();
10451 $instance->init();
10453 return $instance;
10457 * during xmlrpc server code execution, any code wishing to access
10458 * information about the remote peer must use this to get it.
10460 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10462 function get_mnet_remote_client() {
10463 if (!defined('MNET_SERVER')) {
10464 debugging(get_string('notinxmlrpcserver', 'mnet'));
10465 return false;
10467 global $MNET_REMOTE_CLIENT;
10468 if (isset($MNET_REMOTE_CLIENT)) {
10469 return $MNET_REMOTE_CLIENT;
10471 return false;
10475 * during the xmlrpc server code execution, this will be called
10476 * to setup the object returned by {@link get_mnet_remote_client}
10478 * @param mnet_remote_client $client the client to set up
10479 * @throws moodle_exception
10481 function set_mnet_remote_client($client) {
10482 if (!defined('MNET_SERVER')) {
10483 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10485 global $MNET_REMOTE_CLIENT;
10486 $MNET_REMOTE_CLIENT = $client;
10490 * return the jump url for a given remote user
10491 * this is used for rewriting forum post links in emails, etc
10493 * @param stdclass $user the user to get the idp url for
10495 function mnet_get_idp_jump_url($user) {
10496 global $CFG;
10498 static $mnetjumps = array();
10499 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10500 $idp = mnet_get_peer_host($user->mnethostid);
10501 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10502 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10504 return $mnetjumps[$user->mnethostid];
10508 * Gets the homepage to use for the current user
10510 * @return int One of HOMEPAGE_*
10512 function get_home_page() {
10513 global $CFG;
10515 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10516 // If dashboard is disabled, home will be set to default page.
10517 $defaultpage = get_default_home_page();
10518 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10519 if (!empty($CFG->enabledashboard)) {
10520 return HOMEPAGE_MY;
10521 } else {
10522 return $defaultpage;
10524 } else if ($CFG->defaulthomepage == HOMEPAGE_MYCOURSES) {
10525 return HOMEPAGE_MYCOURSES;
10526 } else {
10527 $userhomepage = (int) get_user_preferences('user_home_page_preference', $defaultpage);
10528 if (empty($CFG->enabledashboard) && $userhomepage == HOMEPAGE_MY) {
10529 // If the user was using the dashboard but it's disabled, return the default home page.
10530 $userhomepage = $defaultpage;
10532 return $userhomepage;
10535 return HOMEPAGE_SITE;
10539 * Returns the default home page to display if current one is not defined or can't be applied.
10540 * The default behaviour is to return Dashboard if it's enabled or My courses page if it isn't.
10542 * @return int The default home page.
10544 function get_default_home_page(): int {
10545 global $CFG;
10547 return !empty($CFG->enabledashboard) ? HOMEPAGE_MY : HOMEPAGE_MYCOURSES;
10551 * Gets the name of a course to be displayed when showing a list of courses.
10552 * By default this is just $course->fullname but user can configure it. The
10553 * result of this function should be passed through print_string.
10554 * @param stdClass|core_course_list_element $course Moodle course object
10555 * @return string Display name of course (either fullname or short + fullname)
10557 function get_course_display_name_for_list($course) {
10558 global $CFG;
10559 if (!empty($CFG->courselistshortnames)) {
10560 if (!($course instanceof stdClass)) {
10561 $course = (object)convert_to_array($course);
10563 return get_string('courseextendednamedisplay', '', $course);
10564 } else {
10565 return $course->fullname;
10570 * Safe analogue of unserialize() that can only parse arrays
10572 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10573 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10574 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10576 * @param string $expression
10577 * @return array|bool either parsed array or false if parsing was impossible.
10579 function unserialize_array($expression) {
10580 $subs = [];
10581 // Find nested arrays, parse them and store in $subs , substitute with special string.
10582 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10583 $key = '--SUB' . count($subs) . '--';
10584 $subs[$key] = unserialize_array($matches[2]);
10585 if ($subs[$key] === false) {
10586 return false;
10588 $expression = str_replace($matches[2], $key . ';', $expression);
10591 // Check the expression is an array.
10592 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10593 return false;
10595 // Get the size and elements of an array (key;value;key;value;....).
10596 $parts = explode(';', $matches1[2]);
10597 $size = intval($matches1[1]);
10598 if (count($parts) < $size * 2 + 1) {
10599 return false;
10601 // Analyze each part and make sure it is an integer or string or a substitute.
10602 $value = [];
10603 for ($i = 0; $i < $size * 2; $i++) {
10604 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10605 $parts[$i] = (int)$matches2[1];
10606 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10607 $parts[$i] = $matches3[2];
10608 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10609 $parts[$i] = $subs[$parts[$i]];
10610 } else {
10611 return false;
10614 // Combine keys and values.
10615 for ($i = 0; $i < $size * 2; $i += 2) {
10616 $value[$parts[$i]] = $parts[$i+1];
10618 return $value;
10622 * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10624 * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10625 * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10626 * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10628 * @param string $input
10629 * @return stdClass
10631 function unserialize_object(string $input): stdClass {
10632 $instance = (array) unserialize($input, ['allowed_classes' => [stdClass::class]]);
10633 return (object) $instance;
10637 * The lang_string class
10639 * This special class is used to create an object representation of a string request.
10640 * It is special because processing doesn't occur until the object is first used.
10641 * The class was created especially to aid performance in areas where strings were
10642 * required to be generated but were not necessarily used.
10643 * As an example the admin tree when generated uses over 1500 strings, of which
10644 * normally only 1/3 are ever actually printed at any time.
10645 * The performance advantage is achieved by not actually processing strings that
10646 * arn't being used, as such reducing the processing required for the page.
10648 * How to use the lang_string class?
10649 * There are two methods of using the lang_string class, first through the
10650 * forth argument of the get_string function, and secondly directly.
10651 * The following are examples of both.
10652 * 1. Through get_string calls e.g.
10653 * $string = get_string($identifier, $component, $a, true);
10654 * $string = get_string('yes', 'moodle', null, true);
10655 * 2. Direct instantiation
10656 * $string = new lang_string($identifier, $component, $a, $lang);
10657 * $string = new lang_string('yes');
10659 * How do I use a lang_string object?
10660 * The lang_string object makes use of a magic __toString method so that you
10661 * are able to use the object exactly as you would use a string in most cases.
10662 * This means you are able to collect it into a variable and then directly
10663 * echo it, or concatenate it into another string, or similar.
10664 * The other thing you can do is manually get the string by calling the
10665 * lang_strings out method e.g.
10666 * $string = new lang_string('yes');
10667 * $string->out();
10668 * Also worth noting is that the out method can take one argument, $lang which
10669 * allows the developer to change the language on the fly.
10671 * When should I use a lang_string object?
10672 * The lang_string object is designed to be used in any situation where a
10673 * string may not be needed, but needs to be generated.
10674 * The admin tree is a good example of where lang_string objects should be
10675 * used.
10676 * A more practical example would be any class that requries strings that may
10677 * not be printed (after all classes get renderer by renderers and who knows
10678 * what they will do ;))
10680 * When should I not use a lang_string object?
10681 * Don't use lang_strings when you are going to use a string immediately.
10682 * There is no need as it will be processed immediately and there will be no
10683 * advantage, and in fact perhaps a negative hit as a class has to be
10684 * instantiated for a lang_string object, however get_string won't require
10685 * that.
10687 * Limitations:
10688 * 1. You cannot use a lang_string object as an array offset. Doing so will
10689 * result in PHP throwing an error. (You can use it as an object property!)
10691 * @package core
10692 * @category string
10693 * @copyright 2011 Sam Hemelryk
10694 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10696 class lang_string {
10698 /** @var string The strings identifier */
10699 protected $identifier;
10700 /** @var string The strings component. Default '' */
10701 protected $component = '';
10702 /** @var array|stdClass Any arguments required for the string. Default null */
10703 protected $a = null;
10704 /** @var string The language to use when processing the string. Default null */
10705 protected $lang = null;
10707 /** @var string The processed string (once processed) */
10708 protected $string = null;
10711 * A special boolean. If set to true then the object has been woken up and
10712 * cannot be regenerated. If this is set then $this->string MUST be used.
10713 * @var bool
10715 protected $forcedstring = false;
10718 * Constructs a lang_string object
10720 * This function should do as little processing as possible to ensure the best
10721 * performance for strings that won't be used.
10723 * @param string $identifier The strings identifier
10724 * @param string $component The strings component
10725 * @param stdClass|array $a Any arguments the string requires
10726 * @param string $lang The language to use when processing the string.
10727 * @throws coding_exception
10729 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10730 if (empty($component)) {
10731 $component = 'moodle';
10734 $this->identifier = $identifier;
10735 $this->component = $component;
10736 $this->lang = $lang;
10738 // We MUST duplicate $a to ensure that it if it changes by reference those
10739 // changes are not carried across.
10740 // To do this we always ensure $a or its properties/values are strings
10741 // and that any properties/values that arn't convertable are forgotten.
10742 if ($a !== null) {
10743 if (is_scalar($a)) {
10744 $this->a = $a;
10745 } else if ($a instanceof lang_string) {
10746 $this->a = $a->out();
10747 } else if (is_object($a) or is_array($a)) {
10748 $a = (array)$a;
10749 $this->a = array();
10750 foreach ($a as $key => $value) {
10751 // Make sure conversion errors don't get displayed (results in '').
10752 if (is_array($value)) {
10753 $this->a[$key] = '';
10754 } else if (is_object($value)) {
10755 if (method_exists($value, '__toString')) {
10756 $this->a[$key] = $value->__toString();
10757 } else {
10758 $this->a[$key] = '';
10760 } else {
10761 $this->a[$key] = (string)$value;
10767 if (debugging(false, DEBUG_DEVELOPER)) {
10768 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10769 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10771 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10772 throw new coding_exception('Invalid string compontent. Please check your string definition');
10774 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10775 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10781 * Processes the string.
10783 * This function actually processes the string, stores it in the string property
10784 * and then returns it.
10785 * You will notice that this function is VERY similar to the get_string method.
10786 * That is because it is pretty much doing the same thing.
10787 * However as this function is an upgrade it isn't as tolerant to backwards
10788 * compatibility.
10790 * @return string
10791 * @throws coding_exception
10793 protected function get_string() {
10794 global $CFG;
10796 // Check if we need to process the string.
10797 if ($this->string === null) {
10798 // Check the quality of the identifier.
10799 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10800 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);
10803 // Process the string.
10804 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10805 // Debugging feature lets you display string identifier and component.
10806 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10807 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10810 // Return the string.
10811 return $this->string;
10815 * Returns the string
10817 * @param string $lang The langauge to use when processing the string
10818 * @return string
10820 public function out($lang = null) {
10821 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10822 if ($this->forcedstring) {
10823 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10824 return $this->get_string();
10826 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10827 return $translatedstring->out();
10829 return $this->get_string();
10833 * Magic __toString method for printing a string
10835 * @return string
10837 public function __toString() {
10838 return $this->get_string();
10842 * Magic __set_state method used for var_export
10844 * @param array $array
10845 * @return self
10847 public static function __set_state(array $array): self {
10848 $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10849 $tmp->string = $array['string'];
10850 $tmp->forcedstring = $array['forcedstring'];
10851 return $tmp;
10855 * Prepares the lang_string for sleep and stores only the forcedstring and
10856 * string properties... the string cannot be regenerated so we need to ensure
10857 * it is generated for this.
10859 * @return string
10861 public function __sleep() {
10862 $this->get_string();
10863 $this->forcedstring = true;
10864 return array('forcedstring', 'string', 'lang');
10868 * Returns the identifier.
10870 * @return string
10872 public function get_identifier() {
10873 return $this->identifier;
10877 * Returns the component.
10879 * @return string
10881 public function get_component() {
10882 return $this->component;
10887 * Get human readable name describing the given callable.
10889 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10890 * It does not check if the callable actually exists.
10892 * @param callable|string|array $callable
10893 * @return string|bool Human readable name of callable, or false if not a valid callable.
10895 function get_callable_name($callable) {
10897 if (!is_callable($callable, true, $name)) {
10898 return false;
10900 } else {
10901 return $name;
10906 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10907 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10908 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10909 * such as site registration when $CFG->wwwroot is not publicly accessible.
10910 * Good thing is there is no false negative.
10911 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10913 * @return bool
10915 function site_is_public() {
10916 global $CFG;
10918 // Return early if site admin has forced this setting.
10919 if (isset($CFG->site_is_public)) {
10920 return (bool)$CFG->site_is_public;
10923 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10925 if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10926 $ispublic = false;
10927 } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10928 $ispublic = false;
10929 } else if (($address = \core\ip_utils::get_ip_address($host)) && !ip_is_public($address)) {
10930 $ispublic = false;
10931 } else {
10932 $ispublic = true;
10935 return $ispublic;