MDL-72882 core: Use default site lang when user lang no longer available
[moodle.git] / lib / moodlelib.php
blob4cdd10e58ec868498685549d02e489728c17b4e8
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 {
1108 // Relative - let's make sure there are no tricks.
1109 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1110 // Looks ok.
1111 } else {
1112 $param = '';
1116 return $param;
1118 case PARAM_PEM:
1119 $param = trim((string)$param);
1120 // PEM formatted strings may contain letters/numbers and the symbols:
1121 // forward slash: /
1122 // plus sign: +
1123 // equal sign: =
1124 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1125 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1126 list($wholething, $body) = $matches;
1127 unset($wholething, $matches);
1128 $b64 = clean_param($body, PARAM_BASE64);
1129 if (!empty($b64)) {
1130 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1131 } else {
1132 return '';
1135 return '';
1137 case PARAM_BASE64:
1138 if (!empty($param)) {
1139 // PEM formatted strings may contain letters/numbers and the symbols
1140 // forward slash: /
1141 // plus sign: +
1142 // equal sign: =.
1143 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1144 return '';
1146 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1147 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1148 // than (or equal to) 64 characters long.
1149 for ($i=0, $j=count($lines); $i < $j; $i++) {
1150 if ($i + 1 == $j) {
1151 if (64 < strlen($lines[$i])) {
1152 return '';
1154 continue;
1157 if (64 != strlen($lines[$i])) {
1158 return '';
1161 return implode("\n", $lines);
1162 } else {
1163 return '';
1166 case PARAM_TAG:
1167 $param = (string)fix_utf8($param);
1168 // Please note it is not safe to use the tag name directly anywhere,
1169 // it must be processed with s(), urlencode() before embedding anywhere.
1170 // Remove some nasties.
1171 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1172 // Convert many whitespace chars into one.
1173 $param = preg_replace('/\s+/u', ' ', $param);
1174 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1175 return $param;
1177 case PARAM_TAGLIST:
1178 $param = (string)fix_utf8($param);
1179 $tags = explode(',', $param);
1180 $result = array();
1181 foreach ($tags as $tag) {
1182 $res = clean_param($tag, PARAM_TAG);
1183 if ($res !== '') {
1184 $result[] = $res;
1187 if ($result) {
1188 return implode(',', $result);
1189 } else {
1190 return '';
1193 case PARAM_CAPABILITY:
1194 if (get_capability_info($param)) {
1195 return $param;
1196 } else {
1197 return '';
1200 case PARAM_PERMISSION:
1201 $param = (int)$param;
1202 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1203 return $param;
1204 } else {
1205 return CAP_INHERIT;
1208 case PARAM_AUTH:
1209 $param = clean_param($param, PARAM_PLUGIN);
1210 if (empty($param)) {
1211 return '';
1212 } else if (exists_auth_plugin($param)) {
1213 return $param;
1214 } else {
1215 return '';
1218 case PARAM_LANG:
1219 $param = clean_param($param, PARAM_SAFEDIR);
1220 if (get_string_manager()->translation_exists($param)) {
1221 return $param;
1222 } else {
1223 // Specified language is not installed or param malformed.
1224 return '';
1227 case PARAM_THEME:
1228 $param = clean_param($param, PARAM_PLUGIN);
1229 if (empty($param)) {
1230 return '';
1231 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1232 return $param;
1233 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1234 return $param;
1235 } else {
1236 // Specified theme is not installed.
1237 return '';
1240 case PARAM_USERNAME:
1241 $param = (string)fix_utf8($param);
1242 $param = trim($param);
1243 // Convert uppercase to lowercase MDL-16919.
1244 $param = core_text::strtolower($param);
1245 if (empty($CFG->extendedusernamechars)) {
1246 $param = str_replace(" " , "", $param);
1247 // Regular expression, eliminate all chars EXCEPT:
1248 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1249 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1251 return $param;
1253 case PARAM_EMAIL:
1254 $param = fix_utf8($param);
1255 if (validate_email($param ?? '')) {
1256 return $param;
1257 } else {
1258 return '';
1261 case PARAM_STRINGID:
1262 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', (string)$param)) {
1263 return $param;
1264 } else {
1265 return '';
1268 case PARAM_TIMEZONE:
1269 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1270 $param = (string)fix_utf8($param);
1271 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1272 if (preg_match($timezonepattern, $param)) {
1273 return $param;
1274 } else {
1275 return '';
1278 default:
1279 // Doh! throw error, switched parameters in optional_param or another serious problem.
1280 throw new \moodle_exception("unknownparamtype", '', '', $type);
1285 * Whether the PARAM_* type is compatible in RTL.
1287 * Being compatible with RTL means that the data they contain can flow
1288 * from right-to-left or left-to-right without compromising the user experience.
1290 * Take URLs for example, they are not RTL compatible as they should always
1291 * flow from the left to the right. This also applies to numbers, email addresses,
1292 * configuration snippets, base64 strings, etc...
1294 * This function tries to best guess which parameters can contain localised strings.
1296 * @param string $paramtype Constant PARAM_*.
1297 * @return bool
1299 function is_rtl_compatible($paramtype) {
1300 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1304 * Makes sure the data is using valid utf8, invalid characters are discarded.
1306 * Note: this function is not intended for full objects with methods and private properties.
1308 * @param mixed $value
1309 * @return mixed with proper utf-8 encoding
1311 function fix_utf8($value) {
1312 if (is_null($value) or $value === '') {
1313 return $value;
1315 } else if (is_string($value)) {
1316 if ((string)(int)$value === $value) {
1317 // Shortcut.
1318 return $value;
1320 // No null bytes expected in our data, so let's remove it.
1321 $value = str_replace("\0", '', $value);
1323 // Note: this duplicates min_fix_utf8() intentionally.
1324 static $buggyiconv = null;
1325 if ($buggyiconv === null) {
1326 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1329 if ($buggyiconv) {
1330 if (function_exists('mb_convert_encoding')) {
1331 $subst = mb_substitute_character();
1332 mb_substitute_character('none');
1333 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1334 mb_substitute_character($subst);
1336 } else {
1337 // Warn admins on admin/index.php page.
1338 $result = $value;
1341 } else {
1342 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1345 return $result;
1347 } else if (is_array($value)) {
1348 foreach ($value as $k => $v) {
1349 $value[$k] = fix_utf8($v);
1351 return $value;
1353 } else if (is_object($value)) {
1354 // Do not modify original.
1355 $value = clone($value);
1356 foreach ($value as $k => $v) {
1357 $value->$k = fix_utf8($v);
1359 return $value;
1361 } else {
1362 // This is some other type, no utf-8 here.
1363 return $value;
1368 * Return true if given value is integer or string with integer value
1370 * @param mixed $value String or Int
1371 * @return bool true if number, false if not
1373 function is_number($value) {
1374 if (is_int($value)) {
1375 return true;
1376 } else if (is_string($value)) {
1377 return ((string)(int)$value) === $value;
1378 } else {
1379 return false;
1384 * Returns host part from url.
1386 * @param string $url full url
1387 * @return string host, null if not found
1389 function get_host_from_url($url) {
1390 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1391 if ($matches) {
1392 return $matches[1];
1394 return null;
1398 * Tests whether anything was returned by text editor
1400 * This function is useful for testing whether something you got back from
1401 * the HTML editor actually contains anything. Sometimes the HTML editor
1402 * appear to be empty, but actually you get back a <br> tag or something.
1404 * @param string $string a string containing HTML.
1405 * @return boolean does the string contain any actual content - that is text,
1406 * images, objects, etc.
1408 function html_is_blank($string) {
1409 return trim(strip_tags((string)$string, '<img><object><applet><input><select><textarea><hr>')) == '';
1413 * Set a key in global configuration
1415 * Set a key/value pair in both this session's {@link $CFG} global variable
1416 * and in the 'config' database table for future sessions.
1418 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1419 * In that case it doesn't affect $CFG.
1421 * A NULL value will delete the entry.
1423 * NOTE: this function is called from lib/db/upgrade.php
1425 * @param string $name the key to set
1426 * @param string $value the value to set (without magic quotes)
1427 * @param string $plugin (optional) the plugin scope, default null
1428 * @return bool true or exception
1430 function set_config($name, $value, $plugin = null) {
1431 global $CFG, $DB;
1433 // Redirect to appropriate handler when value is null.
1434 if ($value === null) {
1435 return unset_config($name, $plugin);
1438 // Set variables determining conditions and where to store the new config.
1439 // Plugin config goes to {config_plugins}, core config goes to {config}.
1440 $iscore = empty($plugin);
1441 if ($iscore) {
1442 // If it's for core config.
1443 $table = 'config';
1444 $conditions = ['name' => $name];
1445 $invalidatecachekey = 'core';
1446 } else {
1447 // If it's a plugin.
1448 $table = 'config_plugins';
1449 $conditions = ['name' => $name, 'plugin' => $plugin];
1450 $invalidatecachekey = $plugin;
1453 // DB handling - checks for existing config, updating or inserting only if necessary.
1454 $invalidatecache = true;
1455 $inserted = false;
1456 $record = $DB->get_record($table, $conditions, 'id, value');
1457 if ($record === false) {
1458 // Inserts a new config record.
1459 $config = new stdClass();
1460 $config->name = $name;
1461 $config->value = $value;
1462 if (!$iscore) {
1463 $config->plugin = $plugin;
1465 $inserted = $DB->insert_record($table, $config, false);
1466 } else if ($invalidatecache = ($record->value !== $value)) {
1467 // Record exists - Check and only set new value if it has changed.
1468 $DB->set_field($table, 'value', $value, ['id' => $record->id]);
1471 if ($iscore && !isset($CFG->config_php_settings[$name])) {
1472 // So it's defined for this invocation at least.
1473 // Settings from db are always strings.
1474 $CFG->$name = (string) $value;
1477 // When setting config during a Behat test (in the CLI script, not in the web browser
1478 // requests), remember which ones are set so that we can clear them later.
1479 if ($iscore && $inserted && defined('BEHAT_TEST')) {
1480 $CFG->behat_cli_added_config[$name] = true;
1483 // Update siteidentifier cache, if required.
1484 if ($iscore && $name === 'siteidentifier') {
1485 cache_helper::update_site_identifier($value);
1488 // Invalidate cache, if required.
1489 if ($invalidatecache) {
1490 cache_helper::invalidate_by_definition('core', 'config', [], $invalidatecachekey);
1493 return true;
1497 * Get configuration values from the global config table
1498 * or the config_plugins table.
1500 * If called with one parameter, it will load all the config
1501 * variables for one plugin, and return them as an object.
1503 * If called with 2 parameters it will return a string single
1504 * value or false if the value is not found.
1506 * NOTE: this function is called from lib/db/upgrade.php
1508 * @param string $plugin full component name
1509 * @param string $name default null
1510 * @return mixed hash-like object or single value, return false no config found
1511 * @throws dml_exception
1513 function get_config($plugin, $name = null) {
1514 global $CFG, $DB;
1516 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1517 $forced =& $CFG->config_php_settings;
1518 $iscore = true;
1519 $plugin = 'core';
1520 } else {
1521 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1522 $forced =& $CFG->forced_plugin_settings[$plugin];
1523 } else {
1524 $forced = array();
1526 $iscore = false;
1529 if (!isset($CFG->siteidentifier)) {
1530 try {
1531 // This may throw an exception during installation, which is how we detect the
1532 // need to install the database. For more details see {@see initialise_cfg()}.
1533 $CFG->siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1534 } catch (dml_exception $ex) {
1535 // Set siteidentifier to false. We don't want to trip this continually.
1536 $siteidentifier = false;
1537 throw $ex;
1541 if (!empty($name)) {
1542 if (array_key_exists($name, $forced)) {
1543 return (string)$forced[$name];
1544 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1545 return $CFG->siteidentifier;
1549 $cache = cache::make('core', 'config');
1550 $result = $cache->get($plugin);
1551 if ($result === false) {
1552 // The user is after a recordset.
1553 if (!$iscore) {
1554 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1555 } else {
1556 // This part is not really used any more, but anyway...
1557 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1559 $cache->set($plugin, $result);
1562 if (!empty($name)) {
1563 if (array_key_exists($name, $result)) {
1564 return $result[$name];
1566 return false;
1569 if ($plugin === 'core') {
1570 $result['siteidentifier'] = $CFG->siteidentifier;
1573 foreach ($forced as $key => $value) {
1574 if (is_null($value) or is_array($value) or is_object($value)) {
1575 // We do not want any extra mess here, just real settings that could be saved in db.
1576 unset($result[$key]);
1577 } else {
1578 // Convert to string as if it went through the DB.
1579 $result[$key] = (string)$value;
1583 return (object)$result;
1587 * Removes a key from global configuration.
1589 * NOTE: this function is called from lib/db/upgrade.php
1591 * @param string $name the key to set
1592 * @param string $plugin (optional) the plugin scope
1593 * @return boolean whether the operation succeeded.
1595 function unset_config($name, $plugin=null) {
1596 global $CFG, $DB;
1598 if (empty($plugin)) {
1599 unset($CFG->$name);
1600 $DB->delete_records('config', array('name' => $name));
1601 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1602 } else {
1603 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1604 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1607 return true;
1611 * Remove all the config variables for a given plugin.
1613 * NOTE: this function is called from lib/db/upgrade.php
1615 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1616 * @return boolean whether the operation succeeded.
1618 function unset_all_config_for_plugin($plugin) {
1619 global $DB;
1620 // Delete from the obvious config_plugins first.
1621 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1622 // Next delete any suspect settings from config.
1623 $like = $DB->sql_like('name', '?', true, true, false, '|');
1624 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1625 $DB->delete_records_select('config', $like, $params);
1626 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1627 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1629 return true;
1633 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1635 * All users are verified if they still have the necessary capability.
1637 * @param string $value the value of the config setting.
1638 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1639 * @param bool $includeadmins include administrators.
1640 * @return array of user objects.
1642 function get_users_from_config($value, $capability, $includeadmins = true) {
1643 if (empty($value) or $value === '$@NONE@$') {
1644 return array();
1647 // We have to make sure that users still have the necessary capability,
1648 // it should be faster to fetch them all first and then test if they are present
1649 // instead of validating them one-by-one.
1650 $users = get_users_by_capability(context_system::instance(), $capability);
1651 if ($includeadmins) {
1652 $admins = get_admins();
1653 foreach ($admins as $admin) {
1654 $users[$admin->id] = $admin;
1658 if ($value === '$@ALL@$') {
1659 return $users;
1662 $result = array(); // Result in correct order.
1663 $allowed = explode(',', $value);
1664 foreach ($allowed as $uid) {
1665 if (isset($users[$uid])) {
1666 $user = $users[$uid];
1667 $result[$user->id] = $user;
1671 return $result;
1676 * Invalidates browser caches and cached data in temp.
1678 * @return void
1680 function purge_all_caches() {
1681 purge_caches();
1685 * Selectively invalidate different types of cache.
1687 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1688 * areas alone or in combination.
1690 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1691 * 'muc' Purge MUC caches?
1692 * 'theme' Purge theme cache?
1693 * 'lang' Purge language string cache?
1694 * 'js' Purge javascript cache?
1695 * 'filter' Purge text filter cache?
1696 * 'other' Purge all other caches?
1698 function purge_caches($options = []) {
1699 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1700 if (empty(array_filter($options))) {
1701 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1702 } else {
1703 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1705 if ($options['muc']) {
1706 cache_helper::purge_all();
1708 if ($options['theme']) {
1709 theme_reset_all_caches();
1711 if ($options['lang']) {
1712 get_string_manager()->reset_caches();
1714 if ($options['js']) {
1715 js_reset_all_caches();
1717 if ($options['template']) {
1718 template_reset_all_caches();
1720 if ($options['filter']) {
1721 reset_text_filters_cache();
1723 if ($options['other']) {
1724 purge_other_caches();
1729 * Purge all non-MUC caches not otherwise purged in purge_caches.
1731 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1732 * {@link phpunit_util::reset_dataroot()}
1734 function purge_other_caches() {
1735 global $DB, $CFG;
1736 if (class_exists('core_plugin_manager')) {
1737 core_plugin_manager::reset_caches();
1740 // Bump up cacherev field for all courses.
1741 try {
1742 increment_revision_number('course', 'cacherev', '');
1743 } catch (moodle_exception $e) {
1744 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1747 $DB->reset_caches();
1749 // Purge all other caches: rss, simplepie, etc.
1750 clearstatcache();
1751 remove_dir($CFG->cachedir.'', true);
1753 // Make sure cache dir is writable, throws exception if not.
1754 make_cache_directory('');
1756 // This is the only place where we purge local caches, we are only adding files there.
1757 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1758 remove_dir($CFG->localcachedir, true);
1759 set_config('localcachedirpurged', time());
1760 make_localcache_directory('', true);
1761 \core\task\manager::clear_static_caches();
1765 * Get volatile flags
1767 * @param string $type
1768 * @param int $changedsince default null
1769 * @return array records array
1771 function get_cache_flags($type, $changedsince = null) {
1772 global $DB;
1774 $params = array('type' => $type, 'expiry' => time());
1775 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1776 if ($changedsince !== null) {
1777 $params['changedsince'] = $changedsince;
1778 $sqlwhere .= " AND timemodified > :changedsince";
1780 $cf = array();
1781 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1782 foreach ($flags as $flag) {
1783 $cf[$flag->name] = $flag->value;
1786 return $cf;
1790 * Get volatile flags
1792 * @param string $type
1793 * @param string $name
1794 * @param int $changedsince default null
1795 * @return string|false The cache flag value or false
1797 function get_cache_flag($type, $name, $changedsince=null) {
1798 global $DB;
1800 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1802 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1803 if ($changedsince !== null) {
1804 $params['changedsince'] = $changedsince;
1805 $sqlwhere .= " AND timemodified > :changedsince";
1808 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1812 * Set a volatile flag
1814 * @param string $type the "type" namespace for the key
1815 * @param string $name the key to set
1816 * @param string $value the value to set (without magic quotes) - null will remove the flag
1817 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1818 * @return bool Always returns true
1820 function set_cache_flag($type, $name, $value, $expiry = null) {
1821 global $DB;
1823 $timemodified = time();
1824 if ($expiry === null || $expiry < $timemodified) {
1825 $expiry = $timemodified + 24 * 60 * 60;
1826 } else {
1827 $expiry = (int)$expiry;
1830 if ($value === null) {
1831 unset_cache_flag($type, $name);
1832 return true;
1835 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1836 // This is a potential problem in DEBUG_DEVELOPER.
1837 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1838 return true; // No need to update.
1840 $f->value = $value;
1841 $f->expiry = $expiry;
1842 $f->timemodified = $timemodified;
1843 $DB->update_record('cache_flags', $f);
1844 } else {
1845 $f = new stdClass();
1846 $f->flagtype = $type;
1847 $f->name = $name;
1848 $f->value = $value;
1849 $f->expiry = $expiry;
1850 $f->timemodified = $timemodified;
1851 $DB->insert_record('cache_flags', $f);
1853 return true;
1857 * Removes a single volatile flag
1859 * @param string $type the "type" namespace for the key
1860 * @param string $name the key to set
1861 * @return bool
1863 function unset_cache_flag($type, $name) {
1864 global $DB;
1865 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1866 return true;
1870 * Garbage-collect volatile flags
1872 * @return bool Always returns true
1874 function gc_cache_flags() {
1875 global $DB;
1876 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1877 return true;
1880 // USER PREFERENCE API.
1883 * Refresh user preference cache. This is used most often for $USER
1884 * object that is stored in session, but it also helps with performance in cron script.
1886 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1888 * @package core
1889 * @category preference
1890 * @access public
1891 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1892 * @param int $cachelifetime Cache life time on the current page (in seconds)
1893 * @throws coding_exception
1894 * @return null
1896 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1897 global $DB;
1898 // Static cache, we need to check on each page load, not only every 2 minutes.
1899 static $loadedusers = array();
1901 if (!isset($user->id)) {
1902 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1905 if (empty($user->id) or isguestuser($user->id)) {
1906 // No permanent storage for not-logged-in users and guest.
1907 if (!isset($user->preference)) {
1908 $user->preference = array();
1910 return;
1913 $timenow = time();
1915 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1916 // Already loaded at least once on this page. Are we up to date?
1917 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1918 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1919 return;
1921 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1922 // No change since the lastcheck on this page.
1923 $user->preference['_lastloaded'] = $timenow;
1924 return;
1928 // OK, so we have to reload all preferences.
1929 $loadedusers[$user->id] = true;
1930 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1931 $user->preference['_lastloaded'] = $timenow;
1935 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1937 * NOTE: internal function, do not call from other code.
1939 * @package core
1940 * @access private
1941 * @param integer $userid the user whose prefs were changed.
1943 function mark_user_preferences_changed($userid) {
1944 global $CFG;
1946 if (empty($userid) or isguestuser($userid)) {
1947 // No cache flags for guest and not-logged-in users.
1948 return;
1951 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1955 * Sets a preference for the specified user.
1957 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1959 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1961 * @package core
1962 * @category preference
1963 * @access public
1964 * @param string $name The key to set as preference for the specified user
1965 * @param string $value The value to set for the $name key in the specified user's
1966 * record, null means delete current value.
1967 * @param stdClass|int|null $user A moodle user object or id, null means current user
1968 * @throws coding_exception
1969 * @return bool Always true or exception
1971 function set_user_preference($name, $value, $user = null) {
1972 global $USER, $DB;
1974 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1975 throw new coding_exception('Invalid preference name in set_user_preference() call');
1978 if (is_null($value)) {
1979 // Null means delete current.
1980 return unset_user_preference($name, $user);
1981 } else if (is_object($value)) {
1982 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1983 } else if (is_array($value)) {
1984 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1986 // Value column maximum length is 1333 characters.
1987 $value = (string)$value;
1988 if (core_text::strlen($value) > 1333) {
1989 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1992 if (is_null($user)) {
1993 $user = $USER;
1994 } else if (isset($user->id)) {
1995 // It is a valid object.
1996 } else if (is_numeric($user)) {
1997 $user = (object)array('id' => (int)$user);
1998 } else {
1999 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
2002 check_user_preferences_loaded($user);
2004 if (empty($user->id) or isguestuser($user->id)) {
2005 // No permanent storage for not-logged-in users and guest.
2006 $user->preference[$name] = $value;
2007 return true;
2010 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
2011 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
2012 // Preference already set to this value.
2013 return true;
2015 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
2017 } else {
2018 $preference = new stdClass();
2019 $preference->userid = $user->id;
2020 $preference->name = $name;
2021 $preference->value = $value;
2022 $DB->insert_record('user_preferences', $preference);
2025 // Update value in cache.
2026 $user->preference[$name] = $value;
2027 // Update the $USER in case where we've not a direct reference to $USER.
2028 if ($user !== $USER && $user->id == $USER->id) {
2029 $USER->preference[$name] = $value;
2032 // Set reload flag for other sessions.
2033 mark_user_preferences_changed($user->id);
2035 return true;
2039 * Sets a whole array of preferences for the current user
2041 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2043 * @package core
2044 * @category preference
2045 * @access public
2046 * @param array $prefarray An array of key/value pairs to be set
2047 * @param stdClass|int|null $user A moodle user object or id, null means current user
2048 * @return bool Always true or exception
2050 function set_user_preferences(array $prefarray, $user = null) {
2051 foreach ($prefarray as $name => $value) {
2052 set_user_preference($name, $value, $user);
2054 return true;
2058 * Unsets a preference completely by deleting it from the database
2060 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2062 * @package core
2063 * @category preference
2064 * @access public
2065 * @param string $name The key to unset as preference for the specified user
2066 * @param stdClass|int|null $user A moodle user object or id, null means current user
2067 * @throws coding_exception
2068 * @return bool Always true or exception
2070 function unset_user_preference($name, $user = null) {
2071 global $USER, $DB;
2073 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2074 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2077 if (is_null($user)) {
2078 $user = $USER;
2079 } else if (isset($user->id)) {
2080 // It is a valid object.
2081 } else if (is_numeric($user)) {
2082 $user = (object)array('id' => (int)$user);
2083 } else {
2084 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2087 check_user_preferences_loaded($user);
2089 if (empty($user->id) or isguestuser($user->id)) {
2090 // No permanent storage for not-logged-in user and guest.
2091 unset($user->preference[$name]);
2092 return true;
2095 // Delete from DB.
2096 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2098 // Delete the preference from cache.
2099 unset($user->preference[$name]);
2100 // Update the $USER in case where we've not a direct reference to $USER.
2101 if ($user !== $USER && $user->id == $USER->id) {
2102 unset($USER->preference[$name]);
2105 // Set reload flag for other sessions.
2106 mark_user_preferences_changed($user->id);
2108 return true;
2112 * Used to fetch user preference(s)
2114 * If no arguments are supplied this function will return
2115 * all of the current user preferences as an array.
2117 * If a name is specified then this function
2118 * attempts to return that particular preference value. If
2119 * none is found, then the optional value $default is returned,
2120 * otherwise null.
2122 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2124 * @package core
2125 * @category preference
2126 * @access public
2127 * @param string $name Name of the key to use in finding a preference value
2128 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2129 * @param stdClass|int|null $user A moodle user object or id, null means current user
2130 * @throws coding_exception
2131 * @return string|mixed|null A string containing the value of a single preference. An
2132 * array with all of the preferences or null
2134 function get_user_preferences($name = null, $default = null, $user = null) {
2135 global $USER;
2137 if (is_null($name)) {
2138 // All prefs.
2139 } else if (is_numeric($name) or $name === '_lastloaded') {
2140 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2143 if (is_null($user)) {
2144 $user = $USER;
2145 } else if (isset($user->id)) {
2146 // Is a valid object.
2147 } else if (is_numeric($user)) {
2148 if ($USER->id == $user) {
2149 $user = $USER;
2150 } else {
2151 $user = (object)array('id' => (int)$user);
2153 } else {
2154 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2157 check_user_preferences_loaded($user);
2159 if (empty($name)) {
2160 // All values.
2161 return $user->preference;
2162 } else if (isset($user->preference[$name])) {
2163 // The single string value.
2164 return $user->preference[$name];
2165 } else {
2166 // Default value (null if not specified).
2167 return $default;
2171 // FUNCTIONS FOR HANDLING TIME.
2174 * Given Gregorian date parts in user time produce a GMT timestamp.
2176 * @package core
2177 * @category time
2178 * @param int $year The year part to create timestamp of
2179 * @param int $month The month part to create timestamp of
2180 * @param int $day The day part to create timestamp of
2181 * @param int $hour The hour part to create timestamp of
2182 * @param int $minute The minute part to create timestamp of
2183 * @param int $second The second part to create timestamp of
2184 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2185 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2186 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2187 * applied only if timezone is 99 or string.
2188 * @return int GMT timestamp
2190 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2191 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2192 $date->setDate((int)$year, (int)$month, (int)$day);
2193 $date->setTime((int)$hour, (int)$minute, (int)$second);
2195 $time = $date->getTimestamp();
2197 if ($time === false) {
2198 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2199 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2202 // Moodle BC DST stuff.
2203 if (!$applydst) {
2204 $time += dst_offset_on($time, $timezone);
2207 return $time;
2212 * Format a date/time (seconds) as weeks, days, hours etc as needed
2214 * Given an amount of time in seconds, returns string
2215 * formatted nicely as years, days, hours etc as needed
2217 * @package core
2218 * @category time
2219 * @uses MINSECS
2220 * @uses HOURSECS
2221 * @uses DAYSECS
2222 * @uses YEARSECS
2223 * @param int $totalsecs Time in seconds
2224 * @param stdClass $str Should be a time object
2225 * @return string A nicely formatted date/time string
2227 function format_time($totalsecs, $str = null) {
2229 $totalsecs = abs($totalsecs);
2231 if (!$str) {
2232 // Create the str structure the slow way.
2233 $str = new stdClass();
2234 $str->day = get_string('day');
2235 $str->days = get_string('days');
2236 $str->hour = get_string('hour');
2237 $str->hours = get_string('hours');
2238 $str->min = get_string('min');
2239 $str->mins = get_string('mins');
2240 $str->sec = get_string('sec');
2241 $str->secs = get_string('secs');
2242 $str->year = get_string('year');
2243 $str->years = get_string('years');
2246 $years = floor($totalsecs/YEARSECS);
2247 $remainder = $totalsecs - ($years*YEARSECS);
2248 $days = floor($remainder/DAYSECS);
2249 $remainder = $totalsecs - ($days*DAYSECS);
2250 $hours = floor($remainder/HOURSECS);
2251 $remainder = $remainder - ($hours*HOURSECS);
2252 $mins = floor($remainder/MINSECS);
2253 $secs = $remainder - ($mins*MINSECS);
2255 $ss = ($secs == 1) ? $str->sec : $str->secs;
2256 $sm = ($mins == 1) ? $str->min : $str->mins;
2257 $sh = ($hours == 1) ? $str->hour : $str->hours;
2258 $sd = ($days == 1) ? $str->day : $str->days;
2259 $sy = ($years == 1) ? $str->year : $str->years;
2261 $oyears = '';
2262 $odays = '';
2263 $ohours = '';
2264 $omins = '';
2265 $osecs = '';
2267 if ($years) {
2268 $oyears = $years .' '. $sy;
2270 if ($days) {
2271 $odays = $days .' '. $sd;
2273 if ($hours) {
2274 $ohours = $hours .' '. $sh;
2276 if ($mins) {
2277 $omins = $mins .' '. $sm;
2279 if ($secs) {
2280 $osecs = $secs .' '. $ss;
2283 if ($years) {
2284 return trim($oyears .' '. $odays);
2286 if ($days) {
2287 return trim($odays .' '. $ohours);
2289 if ($hours) {
2290 return trim($ohours .' '. $omins);
2292 if ($mins) {
2293 return trim($omins .' '. $osecs);
2295 if ($secs) {
2296 return $osecs;
2298 return get_string('now');
2302 * Returns a formatted string that represents a date in user time.
2304 * @package core
2305 * @category time
2306 * @param int $date the timestamp in UTC, as obtained from the database.
2307 * @param string $format strftime format. You should probably get this using
2308 * get_string('strftime...', 'langconfig');
2309 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2310 * not 99 then daylight saving will not be added.
2311 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2312 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2313 * If false then the leading zero is maintained.
2314 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2315 * @return string the formatted date/time.
2317 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2318 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2319 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2323 * Returns a html "time" tag with both the exact user date with timezone information
2324 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2326 * @package core
2327 * @category time
2328 * @param int $date the timestamp in UTC, as obtained from the database.
2329 * @param string $format strftime format. You should probably get this using
2330 * get_string('strftime...', 'langconfig');
2331 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2332 * not 99 then daylight saving will not be added.
2333 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2334 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2335 * If false then the leading zero is maintained.
2336 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2337 * @return string the formatted date/time.
2339 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2340 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2341 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2342 return $userdatestr;
2344 $machinedate = new DateTime();
2345 $machinedate->setTimestamp(intval($date));
2346 $machinedate->setTimezone(core_date::get_user_timezone_object());
2348 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2352 * Returns a formatted date ensuring it is UTF-8.
2354 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2355 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2357 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2358 * @param string $format strftime format.
2359 * @param int|float|string $tz the user timezone
2360 * @return string the formatted date/time.
2361 * @since Moodle 2.3.3
2363 function date_format_string($date, $format, $tz = 99) {
2364 global $CFG;
2366 $localewincharset = null;
2367 // Get the calendar type user is using.
2368 if ($CFG->ostype == 'WINDOWS') {
2369 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2370 $localewincharset = $calendartype->locale_win_charset();
2373 if ($localewincharset) {
2374 $format = core_text::convert($format, 'utf-8', $localewincharset);
2377 date_default_timezone_set(core_date::get_user_timezone($tz));
2379 if (strftime('%p', 0) === strftime('%p', HOURSECS * 18)) {
2380 $datearray = getdate($date);
2381 $format = str_replace([
2382 '%P',
2383 '%p',
2384 ], [
2385 $datearray['hours'] < 12 ? get_string('am', 'langconfig') : get_string('pm', 'langconfig'),
2386 $datearray['hours'] < 12 ? get_string('amcaps', 'langconfig') : get_string('pmcaps', 'langconfig'),
2387 ], $format);
2390 $datestring = strftime($format, $date);
2391 core_date::set_default_server_timezone();
2393 if ($localewincharset) {
2394 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2397 return $datestring;
2401 * Given a $time timestamp in GMT (seconds since epoch),
2402 * returns an array that represents the Gregorian date in user time
2404 * @package core
2405 * @category time
2406 * @param int $time Timestamp in GMT
2407 * @param float|int|string $timezone user timezone
2408 * @return array An array that represents the date in user time
2410 function usergetdate($time, $timezone=99) {
2411 if ($time === null) {
2412 // PHP8 and PHP7 return different results when getdate(null) is called.
2413 // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
2414 // In the future versions of Moodle we may consider adding a strict typehint.
2415 debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER);
2416 $time = 0;
2419 date_default_timezone_set(core_date::get_user_timezone($timezone));
2420 $result = getdate($time);
2421 core_date::set_default_server_timezone();
2423 return $result;
2427 * Given a GMT timestamp (seconds since epoch), offsets it by
2428 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2430 * NOTE: this function does not include DST properly,
2431 * you should use the PHP date stuff instead!
2433 * @package core
2434 * @category time
2435 * @param int $date Timestamp in GMT
2436 * @param float|int|string $timezone user timezone
2437 * @return int
2439 function usertime($date, $timezone=99) {
2440 $userdate = new DateTime('@' . $date);
2441 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2442 $dst = dst_offset_on($date, $timezone);
2444 return $date - $userdate->getOffset() + $dst;
2448 * Get a formatted string representation of an interval between two unix timestamps.
2450 * E.g.
2451 * $intervalstring = get_time_interval_string(12345600, 12345660);
2452 * Will produce the string:
2453 * '0d 0h 1m'
2455 * @param int $time1 unix timestamp
2456 * @param int $time2 unix timestamp
2457 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2458 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2460 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2461 $dtdate = new DateTime();
2462 $dtdate->setTimeStamp($time1);
2463 $dtdate2 = new DateTime();
2464 $dtdate2->setTimeStamp($time2);
2465 $interval = $dtdate2->diff($dtdate);
2466 $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2467 return $interval->format($format);
2471 * Given a time, return the GMT timestamp of the most recent midnight
2472 * for the current user.
2474 * @package core
2475 * @category time
2476 * @param int $date Timestamp in GMT
2477 * @param float|int|string $timezone user timezone
2478 * @return int Returns a GMT timestamp
2480 function usergetmidnight($date, $timezone=99) {
2482 $userdate = usergetdate($date, $timezone);
2484 // Time of midnight of this user's day, in GMT.
2485 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2490 * Returns a string that prints the user's timezone
2492 * @package core
2493 * @category time
2494 * @param float|int|string $timezone user timezone
2495 * @return string
2497 function usertimezone($timezone=99) {
2498 $tz = core_date::get_user_timezone($timezone);
2499 return core_date::get_localised_timezone($tz);
2503 * Returns a float or a string which denotes the user's timezone
2504 * 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)
2505 * means that for this timezone there are also DST rules to be taken into account
2506 * Checks various settings and picks the most dominant of those which have a value
2508 * @package core
2509 * @category time
2510 * @param float|int|string $tz timezone to calculate GMT time offset before
2511 * calculating user timezone, 99 is default user timezone
2512 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2513 * @return float|string
2515 function get_user_timezone($tz = 99) {
2516 global $USER, $CFG;
2518 $timezones = array(
2519 $tz,
2520 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2521 isset($USER->timezone) ? $USER->timezone : 99,
2522 isset($CFG->timezone) ? $CFG->timezone : 99,
2525 $tz = 99;
2527 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2528 foreach ($timezones as $nextvalue) {
2529 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2530 $tz = $nextvalue;
2533 return is_numeric($tz) ? (float) $tz : $tz;
2537 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2538 * - Note: Daylight saving only works for string timezones and not for float.
2540 * @package core
2541 * @category time
2542 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2543 * @param int|float|string $strtimezone user timezone
2544 * @return int
2546 function dst_offset_on($time, $strtimezone = null) {
2547 $tz = core_date::get_user_timezone($strtimezone);
2548 $date = new DateTime('@' . $time);
2549 $date->setTimezone(new DateTimeZone($tz));
2550 if ($date->format('I') == '1') {
2551 if ($tz === 'Australia/Lord_Howe') {
2552 return 1800;
2554 return 3600;
2556 return 0;
2560 * Calculates when the day appears in specific month
2562 * @package core
2563 * @category time
2564 * @param int $startday starting day of the month
2565 * @param int $weekday The day when week starts (normally taken from user preferences)
2566 * @param int $month The month whose day is sought
2567 * @param int $year The year of the month whose day is sought
2568 * @return int
2570 function find_day_in_month($startday, $weekday, $month, $year) {
2571 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2573 $daysinmonth = days_in_month($month, $year);
2574 $daysinweek = count($calendartype->get_weekdays());
2576 if ($weekday == -1) {
2577 // Don't care about weekday, so return:
2578 // abs($startday) if $startday != -1
2579 // $daysinmonth otherwise.
2580 return ($startday == -1) ? $daysinmonth : abs($startday);
2583 // From now on we 're looking for a specific weekday.
2584 // Give "end of month" its actual value, since we know it.
2585 if ($startday == -1) {
2586 $startday = -1 * $daysinmonth;
2589 // Starting from day $startday, the sign is the direction.
2590 if ($startday < 1) {
2591 $startday = abs($startday);
2592 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2594 // This is the last such weekday of the month.
2595 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2596 if ($lastinmonth > $daysinmonth) {
2597 $lastinmonth -= $daysinweek;
2600 // Find the first such weekday <= $startday.
2601 while ($lastinmonth > $startday) {
2602 $lastinmonth -= $daysinweek;
2605 return $lastinmonth;
2606 } else {
2607 $indexweekday = dayofweek($startday, $month, $year);
2609 $diff = $weekday - $indexweekday;
2610 if ($diff < 0) {
2611 $diff += $daysinweek;
2614 // This is the first such weekday of the month equal to or after $startday.
2615 $firstfromindex = $startday + $diff;
2617 return $firstfromindex;
2622 * Calculate the number of days in a given month
2624 * @package core
2625 * @category time
2626 * @param int $month The month whose day count is sought
2627 * @param int $year The year of the month whose day count is sought
2628 * @return int
2630 function days_in_month($month, $year) {
2631 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2632 return $calendartype->get_num_days_in_month($year, $month);
2636 * Calculate the position in the week of a specific calendar day
2638 * @package core
2639 * @category time
2640 * @param int $day The day of the date whose position in the week is sought
2641 * @param int $month The month of the date whose position in the week is sought
2642 * @param int $year The year of the date whose position in the week is sought
2643 * @return int
2645 function dayofweek($day, $month, $year) {
2646 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2647 return $calendartype->get_weekday($year, $month, $day);
2650 // USER AUTHENTICATION AND LOGIN.
2653 * Returns full login url.
2655 * Any form submissions for authentication to this URL must include username,
2656 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2658 * @return string login url
2660 function get_login_url() {
2661 global $CFG;
2663 return "$CFG->wwwroot/login/index.php";
2667 * This function checks that the current user is logged in and has the
2668 * required privileges
2670 * This function checks that the current user is logged in, and optionally
2671 * whether they are allowed to be in a particular course and view a particular
2672 * course module.
2673 * If they are not logged in, then it redirects them to the site login unless
2674 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2675 * case they are automatically logged in as guests.
2676 * If $courseid is given and the user is not enrolled in that course then the
2677 * user is redirected to the course enrolment page.
2678 * If $cm is given and the course module is hidden and the user is not a teacher
2679 * in the course then the user is redirected to the course home page.
2681 * When $cm parameter specified, this function sets page layout to 'module'.
2682 * You need to change it manually later if some other layout needed.
2684 * @package core_access
2685 * @category access
2687 * @param mixed $courseorid id of the course or course object
2688 * @param bool $autologinguest default true
2689 * @param object $cm course module object
2690 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2691 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2692 * in order to keep redirects working properly. MDL-14495
2693 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2694 * @return mixed Void, exit, and die depending on path
2695 * @throws coding_exception
2696 * @throws require_login_exception
2697 * @throws moodle_exception
2699 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2700 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2702 // Must not redirect when byteserving already started.
2703 if (!empty($_SERVER['HTTP_RANGE'])) {
2704 $preventredirect = true;
2707 if (AJAX_SCRIPT) {
2708 // We cannot redirect for AJAX scripts either.
2709 $preventredirect = true;
2712 // Setup global $COURSE, themes, language and locale.
2713 if (!empty($courseorid)) {
2714 if (is_object($courseorid)) {
2715 $course = $courseorid;
2716 } else if ($courseorid == SITEID) {
2717 $course = clone($SITE);
2718 } else {
2719 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2721 if ($cm) {
2722 if ($cm->course != $course->id) {
2723 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2725 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2726 if (!($cm instanceof cm_info)) {
2727 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2728 // db queries so this is not really a performance concern, however it is obviously
2729 // better if you use get_fast_modinfo to get the cm before calling this.
2730 $modinfo = get_fast_modinfo($course);
2731 $cm = $modinfo->get_cm($cm->id);
2734 } else {
2735 // Do not touch global $COURSE via $PAGE->set_course(),
2736 // the reasons is we need to be able to call require_login() at any time!!
2737 $course = $SITE;
2738 if ($cm) {
2739 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2743 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2744 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2745 // risk leading the user back to the AJAX request URL.
2746 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2747 $setwantsurltome = false;
2750 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2751 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2752 if ($preventredirect) {
2753 throw new require_login_session_timeout_exception();
2754 } else {
2755 if ($setwantsurltome) {
2756 $SESSION->wantsurl = qualified_me();
2758 redirect(get_login_url());
2762 // If the user is not even logged in yet then make sure they are.
2763 if (!isloggedin()) {
2764 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2765 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2766 // Misconfigured site guest, just redirect to login page.
2767 redirect(get_login_url());
2768 exit; // Never reached.
2770 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2771 complete_user_login($guest);
2772 $USER->autologinguest = true;
2773 $SESSION->lang = $lang;
2774 } else {
2775 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2776 if ($preventredirect) {
2777 throw new require_login_exception('You are not logged in');
2780 if ($setwantsurltome) {
2781 $SESSION->wantsurl = qualified_me();
2784 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2785 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
2786 foreach($authsequence as $authname) {
2787 $authplugin = get_auth_plugin($authname);
2788 $authplugin->pre_loginpage_hook();
2789 if (isloggedin()) {
2790 if ($cm) {
2791 $modinfo = get_fast_modinfo($course);
2792 $cm = $modinfo->get_cm($cm->id);
2794 set_access_log_user();
2795 break;
2799 // If we're still not logged in then go to the login page
2800 if (!isloggedin()) {
2801 redirect(get_login_url());
2802 exit; // Never reached.
2807 // Loginas as redirection if needed.
2808 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2809 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2810 if ($USER->loginascontext->instanceid != $course->id) {
2811 throw new \moodle_exception('loginasonecourse', '',
2812 $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2817 // Check whether the user should be changing password (but only if it is REALLY them).
2818 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2819 $userauth = get_auth_plugin($USER->auth);
2820 if ($userauth->can_change_password() and !$preventredirect) {
2821 if ($setwantsurltome) {
2822 $SESSION->wantsurl = qualified_me();
2824 if ($changeurl = $userauth->change_password_url()) {
2825 // Use plugin custom url.
2826 redirect($changeurl);
2827 } else {
2828 // Use moodle internal method.
2829 redirect($CFG->wwwroot .'/login/change_password.php');
2831 } else if ($userauth->can_change_password()) {
2832 throw new moodle_exception('forcepasswordchangenotice');
2833 } else {
2834 throw new moodle_exception('nopasswordchangeforced', 'auth');
2838 // Check that the user account is properly set up. If we can't redirect to
2839 // edit their profile and this is not a WS request, perform just the lax check.
2840 // It will allow them to use filepicker on the profile edit page.
2842 if ($preventredirect && !WS_SERVER) {
2843 $usernotfullysetup = user_not_fully_set_up($USER, false);
2844 } else {
2845 $usernotfullysetup = user_not_fully_set_up($USER, true);
2848 if ($usernotfullysetup) {
2849 if ($preventredirect) {
2850 throw new moodle_exception('usernotfullysetup');
2852 if ($setwantsurltome) {
2853 $SESSION->wantsurl = qualified_me();
2855 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2858 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2859 sesskey();
2861 if (\core\session\manager::is_loggedinas()) {
2862 // During a "logged in as" session we should force all content to be cleaned because the
2863 // logged in user will be viewing potentially malicious user generated content.
2864 // See MDL-63786 for more details.
2865 $CFG->forceclean = true;
2868 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2870 // Do not bother admins with any formalities, except for activities pending deletion.
2871 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2872 // Set the global $COURSE.
2873 if ($cm) {
2874 $PAGE->set_cm($cm, $course);
2875 $PAGE->set_pagelayout('incourse');
2876 } else if (!empty($courseorid)) {
2877 $PAGE->set_course($course);
2879 // Set accesstime or the user will appear offline which messes up messaging.
2880 // Do not update access time for webservice or ajax requests.
2881 if (!WS_SERVER && !AJAX_SCRIPT) {
2882 user_accesstime_log($course->id);
2885 foreach ($afterlogins as $plugintype => $plugins) {
2886 foreach ($plugins as $pluginfunction) {
2887 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2890 return;
2893 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2894 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2895 if (!defined('NO_SITEPOLICY_CHECK')) {
2896 define('NO_SITEPOLICY_CHECK', false);
2899 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2900 // Do not test if the script explicitly asked for skipping the site policies check.
2901 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2902 $manager = new \core_privacy\local\sitepolicy\manager();
2903 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2904 if ($preventredirect) {
2905 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2907 if ($setwantsurltome) {
2908 $SESSION->wantsurl = qualified_me();
2910 redirect($policyurl);
2914 // Fetch the system context, the course context, and prefetch its child contexts.
2915 $sysctx = context_system::instance();
2916 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2917 if ($cm) {
2918 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2919 } else {
2920 $cmcontext = null;
2923 // If the site is currently under maintenance, then print a message.
2924 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2925 if ($preventredirect) {
2926 throw new require_login_exception('Maintenance in progress');
2928 $PAGE->set_context(null);
2929 print_maintenance_message();
2932 // Make sure the course itself is not hidden.
2933 if ($course->id == SITEID) {
2934 // Frontpage can not be hidden.
2935 } else {
2936 if (is_role_switched($course->id)) {
2937 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2938 } else {
2939 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2940 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2941 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2942 if ($preventredirect) {
2943 throw new require_login_exception('Course is hidden');
2945 $PAGE->set_context(null);
2946 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2947 // the navigation will mess up when trying to find it.
2948 navigation_node::override_active_url(new moodle_url('/'));
2949 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2954 // Is the user enrolled?
2955 if ($course->id == SITEID) {
2956 // Everybody is enrolled on the frontpage.
2957 } else {
2958 if (\core\session\manager::is_loggedinas()) {
2959 // Make sure the REAL person can access this course first.
2960 $realuser = \core\session\manager::get_realuser();
2961 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2962 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2963 if ($preventredirect) {
2964 throw new require_login_exception('Invalid course login-as access');
2966 $PAGE->set_context(null);
2967 echo $OUTPUT->header();
2968 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2972 $access = false;
2974 if (is_role_switched($course->id)) {
2975 // Ok, user had to be inside this course before the switch.
2976 $access = true;
2978 } else if (is_viewing($coursecontext, $USER)) {
2979 // Ok, no need to mess with enrol.
2980 $access = true;
2982 } else {
2983 if (isset($USER->enrol['enrolled'][$course->id])) {
2984 if ($USER->enrol['enrolled'][$course->id] > time()) {
2985 $access = true;
2986 if (isset($USER->enrol['tempguest'][$course->id])) {
2987 unset($USER->enrol['tempguest'][$course->id]);
2988 remove_temp_course_roles($coursecontext);
2990 } else {
2991 // Expired.
2992 unset($USER->enrol['enrolled'][$course->id]);
2995 if (isset($USER->enrol['tempguest'][$course->id])) {
2996 if ($USER->enrol['tempguest'][$course->id] == 0) {
2997 $access = true;
2998 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2999 $access = true;
3000 } else {
3001 // Expired.
3002 unset($USER->enrol['tempguest'][$course->id]);
3003 remove_temp_course_roles($coursecontext);
3007 if (!$access) {
3008 // Cache not ok.
3009 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3010 if ($until !== false) {
3011 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3012 if ($until == 0) {
3013 $until = ENROL_MAX_TIMESTAMP;
3015 $USER->enrol['enrolled'][$course->id] = $until;
3016 $access = true;
3018 } else if (core_course_category::can_view_course_info($course)) {
3019 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3020 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3021 $enrols = enrol_get_plugins(true);
3022 // First ask all enabled enrol instances in course if they want to auto enrol user.
3023 foreach ($instances as $instance) {
3024 if (!isset($enrols[$instance->enrol])) {
3025 continue;
3027 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3028 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3029 if ($until !== false) {
3030 if ($until == 0) {
3031 $until = ENROL_MAX_TIMESTAMP;
3033 $USER->enrol['enrolled'][$course->id] = $until;
3034 $access = true;
3035 break;
3038 // If not enrolled yet try to gain temporary guest access.
3039 if (!$access) {
3040 foreach ($instances as $instance) {
3041 if (!isset($enrols[$instance->enrol])) {
3042 continue;
3044 // Get a duration for the guest access, a timestamp in the future or false.
3045 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3046 if ($until !== false and $until > time()) {
3047 $USER->enrol['tempguest'][$course->id] = $until;
3048 $access = true;
3049 break;
3053 } else {
3054 // User is not enrolled and is not allowed to browse courses here.
3055 if ($preventredirect) {
3056 throw new require_login_exception('Course is not available');
3058 $PAGE->set_context(null);
3059 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3060 // the navigation will mess up when trying to find it.
3061 navigation_node::override_active_url(new moodle_url('/'));
3062 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3067 if (!$access) {
3068 if ($preventredirect) {
3069 throw new require_login_exception('Not enrolled');
3071 if ($setwantsurltome) {
3072 $SESSION->wantsurl = qualified_me();
3074 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3078 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3079 if ($cm && $cm->deletioninprogress) {
3080 if ($preventredirect) {
3081 throw new moodle_exception('activityisscheduledfordeletion');
3083 require_once($CFG->dirroot . '/course/lib.php');
3084 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3087 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3088 if ($cm && !$cm->uservisible) {
3089 if ($preventredirect) {
3090 throw new require_login_exception('Activity is hidden');
3092 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3093 $PAGE->set_course($course);
3094 $renderer = $PAGE->get_renderer('course');
3095 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3096 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3099 // Set the global $COURSE.
3100 if ($cm) {
3101 $PAGE->set_cm($cm, $course);
3102 $PAGE->set_pagelayout('incourse');
3103 } else if (!empty($courseorid)) {
3104 $PAGE->set_course($course);
3107 foreach ($afterlogins as $plugintype => $plugins) {
3108 foreach ($plugins as $pluginfunction) {
3109 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3113 // Finally access granted, update lastaccess times.
3114 // Do not update access time for webservice or ajax requests.
3115 if (!WS_SERVER && !AJAX_SCRIPT) {
3116 user_accesstime_log($course->id);
3121 * A convenience function for where we must be logged in as admin
3122 * @return void
3124 function require_admin() {
3125 require_login(null, false);
3126 require_capability('moodle/site:config', context_system::instance());
3130 * This function just makes sure a user is logged out.
3132 * @package core_access
3133 * @category access
3135 function require_logout() {
3136 global $USER, $DB;
3138 if (!isloggedin()) {
3139 // This should not happen often, no need for hooks or events here.
3140 \core\session\manager::terminate_current();
3141 return;
3144 // Execute hooks before action.
3145 $authplugins = array();
3146 $authsequence = get_enabled_auth_plugins();
3147 foreach ($authsequence as $authname) {
3148 $authplugins[$authname] = get_auth_plugin($authname);
3149 $authplugins[$authname]->prelogout_hook();
3152 // Store info that gets removed during logout.
3153 $sid = session_id();
3154 $event = \core\event\user_loggedout::create(
3155 array(
3156 'userid' => $USER->id,
3157 'objectid' => $USER->id,
3158 'other' => array('sessionid' => $sid),
3161 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3162 $event->add_record_snapshot('sessions', $session);
3165 // Clone of $USER object to be used by auth plugins.
3166 $user = fullclone($USER);
3168 // Delete session record and drop $_SESSION content.
3169 \core\session\manager::terminate_current();
3171 // Trigger event AFTER action.
3172 $event->trigger();
3174 // Hook to execute auth plugins redirection after event trigger.
3175 foreach ($authplugins as $authplugin) {
3176 $authplugin->postlogout_hook($user);
3181 * Weaker version of require_login()
3183 * This is a weaker version of {@link require_login()} which only requires login
3184 * when called from within a course rather than the site page, unless
3185 * the forcelogin option is turned on.
3186 * @see require_login()
3188 * @package core_access
3189 * @category access
3191 * @param mixed $courseorid The course object or id in question
3192 * @param bool $autologinguest Allow autologin guests if that is wanted
3193 * @param object $cm Course activity module if known
3194 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3195 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3196 * in order to keep redirects working properly. MDL-14495
3197 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3198 * @return void
3199 * @throws coding_exception
3201 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3202 global $CFG, $PAGE, $SITE;
3203 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3204 or (!is_object($courseorid) and $courseorid == SITEID));
3205 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3206 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3207 // db queries so this is not really a performance concern, however it is obviously
3208 // better if you use get_fast_modinfo to get the cm before calling this.
3209 if (is_object($courseorid)) {
3210 $course = $courseorid;
3211 } else {
3212 $course = clone($SITE);
3214 $modinfo = get_fast_modinfo($course);
3215 $cm = $modinfo->get_cm($cm->id);
3217 if (!empty($CFG->forcelogin)) {
3218 // Login required for both SITE and courses.
3219 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3221 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3222 // Always login for hidden activities.
3223 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3225 } else if (isloggedin() && !isguestuser()) {
3226 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3227 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3229 } else if ($issite) {
3230 // Login for SITE not required.
3231 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3232 if (!empty($courseorid)) {
3233 if (is_object($courseorid)) {
3234 $course = $courseorid;
3235 } else {
3236 $course = clone $SITE;
3238 if ($cm) {
3239 if ($cm->course != $course->id) {
3240 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3242 $PAGE->set_cm($cm, $course);
3243 $PAGE->set_pagelayout('incourse');
3244 } else {
3245 $PAGE->set_course($course);
3247 } else {
3248 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3249 $PAGE->set_course($PAGE->course);
3251 // Do not update access time for webservice or ajax requests.
3252 if (!WS_SERVER && !AJAX_SCRIPT) {
3253 user_accesstime_log(SITEID);
3255 return;
3257 } else {
3258 // Course login always required.
3259 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3264 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3266 * @param string $keyvalue the key value
3267 * @param string $script unique script identifier
3268 * @param int $instance instance id
3269 * @return stdClass the key entry in the user_private_key table
3270 * @since Moodle 3.2
3271 * @throws moodle_exception
3273 function validate_user_key($keyvalue, $script, $instance) {
3274 global $DB;
3276 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3277 throw new \moodle_exception('invalidkey');
3280 if (!empty($key->validuntil) and $key->validuntil < time()) {
3281 throw new \moodle_exception('expiredkey');
3284 if ($key->iprestriction) {
3285 $remoteaddr = getremoteaddr(null);
3286 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3287 throw new \moodle_exception('ipmismatch');
3290 return $key;
3294 * Require key login. Function terminates with error if key not found or incorrect.
3296 * @uses NO_MOODLE_COOKIES
3297 * @uses PARAM_ALPHANUM
3298 * @param string $script unique script identifier
3299 * @param int $instance optional instance id
3300 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3301 * @return int Instance ID
3303 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3304 global $DB;
3306 if (!NO_MOODLE_COOKIES) {
3307 throw new \moodle_exception('sessioncookiesdisable');
3310 // Extra safety.
3311 \core\session\manager::write_close();
3313 if (null === $keyvalue) {
3314 $keyvalue = required_param('key', PARAM_ALPHANUM);
3317 $key = validate_user_key($keyvalue, $script, $instance);
3319 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3320 throw new \moodle_exception('invaliduserid');
3323 core_user::require_active_user($user, true, true);
3325 // Emulate normal session.
3326 enrol_check_plugins($user, false);
3327 \core\session\manager::set_user($user);
3329 // Note we are not using normal login.
3330 if (!defined('USER_KEY_LOGIN')) {
3331 define('USER_KEY_LOGIN', true);
3334 // Return instance id - it might be empty.
3335 return $key->instance;
3339 * Creates a new private user access key.
3341 * @param string $script unique target identifier
3342 * @param int $userid
3343 * @param int $instance optional instance id
3344 * @param string $iprestriction optional ip restricted access
3345 * @param int $validuntil key valid only until given data
3346 * @return string access key value
3348 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3349 global $DB;
3351 $key = new stdClass();
3352 $key->script = $script;
3353 $key->userid = $userid;
3354 $key->instance = $instance;
3355 $key->iprestriction = $iprestriction;
3356 $key->validuntil = $validuntil;
3357 $key->timecreated = time();
3359 // Something long and unique.
3360 $key->value = md5($userid.'_'.time().random_string(40));
3361 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3362 // Must be unique.
3363 $key->value = md5($userid.'_'.time().random_string(40));
3365 $DB->insert_record('user_private_key', $key);
3366 return $key->value;
3370 * Delete the user's new private user access keys for a particular script.
3372 * @param string $script unique target identifier
3373 * @param int $userid
3374 * @return void
3376 function delete_user_key($script, $userid) {
3377 global $DB;
3378 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3382 * Gets a private user access key (and creates one if one doesn't exist).
3384 * @param string $script unique target identifier
3385 * @param int $userid
3386 * @param int $instance optional instance id
3387 * @param string $iprestriction optional ip restricted access
3388 * @param int $validuntil key valid only until given date
3389 * @return string access key value
3391 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3392 global $DB;
3394 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3395 'instance' => $instance, 'iprestriction' => $iprestriction,
3396 'validuntil' => $validuntil))) {
3397 return $key->value;
3398 } else {
3399 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3405 * Modify the user table by setting the currently logged in user's last login to now.
3407 * @return bool Always returns true
3409 function update_user_login_times() {
3410 global $USER, $DB, $SESSION;
3412 if (isguestuser()) {
3413 // Do not update guest access times/ips for performance.
3414 return true;
3417 if (defined('USER_KEY_LOGIN') && USER_KEY_LOGIN === true) {
3418 // Do not update user login time when using user key login.
3419 return true;
3422 $now = time();
3424 $user = new stdClass();
3425 $user->id = $USER->id;
3427 // Make sure all users that logged in have some firstaccess.
3428 if ($USER->firstaccess == 0) {
3429 $USER->firstaccess = $user->firstaccess = $now;
3432 // Store the previous current as lastlogin.
3433 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3435 $USER->currentlogin = $user->currentlogin = $now;
3437 // Function user_accesstime_log() may not update immediately, better do it here.
3438 $USER->lastaccess = $user->lastaccess = $now;
3439 $SESSION->userpreviousip = $USER->lastip;
3440 $USER->lastip = $user->lastip = getremoteaddr();
3442 // Note: do not call user_update_user() here because this is part of the login process,
3443 // the login event means that these fields were updated.
3444 $DB->update_record('user', $user);
3445 return true;
3449 * Determines if a user has completed setting up their account.
3451 * The lax mode (with $strict = false) has been introduced for special cases
3452 * only where we want to skip certain checks intentionally. This is valid in
3453 * certain mnet or ajax scenarios when the user cannot / should not be
3454 * redirected to edit their profile. In most cases, you should perform the
3455 * strict check.
3457 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3458 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3459 * @return bool
3461 function user_not_fully_set_up($user, $strict = true) {
3462 global $CFG, $SESSION, $USER;
3463 require_once($CFG->dirroot.'/user/profile/lib.php');
3465 // If the user is setup then store this in the session to avoid re-checking.
3466 // Some edge cases are when the users email starts to bounce or the
3467 // configuration for custom fields has changed while they are logged in so
3468 // we re-check this fully every hour for the rare cases it has changed.
3469 if (isset($USER->id) && isset($user->id) && $USER->id === $user->id &&
3470 isset($SESSION->fullysetupstrict) && (time() - $SESSION->fullysetupstrict) < HOURSECS) {
3471 return false;
3474 if (isguestuser($user)) {
3475 return false;
3478 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3479 return true;
3482 if ($strict) {
3483 if (empty($user->id)) {
3484 // Strict mode can be used with existing accounts only.
3485 return true;
3487 if (!profile_has_required_custom_fields_set($user->id)) {
3488 return true;
3490 if (isset($USER->id) && isset($user->id) && $USER->id === $user->id) {
3491 $SESSION->fullysetupstrict = time();
3495 return false;
3499 * Check whether the user has exceeded the bounce threshold
3501 * @param stdClass $user A {@link $USER} object
3502 * @return bool true => User has exceeded bounce threshold
3504 function over_bounce_threshold($user) {
3505 global $CFG, $DB;
3507 if (empty($CFG->handlebounces)) {
3508 return false;
3511 if (empty($user->id)) {
3512 // No real (DB) user, nothing to do here.
3513 return false;
3516 // Set sensible defaults.
3517 if (empty($CFG->minbounces)) {
3518 $CFG->minbounces = 10;
3520 if (empty($CFG->bounceratio)) {
3521 $CFG->bounceratio = .20;
3523 $bouncecount = 0;
3524 $sendcount = 0;
3525 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3526 $bouncecount = $bounce->value;
3528 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3529 $sendcount = $send->value;
3531 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3535 * Used to increment or reset email sent count
3537 * @param stdClass $user object containing an id
3538 * @param bool $reset will reset the count to 0
3539 * @return void
3541 function set_send_count($user, $reset=false) {
3542 global $DB;
3544 if (empty($user->id)) {
3545 // No real (DB) user, nothing to do here.
3546 return;
3549 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3550 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3551 $DB->update_record('user_preferences', $pref);
3552 } else if (!empty($reset)) {
3553 // If it's not there and we're resetting, don't bother. Make a new one.
3554 $pref = new stdClass();
3555 $pref->name = 'email_send_count';
3556 $pref->value = 1;
3557 $pref->userid = $user->id;
3558 $DB->insert_record('user_preferences', $pref, false);
3563 * Increment or reset user's email bounce count
3565 * @param stdClass $user object containing an id
3566 * @param bool $reset will reset the count to 0
3568 function set_bounce_count($user, $reset=false) {
3569 global $DB;
3571 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3572 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3573 $DB->update_record('user_preferences', $pref);
3574 } else if (!empty($reset)) {
3575 // If it's not there and we're resetting, don't bother. Make a new one.
3576 $pref = new stdClass();
3577 $pref->name = 'email_bounce_count';
3578 $pref->value = 1;
3579 $pref->userid = $user->id;
3580 $DB->insert_record('user_preferences', $pref, false);
3585 * Determines if the logged in user is currently moving an activity
3587 * @param int $courseid The id of the course being tested
3588 * @return bool
3590 function ismoving($courseid) {
3591 global $USER;
3593 if (!empty($USER->activitycopy)) {
3594 return ($USER->activitycopycourse == $courseid);
3596 return false;
3600 * Returns a persons full name
3602 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3603 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3604 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3605 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3607 * @param stdClass $user A {@link $USER} object to get full name of.
3608 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3609 * @return string
3611 function fullname($user, $override=false) {
3612 global $CFG, $SESSION;
3614 if (!isset($user->firstname) and !isset($user->lastname)) {
3615 return '';
3618 // Get all of the name fields.
3619 $allnames = \core_user\fields::get_name_fields();
3620 if ($CFG->debugdeveloper) {
3621 foreach ($allnames as $allname) {
3622 if (!property_exists($user, $allname)) {
3623 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3624 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3625 // Message has been sent, no point in sending the message multiple times.
3626 break;
3631 if (!$override) {
3632 if (!empty($CFG->forcefirstname)) {
3633 $user->firstname = $CFG->forcefirstname;
3635 if (!empty($CFG->forcelastname)) {
3636 $user->lastname = $CFG->forcelastname;
3640 if (!empty($SESSION->fullnamedisplay)) {
3641 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3644 $template = null;
3645 // If the fullnamedisplay setting is available, set the template to that.
3646 if (isset($CFG->fullnamedisplay)) {
3647 $template = $CFG->fullnamedisplay;
3649 // If the template is empty, or set to language, return the language string.
3650 if ((empty($template) || $template == 'language') && !$override) {
3651 return get_string('fullnamedisplay', null, $user);
3654 // Check to see if we are displaying according to the alternative full name format.
3655 if ($override) {
3656 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3657 // Default to show just the user names according to the fullnamedisplay string.
3658 return get_string('fullnamedisplay', null, $user);
3659 } else {
3660 // If the override is true, then change the template to use the complete name.
3661 $template = $CFG->alternativefullnameformat;
3665 $requirednames = array();
3666 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3667 foreach ($allnames as $allname) {
3668 if (strpos($template, $allname) !== false) {
3669 $requirednames[] = $allname;
3673 $displayname = $template;
3674 // Switch in the actual data into the template.
3675 foreach ($requirednames as $altname) {
3676 if (isset($user->$altname)) {
3677 // Using empty() on the below if statement causes breakages.
3678 if ((string)$user->$altname == '') {
3679 $displayname = str_replace($altname, 'EMPTY', $displayname);
3680 } else {
3681 $displayname = str_replace($altname, $user->$altname, $displayname);
3683 } else {
3684 $displayname = str_replace($altname, 'EMPTY', $displayname);
3687 // Tidy up any misc. characters (Not perfect, but gets most characters).
3688 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3689 // katakana and parenthesis.
3690 $patterns = array();
3691 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3692 // filled in by a user.
3693 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3694 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3695 // This regular expression is to remove any double spaces in the display name.
3696 $patterns[] = '/\s{2,}/u';
3697 foreach ($patterns as $pattern) {
3698 $displayname = preg_replace($pattern, ' ', $displayname);
3701 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3702 $displayname = trim($displayname);
3703 if (empty($displayname)) {
3704 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3705 // people in general feel is a good setting to fall back on.
3706 $displayname = $user->firstname;
3708 return $displayname;
3712 * Reduces lines of duplicated code for getting user name fields.
3714 * See also {@link user_picture::unalias()}
3716 * @param object $addtoobject Object to add user name fields to.
3717 * @param object $secondobject Object that contains user name field information.
3718 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3719 * @param array $additionalfields Additional fields to be matched with data in the second object.
3720 * The key can be set to the user table field name.
3721 * @return object User name fields.
3723 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3724 $fields = [];
3725 foreach (\core_user\fields::get_name_fields() as $field) {
3726 $fields[$field] = $prefix . $field;
3728 if ($additionalfields) {
3729 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3730 // the key is a number and then sets the key to the array value.
3731 foreach ($additionalfields as $key => $value) {
3732 if (is_numeric($key)) {
3733 $additionalfields[$value] = $prefix . $value;
3734 unset($additionalfields[$key]);
3735 } else {
3736 $additionalfields[$key] = $prefix . $value;
3739 $fields = array_merge($fields, $additionalfields);
3741 foreach ($fields as $key => $field) {
3742 // Important that we have all of the user name fields present in the object that we are sending back.
3743 $addtoobject->$key = '';
3744 if (isset($secondobject->$field)) {
3745 $addtoobject->$key = $secondobject->$field;
3748 return $addtoobject;
3752 * Returns an array of values in order of occurance in a provided string.
3753 * The key in the result is the character postion in the string.
3755 * @param array $values Values to be found in the string format
3756 * @param string $stringformat The string which may contain values being searched for.
3757 * @return array An array of values in order according to placement in the string format.
3759 function order_in_string($values, $stringformat) {
3760 $valuearray = array();
3761 foreach ($values as $value) {
3762 $pattern = "/$value\b/";
3763 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3764 if (preg_match($pattern, $stringformat)) {
3765 $replacement = "thing";
3766 // Replace the value with something more unique to ensure we get the right position when using strpos().
3767 $newformat = preg_replace($pattern, $replacement, $stringformat);
3768 $position = strpos($newformat, $replacement);
3769 $valuearray[$position] = $value;
3772 ksort($valuearray);
3773 return $valuearray;
3777 * Returns whether a given authentication plugin exists.
3779 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3780 * @return boolean Whether the plugin is available.
3782 function exists_auth_plugin($auth) {
3783 global $CFG;
3785 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3786 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3788 return false;
3792 * Checks if a given plugin is in the list of enabled authentication plugins.
3794 * @param string $auth Authentication plugin.
3795 * @return boolean Whether the plugin is enabled.
3797 function is_enabled_auth($auth) {
3798 if (empty($auth)) {
3799 return false;
3802 $enabled = get_enabled_auth_plugins();
3804 return in_array($auth, $enabled);
3808 * Returns an authentication plugin instance.
3810 * @param string $auth name of authentication plugin
3811 * @return auth_plugin_base An instance of the required authentication plugin.
3813 function get_auth_plugin($auth) {
3814 global $CFG;
3816 // Check the plugin exists first.
3817 if (! exists_auth_plugin($auth)) {
3818 throw new \moodle_exception('authpluginnotfound', 'debug', '', $auth);
3821 // Return auth plugin instance.
3822 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3823 $class = "auth_plugin_$auth";
3824 return new $class;
3828 * Returns array of active auth plugins.
3830 * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
3831 * @return array
3833 function get_enabled_auth_plugins($fix=false) {
3834 global $CFG;
3836 $default = array('manual', 'nologin');
3838 if (empty($CFG->auth)) {
3839 $auths = array();
3840 } else {
3841 $auths = explode(',', $CFG->auth);
3844 $auths = array_unique($auths);
3845 $oldauthconfig = implode(',', $auths);
3846 foreach ($auths as $k => $authname) {
3847 if (in_array($authname, $default)) {
3848 // The manual and nologin plugin never need to be stored.
3849 unset($auths[$k]);
3850 } else if (!exists_auth_plugin($authname)) {
3851 debugging(get_string('authpluginnotfound', 'debug', $authname));
3852 unset($auths[$k]);
3856 // Ideally only explicit interaction from a human admin should trigger a
3857 // change in auth config, see MDL-70424 for details.
3858 if ($fix) {
3859 $newconfig = implode(',', $auths);
3860 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3861 add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
3862 set_config('auth', $newconfig);
3866 return (array_merge($default, $auths));
3870 * Returns true if an internal authentication method is being used.
3871 * if method not specified then, global default is assumed
3873 * @param string $auth Form of authentication required
3874 * @return bool
3876 function is_internal_auth($auth) {
3877 // Throws error if bad $auth.
3878 $authplugin = get_auth_plugin($auth);
3879 return $authplugin->is_internal();
3883 * Returns true if the user is a 'restored' one.
3885 * Used in the login process to inform the user and allow him/her to reset the password
3887 * @param string $username username to be checked
3888 * @return bool
3890 function is_restored_user($username) {
3891 global $CFG, $DB;
3893 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3897 * Returns an array of user fields
3899 * @return array User field/column names
3901 function get_user_fieldnames() {
3902 global $DB;
3904 $fieldarray = $DB->get_columns('user');
3905 unset($fieldarray['id']);
3906 $fieldarray = array_keys($fieldarray);
3908 return $fieldarray;
3912 * Returns the string of the language for the new user.
3914 * @return string language for the new user
3916 function get_newuser_language() {
3917 global $CFG, $SESSION;
3918 return (!empty($CFG->autolangusercreation) && !empty($SESSION->lang)) ? $SESSION->lang : $CFG->lang;
3922 * Creates a bare-bones user record
3924 * @todo Outline auth types and provide code example
3926 * @param string $username New user's username to add to record
3927 * @param string $password New user's password to add to record
3928 * @param string $auth Form of authentication required
3929 * @return stdClass A complete user object
3931 function create_user_record($username, $password, $auth = 'manual') {
3932 global $CFG, $DB, $SESSION;
3933 require_once($CFG->dirroot.'/user/profile/lib.php');
3934 require_once($CFG->dirroot.'/user/lib.php');
3936 // Just in case check text case.
3937 $username = trim(core_text::strtolower($username));
3939 $authplugin = get_auth_plugin($auth);
3940 $customfields = $authplugin->get_custom_user_profile_fields();
3941 $newuser = new stdClass();
3942 if ($newinfo = $authplugin->get_userinfo($username)) {
3943 $newinfo = truncate_userinfo($newinfo);
3944 foreach ($newinfo as $key => $value) {
3945 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3946 $newuser->$key = $value;
3951 if (!empty($newuser->email)) {
3952 if (email_is_not_allowed($newuser->email)) {
3953 unset($newuser->email);
3957 $newuser->auth = $auth;
3958 $newuser->username = $username;
3960 // Fix for MDL-8480
3961 // user CFG lang for user if $newuser->lang is empty
3962 // or $user->lang is not an installed language.
3963 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3964 $newuser->lang = get_newuser_language();
3966 $newuser->confirmed = 1;
3967 $newuser->lastip = getremoteaddr();
3968 $newuser->timecreated = time();
3969 $newuser->timemodified = $newuser->timecreated;
3970 $newuser->mnethostid = $CFG->mnet_localhost_id;
3972 $newuser->id = user_create_user($newuser, false, false);
3974 // Save user profile data.
3975 profile_save_data($newuser);
3977 $user = get_complete_user_data('id', $newuser->id);
3978 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3979 set_user_preference('auth_forcepasswordchange', 1, $user);
3981 // Set the password.
3982 update_internal_user_password($user, $password);
3984 // Trigger event.
3985 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3987 return $user;
3991 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3993 * @param string $username user's username to update the record
3994 * @return stdClass A complete user object
3996 function update_user_record($username) {
3997 global $DB, $CFG;
3998 // Just in case check text case.
3999 $username = trim(core_text::strtolower($username));
4001 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
4002 return update_user_record_by_id($oldinfo->id);
4006 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4008 * @param int $id user id
4009 * @return stdClass A complete user object
4011 function update_user_record_by_id($id) {
4012 global $DB, $CFG;
4013 require_once($CFG->dirroot."/user/profile/lib.php");
4014 require_once($CFG->dirroot.'/user/lib.php');
4016 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
4017 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
4019 $newuser = array();
4020 $userauth = get_auth_plugin($oldinfo->auth);
4022 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4023 $newinfo = truncate_userinfo($newinfo);
4024 $customfields = $userauth->get_custom_user_profile_fields();
4026 foreach ($newinfo as $key => $value) {
4027 $iscustom = in_array($key, $customfields);
4028 if (!$iscustom) {
4029 $key = strtolower($key);
4031 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4032 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4033 // Unknown or must not be changed.
4034 continue;
4036 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
4037 continue;
4039 $confval = $userauth->config->{'field_updatelocal_' . $key};
4040 $lockval = $userauth->config->{'field_lock_' . $key};
4041 if ($confval === 'onlogin') {
4042 // MDL-4207 Don't overwrite modified user profile values with
4043 // empty LDAP values when 'unlocked if empty' is set. The purpose
4044 // of the setting 'unlocked if empty' is to allow the user to fill
4045 // in a value for the selected field _if LDAP is giving
4046 // nothing_ for this field. Thus it makes sense to let this value
4047 // stand in until LDAP is giving a value for this field.
4048 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4049 if ($iscustom || (in_array($key, $userauth->userfields) &&
4050 ((string)$oldinfo->$key !== (string)$value))) {
4051 $newuser[$key] = (string)$value;
4056 if ($newuser) {
4057 $newuser['id'] = $oldinfo->id;
4058 $newuser['timemodified'] = time();
4059 user_update_user((object) $newuser, false, false);
4061 // Save user profile data.
4062 profile_save_data((object) $newuser);
4064 // Trigger event.
4065 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4069 return get_complete_user_data('id', $oldinfo->id);
4073 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4075 * @param array $info Array of user properties to truncate if needed
4076 * @return array The now truncated information that was passed in
4078 function truncate_userinfo(array $info) {
4079 // Define the limits.
4080 $limit = array(
4081 'username' => 100,
4082 'idnumber' => 255,
4083 'firstname' => 100,
4084 'lastname' => 100,
4085 'email' => 100,
4086 'phone1' => 20,
4087 'phone2' => 20,
4088 'institution' => 255,
4089 'department' => 255,
4090 'address' => 255,
4091 'city' => 120,
4092 'country' => 2,
4095 // Apply where needed.
4096 foreach (array_keys($info) as $key) {
4097 if (!empty($limit[$key])) {
4098 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4102 return $info;
4106 * Marks user deleted in internal user database and notifies the auth plugin.
4107 * Also unenrols user from all roles and does other cleanup.
4109 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4111 * @param stdClass $user full user object before delete
4112 * @return boolean success
4113 * @throws coding_exception if invalid $user parameter detected
4115 function delete_user(stdClass $user) {
4116 global $CFG, $DB, $SESSION;
4117 require_once($CFG->libdir.'/grouplib.php');
4118 require_once($CFG->libdir.'/gradelib.php');
4119 require_once($CFG->dirroot.'/message/lib.php');
4120 require_once($CFG->dirroot.'/user/lib.php');
4122 // Make sure nobody sends bogus record type as parameter.
4123 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4124 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4127 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4128 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4129 debugging('Attempt to delete unknown user account.');
4130 return false;
4133 // There must be always exactly one guest record, originally the guest account was identified by username only,
4134 // now we use $CFG->siteguest for performance reasons.
4135 if ($user->username === 'guest' or isguestuser($user)) {
4136 debugging('Guest user account can not be deleted.');
4137 return false;
4140 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4141 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4142 if ($user->auth === 'manual' and is_siteadmin($user)) {
4143 debugging('Local administrator accounts can not be deleted.');
4144 return false;
4147 // Allow plugins to use this user object before we completely delete it.
4148 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4149 foreach ($pluginsfunction as $plugintype => $plugins) {
4150 foreach ($plugins as $pluginfunction) {
4151 $pluginfunction($user);
4156 // Keep user record before updating it, as we have to pass this to user_deleted event.
4157 $olduser = clone $user;
4159 // Keep a copy of user context, we need it for event.
4160 $usercontext = context_user::instance($user->id);
4162 // Delete all grades - backup is kept in grade_grades_history table.
4163 grade_user_delete($user->id);
4165 // TODO: remove from cohorts using standard API here.
4167 // Remove user tags.
4168 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4170 // Unconditionally unenrol from all courses.
4171 enrol_user_delete($user);
4173 // Unenrol from all roles in all contexts.
4174 // This might be slow but it is really needed - modules might do some extra cleanup!
4175 role_unassign_all(array('userid' => $user->id));
4177 // Notify the competency subsystem.
4178 \core_competency\api::hook_user_deleted($user->id);
4180 // Now do a brute force cleanup.
4182 // Delete all user events and subscription events.
4183 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
4185 // Now, delete all calendar subscription from the user.
4186 $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
4188 // Remove from all cohorts.
4189 $DB->delete_records('cohort_members', array('userid' => $user->id));
4191 // Remove from all groups.
4192 $DB->delete_records('groups_members', array('userid' => $user->id));
4194 // Brute force unenrol from all courses.
4195 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4197 // Purge user preferences.
4198 $DB->delete_records('user_preferences', array('userid' => $user->id));
4200 // Purge user extra profile info.
4201 $DB->delete_records('user_info_data', array('userid' => $user->id));
4203 // Purge log of previous password hashes.
4204 $DB->delete_records('user_password_history', array('userid' => $user->id));
4206 // Last course access not necessary either.
4207 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4208 // Remove all user tokens.
4209 $DB->delete_records('external_tokens', array('userid' => $user->id));
4211 // Unauthorise the user for all services.
4212 $DB->delete_records('external_services_users', array('userid' => $user->id));
4214 // Remove users private keys.
4215 $DB->delete_records('user_private_key', array('userid' => $user->id));
4217 // Remove users customised pages.
4218 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4220 // Remove user's oauth2 refresh tokens, if present.
4221 $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id));
4223 // Delete user from $SESSION->bulk_users.
4224 if (isset($SESSION->bulk_users[$user->id])) {
4225 unset($SESSION->bulk_users[$user->id]);
4228 // Force logout - may fail if file based sessions used, sorry.
4229 \core\session\manager::kill_user_sessions($user->id);
4231 // Generate username from email address, or a fake email.
4232 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4234 $deltime = time();
4235 $deltimelength = core_text::strlen((string) $deltime);
4237 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4238 $delname = clean_param($delemail, PARAM_USERNAME);
4239 $delname = core_text::substr($delname, 0, 100 - ($deltimelength + 1)) . ".{$deltime}";
4241 // Workaround for bulk deletes of users with the same email address.
4242 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4243 $delname++;
4246 // Mark internal user record as "deleted".
4247 $updateuser = new stdClass();
4248 $updateuser->id = $user->id;
4249 $updateuser->deleted = 1;
4250 $updateuser->username = $delname; // Remember it just in case.
4251 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4252 $updateuser->idnumber = ''; // Clear this field to free it up.
4253 $updateuser->picture = 0;
4254 $updateuser->timemodified = $deltime;
4256 // Don't trigger update event, as user is being deleted.
4257 user_update_user($updateuser, false, false);
4259 // Delete all content associated with the user context, but not the context itself.
4260 $usercontext->delete_content();
4262 // Delete any search data.
4263 \core_search\manager::context_deleted($usercontext);
4265 // Any plugin that needs to cleanup should register this event.
4266 // Trigger event.
4267 $event = \core\event\user_deleted::create(
4268 array(
4269 'objectid' => $user->id,
4270 'relateduserid' => $user->id,
4271 'context' => $usercontext,
4272 'other' => array(
4273 'username' => $user->username,
4274 'email' => $user->email,
4275 'idnumber' => $user->idnumber,
4276 'picture' => $user->picture,
4277 'mnethostid' => $user->mnethostid
4281 $event->add_record_snapshot('user', $olduser);
4282 $event->trigger();
4284 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4285 // should know about this updated property persisted to the user's table.
4286 $user->timemodified = $updateuser->timemodified;
4288 // Notify auth plugin - do not block the delete even when plugin fails.
4289 $authplugin = get_auth_plugin($user->auth);
4290 $authplugin->user_delete($user);
4292 return true;
4296 * Retrieve the guest user object.
4298 * @return stdClass A {@link $USER} object
4300 function guest_user() {
4301 global $CFG, $DB;
4303 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4304 $newuser->confirmed = 1;
4305 $newuser->lang = get_newuser_language();
4306 $newuser->lastip = getremoteaddr();
4309 return $newuser;
4313 * Authenticates a user against the chosen authentication mechanism
4315 * Given a username and password, this function looks them
4316 * up using the currently selected authentication mechanism,
4317 * and if the authentication is successful, it returns a
4318 * valid $user object from the 'user' table.
4320 * Uses auth_ functions from the currently active auth module
4322 * After authenticate_user_login() returns success, you will need to
4323 * log that the user has logged in, and call complete_user_login() to set
4324 * the session up.
4326 * Note: this function works only with non-mnet accounts!
4328 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4329 * @param string $password User's password
4330 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4331 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4332 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4333 * @return stdClass|false A {@link $USER} object or false if error
4335 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4336 global $CFG, $DB, $PAGE;
4337 require_once("$CFG->libdir/authlib.php");
4339 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4340 // we have found the user
4342 } else if (!empty($CFG->authloginviaemail)) {
4343 if ($email = clean_param($username, PARAM_EMAIL)) {
4344 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4345 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4346 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4347 if (count($users) === 1) {
4348 // Use email for login only if unique.
4349 $user = reset($users);
4350 $user = get_complete_user_data('id', $user->id);
4351 $username = $user->username;
4353 unset($users);
4357 // Make sure this request came from the login form.
4358 if (!\core\session\manager::validate_login_token($logintoken)) {
4359 $failurereason = AUTH_LOGIN_FAILED;
4361 // Trigger login failed event (specifying the ID of the found user, if available).
4362 \core\event\user_login_failed::create([
4363 'userid' => ($user->id ?? 0),
4364 'other' => [
4365 'username' => $username,
4366 'reason' => $failurereason,
4368 ])->trigger();
4370 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4371 return false;
4374 $authsenabled = get_enabled_auth_plugins();
4376 if ($user) {
4377 // Use manual if auth not set.
4378 $auth = empty($user->auth) ? 'manual' : $user->auth;
4380 if (in_array($user->auth, $authsenabled)) {
4381 $authplugin = get_auth_plugin($user->auth);
4382 $authplugin->pre_user_login_hook($user);
4385 if (!empty($user->suspended)) {
4386 $failurereason = AUTH_LOGIN_SUSPENDED;
4388 // Trigger login failed event.
4389 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4390 'other' => array('username' => $username, 'reason' => $failurereason)));
4391 $event->trigger();
4392 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4393 return false;
4395 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4396 // Legacy way to suspend user.
4397 $failurereason = AUTH_LOGIN_SUSPENDED;
4399 // Trigger login failed event.
4400 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4401 'other' => array('username' => $username, 'reason' => $failurereason)));
4402 $event->trigger();
4403 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4404 return false;
4406 $auths = array($auth);
4408 } else {
4409 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4410 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4411 $failurereason = AUTH_LOGIN_NOUSER;
4413 // Trigger login failed event.
4414 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4415 'reason' => $failurereason)));
4416 $event->trigger();
4417 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4418 return false;
4421 // User does not exist.
4422 $auths = $authsenabled;
4423 $user = new stdClass();
4424 $user->id = 0;
4427 if ($ignorelockout) {
4428 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4429 // or this function is called from a SSO script.
4430 } else if ($user->id) {
4431 // Verify login lockout after other ways that may prevent user login.
4432 if (login_is_lockedout($user)) {
4433 $failurereason = AUTH_LOGIN_LOCKOUT;
4435 // Trigger login failed event.
4436 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4437 'other' => array('username' => $username, 'reason' => $failurereason)));
4438 $event->trigger();
4440 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4441 return false;
4443 } else {
4444 // We can not lockout non-existing accounts.
4447 foreach ($auths as $auth) {
4448 $authplugin = get_auth_plugin($auth);
4450 // On auth fail fall through to the next plugin.
4451 if (!$authplugin->user_login($username, $password)) {
4452 continue;
4455 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4456 if (!empty($CFG->passwordpolicycheckonlogin)) {
4457 $errmsg = '';
4458 $passed = check_password_policy($password, $errmsg, $user);
4459 if (!$passed) {
4460 // First trigger event for failure.
4461 $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
4462 $failedevent->trigger();
4464 // If able to change password, set flag and move on.
4465 if ($authplugin->can_change_password()) {
4466 // Check if we are on internal change password page, or service is external, don't show notification.
4467 $internalchangeurl = new moodle_url('/login/change_password.php');
4468 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
4469 \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
4471 set_user_preference('auth_forcepasswordchange', 1, $user);
4472 } else if ($authplugin->can_reset_password()) {
4473 // Else force a reset if possible.
4474 \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
4475 redirect(new moodle_url('/login/forgot_password.php'));
4476 } else {
4477 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4478 // If support page is set, add link for help.
4479 if (!empty($CFG->supportpage)) {
4480 $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
4481 $link = \html_writer::tag('p', $link);
4482 $notifymsg .= $link;
4485 // If no change or reset is possible, add a notification for user.
4486 \core\notification::error($notifymsg);
4491 // Successful authentication.
4492 if ($user->id) {
4493 // User already exists in database.
4494 if (empty($user->auth)) {
4495 // For some reason auth isn't set yet.
4496 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4497 $user->auth = $auth;
4500 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4501 // the current hash algorithm while we have access to the user's password.
4502 update_internal_user_password($user, $password);
4504 if ($authplugin->is_synchronised_with_external()) {
4505 // Update user record from external DB.
4506 $user = update_user_record_by_id($user->id);
4508 } else {
4509 // The user is authenticated but user creation may be disabled.
4510 if (!empty($CFG->authpreventaccountcreation)) {
4511 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4513 // Trigger login failed event.
4514 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4515 'reason' => $failurereason)));
4516 $event->trigger();
4518 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4519 $_SERVER['HTTP_USER_AGENT']);
4520 return false;
4521 } else {
4522 $user = create_user_record($username, $password, $auth);
4526 $authplugin->sync_roles($user);
4528 foreach ($authsenabled as $hau) {
4529 $hauth = get_auth_plugin($hau);
4530 $hauth->user_authenticated_hook($user, $username, $password);
4533 if (empty($user->id)) {
4534 $failurereason = AUTH_LOGIN_NOUSER;
4535 // Trigger login failed event.
4536 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4537 'reason' => $failurereason)));
4538 $event->trigger();
4539 return false;
4542 if (!empty($user->suspended)) {
4543 // Just in case some auth plugin suspended account.
4544 $failurereason = AUTH_LOGIN_SUSPENDED;
4545 // Trigger login failed event.
4546 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4547 'other' => array('username' => $username, 'reason' => $failurereason)));
4548 $event->trigger();
4549 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4550 return false;
4553 login_attempt_valid($user);
4554 $failurereason = AUTH_LOGIN_OK;
4555 return $user;
4558 // Failed if all the plugins have failed.
4559 if (debugging('', DEBUG_ALL)) {
4560 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4563 if ($user->id) {
4564 login_attempt_failed($user);
4565 $failurereason = AUTH_LOGIN_FAILED;
4566 // Trigger login failed event.
4567 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4568 'other' => array('username' => $username, 'reason' => $failurereason)));
4569 $event->trigger();
4570 } else {
4571 $failurereason = AUTH_LOGIN_NOUSER;
4572 // Trigger login failed event.
4573 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4574 'reason' => $failurereason)));
4575 $event->trigger();
4578 return false;
4582 * Call to complete the user login process after authenticate_user_login()
4583 * has succeeded. It will setup the $USER variable and other required bits
4584 * and pieces.
4586 * NOTE:
4587 * - It will NOT log anything -- up to the caller to decide what to log.
4588 * - this function does not set any cookies any more!
4590 * @param stdClass $user
4591 * @param array $extrauserinfo
4592 * @return stdClass A {@link $USER} object - BC only, do not use
4594 function complete_user_login($user, array $extrauserinfo = []) {
4595 global $CFG, $DB, $USER, $SESSION;
4597 \core\session\manager::login_user($user);
4599 // Reload preferences from DB.
4600 unset($USER->preference);
4601 check_user_preferences_loaded($USER);
4603 // Update login times.
4604 update_user_login_times();
4606 // Extra session prefs init.
4607 set_login_session_preferences();
4609 // Trigger login event.
4610 $event = \core\event\user_loggedin::create(
4611 array(
4612 'userid' => $USER->id,
4613 'objectid' => $USER->id,
4614 'other' => [
4615 'username' => $USER->username,
4616 'extrauserinfo' => $extrauserinfo
4620 $event->trigger();
4622 // Check if the user is using a new browser or session (a new MoodleSession cookie is set in that case).
4623 // If the user is accessing from the same IP, ignore everything (most of the time will be a new session in the same browser).
4624 // Skip Web Service requests, CLI scripts, AJAX scripts, and request from the mobile app itself.
4625 $loginip = getremoteaddr();
4626 $isnewip = isset($SESSION->userpreviousip) && $SESSION->userpreviousip != $loginip;
4627 $isvalidenv = (!WS_SERVER && !CLI_SCRIPT && !NO_MOODLE_COOKIES) || PHPUNIT_TEST;
4629 if (!empty($SESSION->isnewsessioncookie) && $isnewip && $isvalidenv && !\core_useragent::is_moodle_app()) {
4631 $logintime = time();
4632 $ismoodleapp = false;
4633 $useragent = \core_useragent::get_user_agent_string();
4635 // Schedule adhoc task to sent a login notification to the user.
4636 $task = new \core\task\send_login_notifications();
4637 $task->set_userid($USER->id);
4638 $task->set_custom_data(compact('ismoodleapp', 'useragent', 'loginip', 'logintime'));
4639 $task->set_component('core');
4640 \core\task\manager::queue_adhoc_task($task);
4643 // Queue migrating the messaging data, if we need to.
4644 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4645 // Check if there are any legacy messages to migrate.
4646 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4647 \core_message\task\migrate_message_data::queue_task($USER->id);
4648 } else {
4649 set_user_preference('core_message_migrate_data', true, $USER->id);
4653 if (isguestuser()) {
4654 // No need to continue when user is THE guest.
4655 return $USER;
4658 if (CLI_SCRIPT) {
4659 // We can redirect to password change URL only in browser.
4660 return $USER;
4663 // Select password change url.
4664 $userauth = get_auth_plugin($USER->auth);
4666 // Check whether the user should be changing password.
4667 if (get_user_preferences('auth_forcepasswordchange', false)) {
4668 if ($userauth->can_change_password()) {
4669 if ($changeurl = $userauth->change_password_url()) {
4670 redirect($changeurl);
4671 } else {
4672 require_once($CFG->dirroot . '/login/lib.php');
4673 $SESSION->wantsurl = core_login_get_return_url();
4674 redirect($CFG->wwwroot.'/login/change_password.php');
4676 } else {
4677 throw new \moodle_exception('nopasswordchangeforced', 'auth');
4680 return $USER;
4684 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4686 * @param string $password String to check.
4687 * @return boolean True if the $password matches the format of an md5 sum.
4689 function password_is_legacy_hash($password) {
4690 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4694 * Compare password against hash stored in user object to determine if it is valid.
4696 * If necessary it also updates the stored hash to the current format.
4698 * @param stdClass $user (Password property may be updated).
4699 * @param string $password Plain text password.
4700 * @return bool True if password is valid.
4702 function validate_internal_user_password($user, $password) {
4703 global $CFG;
4705 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4706 // Internal password is not used at all, it can not validate.
4707 return false;
4710 // If hash isn't a legacy (md5) hash, validate using the library function.
4711 if (!password_is_legacy_hash($user->password)) {
4712 return password_verify($password, $user->password);
4715 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4716 // is valid we can then update it to the new algorithm.
4718 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4719 $validated = false;
4721 if ($user->password === md5($password.$sitesalt)
4722 or $user->password === md5($password)
4723 or $user->password === md5(addslashes($password).$sitesalt)
4724 or $user->password === md5(addslashes($password))) {
4725 // Note: we are intentionally using the addslashes() here because we
4726 // need to accept old password hashes of passwords with magic quotes.
4727 $validated = true;
4729 } else {
4730 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4731 $alt = 'passwordsaltalt'.$i;
4732 if (!empty($CFG->$alt)) {
4733 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4734 $validated = true;
4735 break;
4741 if ($validated) {
4742 // If the password matches the existing md5 hash, update to the
4743 // current hash algorithm while we have access to the user's password.
4744 update_internal_user_password($user, $password);
4747 return $validated;
4751 * Calculate hash for a plain text password.
4753 * @param string $password Plain text password to be hashed.
4754 * @param bool $fasthash If true, use a low cost factor when generating the hash
4755 * This is much faster to generate but makes the hash
4756 * less secure. It is used when lots of hashes need to
4757 * be generated quickly.
4758 * @return string The hashed password.
4760 * @throws moodle_exception If a problem occurs while generating the hash.
4762 function hash_internal_user_password($password, $fasthash = false) {
4763 global $CFG;
4765 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4766 $options = ($fasthash) ? array('cost' => 4) : array();
4768 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4770 if ($generatedhash === false || $generatedhash === null) {
4771 throw new moodle_exception('Failed to generate password hash.');
4774 return $generatedhash;
4778 * Update password hash in user object (if necessary).
4780 * The password is updated if:
4781 * 1. The password has changed (the hash of $user->password is different
4782 * to the hash of $password).
4783 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4784 * md5 algorithm).
4786 * Updating the password will modify the $user object and the database
4787 * record to use the current hashing algorithm.
4788 * It will remove Web Services user tokens too.
4790 * @param stdClass $user User object (password property may be updated).
4791 * @param string $password Plain text password.
4792 * @param bool $fasthash If true, use a low cost factor when generating the hash
4793 * This is much faster to generate but makes the hash
4794 * less secure. It is used when lots of hashes need to
4795 * be generated quickly.
4796 * @return bool Always returns true.
4798 function update_internal_user_password($user, $password, $fasthash = false) {
4799 global $CFG, $DB;
4801 // Figure out what the hashed password should be.
4802 if (!isset($user->auth)) {
4803 debugging('User record in update_internal_user_password() must include field auth',
4804 DEBUG_DEVELOPER);
4805 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4807 $authplugin = get_auth_plugin($user->auth);
4808 if ($authplugin->prevent_local_passwords()) {
4809 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4810 } else {
4811 $hashedpassword = hash_internal_user_password($password, $fasthash);
4814 $algorithmchanged = false;
4816 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4817 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4818 $passwordchanged = ($user->password !== $hashedpassword);
4820 } else if (isset($user->password)) {
4821 // If verification fails then it means the password has changed.
4822 $passwordchanged = !password_verify($password, $user->password);
4823 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4824 } else {
4825 // While creating new user, password in unset in $user object, to avoid
4826 // saving it with user_create()
4827 $passwordchanged = true;
4830 if ($passwordchanged || $algorithmchanged) {
4831 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4832 $user->password = $hashedpassword;
4834 // Trigger event.
4835 $user = $DB->get_record('user', array('id' => $user->id));
4836 \core\event\user_password_updated::create_from_user($user)->trigger();
4838 // Remove WS user tokens.
4839 if (!empty($CFG->passwordchangetokendeletion)) {
4840 require_once($CFG->dirroot.'/webservice/lib.php');
4841 webservice::delete_user_ws_tokens($user->id);
4845 return true;
4849 * Get a complete user record, which includes all the info in the user record.
4851 * Intended for setting as $USER session variable
4853 * @param string $field The user field to be checked for a given value.
4854 * @param string $value The value to match for $field.
4855 * @param int $mnethostid
4856 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4857 * found. Otherwise, it will just return false.
4858 * @return mixed False, or A {@link $USER} object.
4860 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4861 global $CFG, $DB;
4863 if (!$field || !$value) {
4864 return false;
4867 // Change the field to lowercase.
4868 $field = core_text::strtolower($field);
4870 // List of case insensitive fields.
4871 $caseinsensitivefields = ['email'];
4873 // Username input is forced to lowercase and should be case sensitive.
4874 if ($field == 'username') {
4875 $value = core_text::strtolower($value);
4878 // Build the WHERE clause for an SQL query.
4879 $params = array('fieldval' => $value);
4881 // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4882 // such as MySQL by pre-filtering users with accent-insensitive subselect.
4883 if (in_array($field, $caseinsensitivefields)) {
4884 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4885 $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4886 $params['fieldval2'] = $value;
4887 } else {
4888 $fieldselect = "$field = :fieldval";
4889 $idsubselect = '';
4891 $constraints = "$fieldselect AND deleted <> 1";
4893 // If we are loading user data based on anything other than id,
4894 // we must also restrict our search based on mnet host.
4895 if ($field != 'id') {
4896 if (empty($mnethostid)) {
4897 // If empty, we restrict to local users.
4898 $mnethostid = $CFG->mnet_localhost_id;
4901 if (!empty($mnethostid)) {
4902 $params['mnethostid'] = $mnethostid;
4903 $constraints .= " AND mnethostid = :mnethostid";
4906 if ($idsubselect) {
4907 $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4910 // Get all the basic user data.
4911 try {
4912 // Make sure that there's only a single record that matches our query.
4913 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4914 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4915 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4916 } catch (dml_exception $exception) {
4917 if ($throwexception) {
4918 throw $exception;
4919 } else {
4920 // Return false when no records or multiple records were found.
4921 return false;
4925 // Get various settings and preferences.
4927 // Preload preference cache.
4928 check_user_preferences_loaded($user);
4930 // Load course enrolment related stuff.
4931 $user->lastcourseaccess = array(); // During last session.
4932 $user->currentcourseaccess = array(); // During current session.
4933 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4934 foreach ($lastaccesses as $lastaccess) {
4935 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4939 // Add cohort theme.
4940 if (!empty($CFG->allowcohortthemes)) {
4941 require_once($CFG->dirroot . '/cohort/lib.php');
4942 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4943 $user->cohorttheme = $cohorttheme;
4947 // Add the custom profile fields to the user record.
4948 $user->profile = array();
4949 if (!isguestuser($user)) {
4950 require_once($CFG->dirroot.'/user/profile/lib.php');
4951 profile_load_custom_fields($user);
4954 // Rewrite some variables if necessary.
4955 if (!empty($user->description)) {
4956 // No need to cart all of it around.
4957 $user->description = true;
4959 if (isguestuser($user)) {
4960 // Guest language always same as site.
4961 $user->lang = get_newuser_language();
4962 // Name always in current language.
4963 $user->firstname = get_string('guestuser');
4964 $user->lastname = ' ';
4967 return $user;
4971 * Validate a password against the configured password policy
4973 * @param string $password the password to be checked against the password policy
4974 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4975 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
4977 * @return bool true if the password is valid according to the policy. false otherwise.
4979 function check_password_policy($password, &$errmsg, $user = null) {
4980 global $CFG;
4982 if (!empty($CFG->passwordpolicy)) {
4983 $errmsg = '';
4984 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4985 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4987 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4988 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4990 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4991 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4993 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4994 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4996 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4997 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4999 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
5000 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
5003 // Fire any additional password policy functions from plugins.
5004 // Plugin functions should output an error message string or empty string for success.
5005 $pluginsfunction = get_plugins_with_function('check_password_policy');
5006 foreach ($pluginsfunction as $plugintype => $plugins) {
5007 foreach ($plugins as $pluginfunction) {
5008 $pluginerr = $pluginfunction($password, $user);
5009 if ($pluginerr) {
5010 $errmsg .= '<div>'. $pluginerr .'</div>';
5016 if ($errmsg == '') {
5017 return true;
5018 } else {
5019 return false;
5025 * When logging in, this function is run to set certain preferences for the current SESSION.
5027 function set_login_session_preferences() {
5028 global $SESSION;
5030 $SESSION->justloggedin = true;
5032 unset($SESSION->lang);
5033 unset($SESSION->forcelang);
5034 unset($SESSION->load_navigation_admin);
5039 * Delete a course, including all related data from the database, and any associated files.
5041 * @param mixed $courseorid The id of the course or course object to delete.
5042 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5043 * @return bool true if all the removals succeeded. false if there were any failures. If this
5044 * method returns false, some of the removals will probably have succeeded, and others
5045 * failed, but you have no way of knowing which.
5047 function delete_course($courseorid, $showfeedback = true) {
5048 global $DB;
5050 if (is_object($courseorid)) {
5051 $courseid = $courseorid->id;
5052 $course = $courseorid;
5053 } else {
5054 $courseid = $courseorid;
5055 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5056 return false;
5059 $context = context_course::instance($courseid);
5061 // Frontpage course can not be deleted!!
5062 if ($courseid == SITEID) {
5063 return false;
5066 // Allow plugins to use this course before we completely delete it.
5067 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5068 foreach ($pluginsfunction as $plugintype => $plugins) {
5069 foreach ($plugins as $pluginfunction) {
5070 $pluginfunction($course);
5075 // Tell the search manager we are about to delete a course. This prevents us sending updates
5076 // for each individual context being deleted.
5077 \core_search\manager::course_deleting_start($courseid);
5079 $handler = core_course\customfield\course_handler::create();
5080 $handler->delete_instance($courseid);
5082 // Make the course completely empty.
5083 remove_course_contents($courseid, $showfeedback);
5085 // Delete the course and related context instance.
5086 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5088 $DB->delete_records("course", array("id" => $courseid));
5089 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5091 // Reset all course related caches here.
5092 core_courseformat\base::reset_course_cache($courseid);
5094 // Tell search that we have deleted the course so it can delete course data from the index.
5095 \core_search\manager::course_deleting_finish($courseid);
5097 // Trigger a course deleted event.
5098 $event = \core\event\course_deleted::create(array(
5099 'objectid' => $course->id,
5100 'context' => $context,
5101 'other' => array(
5102 'shortname' => $course->shortname,
5103 'fullname' => $course->fullname,
5104 'idnumber' => $course->idnumber
5107 $event->add_record_snapshot('course', $course);
5108 $event->trigger();
5110 return true;
5114 * Clear a course out completely, deleting all content but don't delete the course itself.
5116 * This function does not verify any permissions.
5118 * Please note this function also deletes all user enrolments,
5119 * enrolment instances and role assignments by default.
5121 * $options:
5122 * - 'keep_roles_and_enrolments' - false by default
5123 * - 'keep_groups_and_groupings' - false by default
5125 * @param int $courseid The id of the course that is being deleted
5126 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5127 * @param array $options extra options
5128 * @return bool true if all the removals succeeded. false if there were any failures. If this
5129 * method returns false, some of the removals will probably have succeeded, and others
5130 * failed, but you have no way of knowing which.
5132 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5133 global $CFG, $DB, $OUTPUT;
5135 require_once($CFG->libdir.'/badgeslib.php');
5136 require_once($CFG->libdir.'/completionlib.php');
5137 require_once($CFG->libdir.'/questionlib.php');
5138 require_once($CFG->libdir.'/gradelib.php');
5139 require_once($CFG->dirroot.'/group/lib.php');
5140 require_once($CFG->dirroot.'/comment/lib.php');
5141 require_once($CFG->dirroot.'/rating/lib.php');
5142 require_once($CFG->dirroot.'/notes/lib.php');
5144 // Handle course badges.
5145 badges_handle_course_deletion($courseid);
5147 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5148 $strdeleted = get_string('deleted').' - ';
5150 // Some crazy wishlist of stuff we should skip during purging of course content.
5151 $options = (array)$options;
5153 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5154 $coursecontext = context_course::instance($courseid);
5155 $fs = get_file_storage();
5157 // Delete course completion information, this has to be done before grades and enrols.
5158 $cc = new completion_info($course);
5159 $cc->clear_criteria();
5160 if ($showfeedback) {
5161 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5164 // Remove all data from gradebook - this needs to be done before course modules
5165 // because while deleting this information, the system may need to reference
5166 // the course modules that own the grades.
5167 remove_course_grades($courseid, $showfeedback);
5168 remove_grade_letters($coursecontext, $showfeedback);
5170 // Delete course blocks in any all child contexts,
5171 // they may depend on modules so delete them first.
5172 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5173 foreach ($childcontexts as $childcontext) {
5174 blocks_delete_all_for_context($childcontext->id);
5176 unset($childcontexts);
5177 blocks_delete_all_for_context($coursecontext->id);
5178 if ($showfeedback) {
5179 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5182 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
5183 rebuild_course_cache($courseid, true);
5185 // Get the list of all modules that are properly installed.
5186 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5188 // Delete every instance of every module,
5189 // this has to be done before deleting of course level stuff.
5190 $locations = core_component::get_plugin_list('mod');
5191 foreach ($locations as $modname => $moddir) {
5192 if ($modname === 'NEWMODULE') {
5193 continue;
5195 if (array_key_exists($modname, $allmodules)) {
5196 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5197 FROM {".$modname."} m
5198 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5199 WHERE m.course = :courseid";
5200 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5201 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5203 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5204 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5206 if ($instances) {
5207 foreach ($instances as $cm) {
5208 if ($cm->id) {
5209 // Delete activity context questions and question categories.
5210 question_delete_activity($cm);
5211 // Notify the competency subsystem.
5212 \core_competency\api::hook_course_module_deleted($cm);
5214 // Delete all tag instances associated with the instance of this module.
5215 core_tag_tag::delete_instances("mod_{$modname}", null, context_module::instance($cm->id)->id);
5216 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
5218 if (function_exists($moddelete)) {
5219 // This purges all module data in related tables, extra user prefs, settings, etc.
5220 $moddelete($cm->modinstance);
5221 } else {
5222 // NOTE: we should not allow installation of modules with missing delete support!
5223 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5224 $DB->delete_records($modname, array('id' => $cm->modinstance));
5227 if ($cm->id) {
5228 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5229 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5230 $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id]);
5231 $DB->delete_records('course_modules_viewed', ['coursemoduleid' => $cm->id]);
5232 $DB->delete_records('course_modules', array('id' => $cm->id));
5233 rebuild_course_cache($cm->course, true);
5237 if ($instances and $showfeedback) {
5238 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5240 } else {
5241 // Ooops, this module is not properly installed, force-delete it in the next block.
5245 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5247 // Delete completion defaults.
5248 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5250 // Remove all data from availability and completion tables that is associated
5251 // with course-modules belonging to this course. Note this is done even if the
5252 // features are not enabled now, in case they were enabled previously.
5253 $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
5254 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5255 $DB->delete_records_subquery('course_modules_viewed', 'coursemoduleid', 'id',
5256 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5258 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5259 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5260 $allmodulesbyid = array_flip($allmodules);
5261 foreach ($cms as $cm) {
5262 if (array_key_exists($cm->module, $allmodulesbyid)) {
5263 try {
5264 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5265 } catch (Exception $e) {
5266 // Ignore weird or missing table problems.
5269 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5270 $DB->delete_records('course_modules', array('id' => $cm->id));
5271 rebuild_course_cache($cm->course, true);
5274 if ($showfeedback) {
5275 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5278 // Delete questions and question categories.
5279 question_delete_course($course);
5280 if ($showfeedback) {
5281 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5284 // Delete content bank contents.
5285 $cb = new \core_contentbank\contentbank();
5286 $cbdeleted = $cb->delete_contents($coursecontext);
5287 if ($showfeedback && $cbdeleted) {
5288 echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5291 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5292 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5293 foreach ($childcontexts as $childcontext) {
5294 $childcontext->delete();
5296 unset($childcontexts);
5298 // Remove roles and enrolments by default.
5299 if (empty($options['keep_roles_and_enrolments'])) {
5300 // This hack is used in restore when deleting contents of existing course.
5301 // During restore, we should remove only enrolment related data that the user performing the restore has a
5302 // permission to remove.
5303 $userid = $options['userid'] ?? null;
5304 enrol_course_delete($course, $userid);
5305 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5306 if ($showfeedback) {
5307 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5311 // Delete any groups, removing members and grouping/course links first.
5312 if (empty($options['keep_groups_and_groupings'])) {
5313 groups_delete_groupings($course->id, $showfeedback);
5314 groups_delete_groups($course->id, $showfeedback);
5317 // Filters be gone!
5318 filter_delete_all_for_context($coursecontext->id);
5320 // Notes, you shall not pass!
5321 note_delete_all($course->id);
5323 // Die comments!
5324 comment::delete_comments($coursecontext->id);
5326 // Ratings are history too.
5327 $delopt = new stdclass();
5328 $delopt->contextid = $coursecontext->id;
5329 $rm = new rating_manager();
5330 $rm->delete_ratings($delopt);
5332 // Delete course tags.
5333 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5335 // Give the course format the opportunity to remove its obscure data.
5336 $format = course_get_format($course);
5337 $format->delete_format_data();
5339 // Notify the competency subsystem.
5340 \core_competency\api::hook_course_deleted($course);
5342 // Delete calendar events.
5343 $DB->delete_records('event', array('courseid' => $course->id));
5344 $fs->delete_area_files($coursecontext->id, 'calendar');
5346 // Delete all related records in other core tables that may have a courseid
5347 // This array stores the tables that need to be cleared, as
5348 // table_name => column_name that contains the course id.
5349 $tablestoclear = array(
5350 'backup_courses' => 'courseid', // Scheduled backup stuff.
5351 'user_lastaccess' => 'courseid', // User access info.
5353 foreach ($tablestoclear as $table => $col) {
5354 $DB->delete_records($table, array($col => $course->id));
5357 // Delete all course backup files.
5358 $fs->delete_area_files($coursecontext->id, 'backup');
5360 // Cleanup course record - remove links to deleted stuff.
5361 $oldcourse = new stdClass();
5362 $oldcourse->id = $course->id;
5363 $oldcourse->summary = '';
5364 $oldcourse->cacherev = 0;
5365 $oldcourse->legacyfiles = 0;
5366 if (!empty($options['keep_groups_and_groupings'])) {
5367 $oldcourse->defaultgroupingid = 0;
5369 $DB->update_record('course', $oldcourse);
5371 // Delete course sections.
5372 $DB->delete_records('course_sections', array('course' => $course->id));
5374 // Delete legacy, section and any other course files.
5375 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5377 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5378 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5379 // Easy, do not delete the context itself...
5380 $coursecontext->delete_content();
5381 } else {
5382 // Hack alert!!!!
5383 // We can not drop all context stuff because it would bork enrolments and roles,
5384 // there might be also files used by enrol plugins...
5387 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5388 // also some non-standard unsupported plugins may try to store something there.
5389 fulldelete($CFG->dataroot.'/'.$course->id);
5391 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5392 course_modinfo::purge_course_cache($courseid);
5394 // Trigger a course content deleted event.
5395 $event = \core\event\course_content_deleted::create(array(
5396 'objectid' => $course->id,
5397 'context' => $coursecontext,
5398 'other' => array('shortname' => $course->shortname,
5399 'fullname' => $course->fullname,
5400 'options' => $options) // Passing this for legacy reasons.
5402 $event->add_record_snapshot('course', $course);
5403 $event->trigger();
5405 return true;
5409 * Change dates in module - used from course reset.
5411 * @param string $modname forum, assignment, etc
5412 * @param array $fields array of date fields from mod table
5413 * @param int $timeshift time difference
5414 * @param int $courseid
5415 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5416 * @return bool success
5418 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5419 global $CFG, $DB;
5420 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5422 $return = true;
5423 $params = array($timeshift, $courseid);
5424 foreach ($fields as $field) {
5425 $updatesql = "UPDATE {".$modname."}
5426 SET $field = $field + ?
5427 WHERE course=? AND $field<>0";
5428 if ($modid) {
5429 $updatesql .= ' AND id=?';
5430 $params[] = $modid;
5432 $return = $DB->execute($updatesql, $params) && $return;
5435 return $return;
5439 * This function will empty a course of user data.
5440 * It will retain the activities and the structure of the course.
5442 * @param object $data an object containing all the settings including courseid (without magic quotes)
5443 * @return array status array of array component, item, error
5445 function reset_course_userdata($data) {
5446 global $CFG, $DB;
5447 require_once($CFG->libdir.'/gradelib.php');
5448 require_once($CFG->libdir.'/completionlib.php');
5449 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5450 require_once($CFG->dirroot.'/group/lib.php');
5452 $data->courseid = $data->id;
5453 $context = context_course::instance($data->courseid);
5455 $eventparams = array(
5456 'context' => $context,
5457 'courseid' => $data->id,
5458 'other' => array(
5459 'reset_options' => (array) $data
5462 $event = \core\event\course_reset_started::create($eventparams);
5463 $event->trigger();
5465 // Calculate the time shift of dates.
5466 if (!empty($data->reset_start_date)) {
5467 // Time part of course startdate should be zero.
5468 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5469 } else {
5470 $data->timeshift = 0;
5473 // Result array: component, item, error.
5474 $status = array();
5476 // Start the resetting.
5477 $componentstr = get_string('general');
5479 // Move the course start time.
5480 if (!empty($data->reset_start_date) and $data->timeshift) {
5481 // Change course start data.
5482 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5483 // Update all course and group events - do not move activity events.
5484 $updatesql = "UPDATE {event}
5485 SET timestart = timestart + ?
5486 WHERE courseid=? AND instance=0";
5487 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5489 // Update any date activity restrictions.
5490 if ($CFG->enableavailability) {
5491 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5494 // Update completion expected dates.
5495 if ($CFG->enablecompletion) {
5496 $modinfo = get_fast_modinfo($data->courseid);
5497 $changed = false;
5498 foreach ($modinfo->get_cms() as $cm) {
5499 if ($cm->completion && !empty($cm->completionexpected)) {
5500 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5501 array('id' => $cm->id));
5502 $changed = true;
5506 // Clear course cache if changes made.
5507 if ($changed) {
5508 rebuild_course_cache($data->courseid, true);
5511 // Update course date completion criteria.
5512 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5515 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5518 if (!empty($data->reset_end_date)) {
5519 // If the user set a end date value respect it.
5520 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5521 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5522 // If there is a time shift apply it to the end date as well.
5523 $enddate = $data->reset_end_date_old + $data->timeshift;
5524 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5527 if (!empty($data->reset_events)) {
5528 $DB->delete_records('event', array('courseid' => $data->courseid));
5529 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5532 if (!empty($data->reset_notes)) {
5533 require_once($CFG->dirroot.'/notes/lib.php');
5534 note_delete_all($data->courseid);
5535 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5538 if (!empty($data->delete_blog_associations)) {
5539 require_once($CFG->dirroot.'/blog/lib.php');
5540 blog_remove_associations_for_course($data->courseid);
5541 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5544 if (!empty($data->reset_completion)) {
5545 // Delete course and activity completion information.
5546 $course = $DB->get_record('course', array('id' => $data->courseid));
5547 $cc = new completion_info($course);
5548 $cc->delete_all_completion_data();
5549 $status[] = array('component' => $componentstr,
5550 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5553 if (!empty($data->reset_competency_ratings)) {
5554 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5555 $status[] = array('component' => $componentstr,
5556 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5559 $componentstr = get_string('roles');
5561 if (!empty($data->reset_roles_overrides)) {
5562 $children = $context->get_child_contexts();
5563 foreach ($children as $child) {
5564 $child->delete_capabilities();
5566 $context->delete_capabilities();
5567 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5570 if (!empty($data->reset_roles_local)) {
5571 $children = $context->get_child_contexts();
5572 foreach ($children as $child) {
5573 role_unassign_all(array('contextid' => $child->id));
5575 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5578 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5579 $data->unenrolled = array();
5580 if (!empty($data->unenrol_users)) {
5581 $plugins = enrol_get_plugins(true);
5582 $instances = enrol_get_instances($data->courseid, true);
5583 foreach ($instances as $key => $instance) {
5584 if (!isset($plugins[$instance->enrol])) {
5585 unset($instances[$key]);
5586 continue;
5590 $usersroles = enrol_get_course_users_roles($data->courseid);
5591 foreach ($data->unenrol_users as $withroleid) {
5592 if ($withroleid) {
5593 $sql = "SELECT ue.*
5594 FROM {user_enrolments} ue
5595 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5596 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5597 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5598 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5600 } else {
5601 // Without any role assigned at course context.
5602 $sql = "SELECT ue.*
5603 FROM {user_enrolments} ue
5604 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5605 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5606 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5607 WHERE ra.id IS null";
5608 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5611 $rs = $DB->get_recordset_sql($sql, $params);
5612 foreach ($rs as $ue) {
5613 if (!isset($instances[$ue->enrolid])) {
5614 continue;
5616 $instance = $instances[$ue->enrolid];
5617 $plugin = $plugins[$instance->enrol];
5618 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5619 continue;
5622 if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5623 // If we don't remove all roles and user has more than one role, just remove this role.
5624 role_unassign($withroleid, $ue->userid, $context->id);
5626 unset($usersroles[$ue->userid][$withroleid]);
5627 } else {
5628 // If we remove all roles or user has only one role, unenrol user from course.
5629 $plugin->unenrol_user($instance, $ue->userid);
5631 $data->unenrolled[$ue->userid] = $ue->userid;
5633 $rs->close();
5636 if (!empty($data->unenrolled)) {
5637 $status[] = array(
5638 'component' => $componentstr,
5639 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5640 'error' => false
5644 $componentstr = get_string('groups');
5646 // Remove all group members.
5647 if (!empty($data->reset_groups_members)) {
5648 groups_delete_group_members($data->courseid);
5649 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5652 // Remove all groups.
5653 if (!empty($data->reset_groups_remove)) {
5654 groups_delete_groups($data->courseid, false);
5655 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5658 // Remove all grouping members.
5659 if (!empty($data->reset_groupings_members)) {
5660 groups_delete_groupings_groups($data->courseid, false);
5661 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5664 // Remove all groupings.
5665 if (!empty($data->reset_groupings_remove)) {
5666 groups_delete_groupings($data->courseid, false);
5667 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5670 // Look in every instance of every module for data to delete.
5671 $unsupportedmods = array();
5672 if ($allmods = $DB->get_records('modules') ) {
5673 foreach ($allmods as $mod) {
5674 $modname = $mod->name;
5675 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5676 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5677 if (file_exists($modfile)) {
5678 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5679 continue; // Skip mods with no instances.
5681 include_once($modfile);
5682 if (function_exists($moddeleteuserdata)) {
5683 $modstatus = $moddeleteuserdata($data);
5684 if (is_array($modstatus)) {
5685 $status = array_merge($status, $modstatus);
5686 } else {
5687 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5689 } else {
5690 $unsupportedmods[] = $mod;
5692 } else {
5693 debugging('Missing lib.php in '.$modname.' module!');
5695 // Update calendar events for all modules.
5696 course_module_bulk_update_calendar_events($modname, $data->courseid);
5700 // Mention unsupported mods.
5701 if (!empty($unsupportedmods)) {
5702 foreach ($unsupportedmods as $mod) {
5703 $status[] = array(
5704 'component' => get_string('modulenameplural', $mod->name),
5705 'item' => '',
5706 'error' => get_string('resetnotimplemented')
5711 $componentstr = get_string('gradebook', 'grades');
5712 // Reset gradebook,.
5713 if (!empty($data->reset_gradebook_items)) {
5714 remove_course_grades($data->courseid, false);
5715 grade_grab_course_grades($data->courseid);
5716 grade_regrade_final_grades($data->courseid);
5717 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5719 } else if (!empty($data->reset_gradebook_grades)) {
5720 grade_course_reset($data->courseid);
5721 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5723 // Reset comments.
5724 if (!empty($data->reset_comments)) {
5725 require_once($CFG->dirroot.'/comment/lib.php');
5726 comment::reset_course_page_comments($context);
5729 $event = \core\event\course_reset_ended::create($eventparams);
5730 $event->trigger();
5732 return $status;
5736 * Generate an email processing address.
5738 * @param int $modid
5739 * @param string $modargs
5740 * @return string Returns email processing address
5742 function generate_email_processing_address($modid, $modargs) {
5743 global $CFG;
5745 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5746 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5752 * @todo Finish documenting this function
5754 * @param string $modargs
5755 * @param string $body Currently unused
5757 function moodle_process_email($modargs, $body) {
5758 global $DB;
5760 // The first char should be an unencoded letter. We'll take this as an action.
5761 switch ($modargs[0]) {
5762 case 'B': { // Bounce.
5763 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5764 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5765 // Check the half md5 of their email.
5766 $md5check = substr(md5($user->email), 0, 16);
5767 if ($md5check == substr($modargs, -16)) {
5768 set_bounce_count($user);
5770 // Else maybe they've already changed it?
5773 break;
5774 // Maybe more later?
5778 // CORRESPONDENCE.
5781 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5783 * @param string $action 'get', 'buffer', 'close' or 'flush'
5784 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5786 function get_mailer($action='get') {
5787 global $CFG;
5789 /** @var moodle_phpmailer $mailer */
5790 static $mailer = null;
5791 static $counter = 0;
5793 if (!isset($CFG->smtpmaxbulk)) {
5794 $CFG->smtpmaxbulk = 1;
5797 if ($action == 'get') {
5798 $prevkeepalive = false;
5800 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5801 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5802 $counter++;
5803 // Reset the mailer.
5804 $mailer->Priority = 3;
5805 $mailer->CharSet = 'UTF-8'; // Our default.
5806 $mailer->ContentType = "text/plain";
5807 $mailer->Encoding = "8bit";
5808 $mailer->From = "root@localhost";
5809 $mailer->FromName = "Root User";
5810 $mailer->Sender = "";
5811 $mailer->Subject = "";
5812 $mailer->Body = "";
5813 $mailer->AltBody = "";
5814 $mailer->ConfirmReadingTo = "";
5816 $mailer->clearAllRecipients();
5817 $mailer->clearReplyTos();
5818 $mailer->clearAttachments();
5819 $mailer->clearCustomHeaders();
5820 return $mailer;
5823 $prevkeepalive = $mailer->SMTPKeepAlive;
5824 get_mailer('flush');
5827 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5828 $mailer = new moodle_phpmailer();
5830 $counter = 1;
5832 if ($CFG->smtphosts == 'qmail') {
5833 // Use Qmail system.
5834 $mailer->isQmail();
5836 } else if (empty($CFG->smtphosts)) {
5837 // Use PHP mail() = sendmail.
5838 $mailer->isMail();
5840 } else {
5841 // Use SMTP directly.
5842 $mailer->isSMTP();
5843 if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5844 $mailer->SMTPDebug = 3;
5846 // Specify main and backup servers.
5847 $mailer->Host = $CFG->smtphosts;
5848 // Specify secure connection protocol.
5849 $mailer->SMTPSecure = $CFG->smtpsecure;
5850 // Use previous keepalive.
5851 $mailer->SMTPKeepAlive = $prevkeepalive;
5853 if ($CFG->smtpuser) {
5854 // Use SMTP authentication.
5855 $mailer->SMTPAuth = true;
5856 $mailer->Username = $CFG->smtpuser;
5857 $mailer->Password = $CFG->smtppass;
5861 return $mailer;
5864 $nothing = null;
5866 // Keep smtp session open after sending.
5867 if ($action == 'buffer') {
5868 if (!empty($CFG->smtpmaxbulk)) {
5869 get_mailer('flush');
5870 $m = get_mailer();
5871 if ($m->Mailer == 'smtp') {
5872 $m->SMTPKeepAlive = true;
5875 return $nothing;
5878 // Close smtp session, but continue buffering.
5879 if ($action == 'flush') {
5880 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5881 if (!empty($mailer->SMTPDebug)) {
5882 echo '<pre>'."\n";
5884 $mailer->SmtpClose();
5885 if (!empty($mailer->SMTPDebug)) {
5886 echo '</pre>';
5889 return $nothing;
5892 // Close smtp session, do not buffer anymore.
5893 if ($action == 'close') {
5894 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5895 get_mailer('flush');
5896 $mailer->SMTPKeepAlive = false;
5898 $mailer = null; // Better force new instance.
5899 return $nothing;
5904 * A helper function to test for email diversion
5906 * @param string $email
5907 * @return bool Returns true if the email should be diverted
5909 function email_should_be_diverted($email) {
5910 global $CFG;
5912 if (empty($CFG->divertallemailsto)) {
5913 return false;
5916 if (empty($CFG->divertallemailsexcept)) {
5917 return true;
5920 $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept, -1, PREG_SPLIT_NO_EMPTY));
5921 foreach ($patterns as $pattern) {
5922 if (preg_match("/$pattern/", $email)) {
5923 return false;
5927 return true;
5931 * Generate a unique email Message-ID using the moodle domain and install path
5933 * @param string $localpart An optional unique message id prefix.
5934 * @return string The formatted ID ready for appending to the email headers.
5936 function generate_email_messageid($localpart = null) {
5937 global $CFG;
5939 $urlinfo = parse_url($CFG->wwwroot);
5940 $base = '@' . $urlinfo['host'];
5942 // If multiple moodles are on the same domain we want to tell them
5943 // apart so we add the install path to the local part. This means
5944 // that the id local part should never contain a / character so
5945 // we can correctly parse the id to reassemble the wwwroot.
5946 if (isset($urlinfo['path'])) {
5947 $base = $urlinfo['path'] . $base;
5950 if (empty($localpart)) {
5951 $localpart = uniqid('', true);
5954 // Because we may have an option /installpath suffix to the local part
5955 // of the id we need to escape any / chars which are in the $localpart.
5956 $localpart = str_replace('/', '%2F', $localpart);
5958 return '<' . $localpart . $base . '>';
5962 * Send an email to a specified user
5964 * @param stdClass $user A {@link $USER} object
5965 * @param stdClass $from A {@link $USER} object
5966 * @param string $subject plain text subject line of the email
5967 * @param string $messagetext plain text version of the message
5968 * @param string $messagehtml complete html version of the message (optional)
5969 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
5970 * the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
5971 * @param string $attachname the name of the file (extension indicates MIME)
5972 * @param bool $usetrueaddress determines whether $from email address should
5973 * be sent out. Will be overruled by user profile setting for maildisplay
5974 * @param string $replyto Email address to reply to
5975 * @param string $replytoname Name of reply to recipient
5976 * @param int $wordwrapwidth custom word wrap width, default 79
5977 * @return bool Returns true if mail was sent OK and false if there was an error.
5979 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5980 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5982 global $CFG, $PAGE, $SITE;
5984 if (empty($user) or empty($user->id)) {
5985 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5986 return false;
5989 if (empty($user->email)) {
5990 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5991 return false;
5994 if (!empty($user->deleted)) {
5995 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5996 return false;
5999 if (defined('BEHAT_SITE_RUNNING')) {
6000 // Fake email sending in behat.
6001 return true;
6004 if (!empty($CFG->noemailever)) {
6005 // Hidden setting for development sites, set in config.php if needed.
6006 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
6007 return true;
6010 if (email_should_be_diverted($user->email)) {
6011 $subject = "[DIVERTED {$user->email}] $subject";
6012 $user = clone($user);
6013 $user->email = $CFG->divertallemailsto;
6016 // Skip mail to suspended users.
6017 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
6018 return true;
6021 if (!validate_email($user->email)) {
6022 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
6023 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
6024 return false;
6027 if (over_bounce_threshold($user)) {
6028 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
6029 return false;
6032 // TLD .invalid is specifically reserved for invalid domain names.
6033 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
6034 if (substr($user->email, -8) == '.invalid') {
6035 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
6036 return true; // This is not an error.
6039 // If the user is a remote mnet user, parse the email text for URL to the
6040 // wwwroot and modify the url to direct the user's browser to login at their
6041 // home site (identity provider - idp) before hitting the link itself.
6042 if (is_mnet_remote_user($user)) {
6043 require_once($CFG->dirroot.'/mnet/lib.php');
6045 $jumpurl = mnet_get_idp_jump_url($user);
6046 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
6048 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
6049 $callback,
6050 $messagetext);
6051 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
6052 $callback,
6053 $messagehtml);
6055 $mail = get_mailer();
6057 if (!empty($mail->SMTPDebug)) {
6058 echo '<pre>' . "\n";
6061 $temprecipients = array();
6062 $tempreplyto = array();
6064 // Make sure that we fall back onto some reasonable no-reply address.
6065 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
6066 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
6068 if (!validate_email($noreplyaddress)) {
6069 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6070 $noreplyaddress = $noreplyaddressdefault;
6073 // Make up an email address for handling bounces.
6074 if (!empty($CFG->handlebounces)) {
6075 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
6076 $mail->Sender = generate_email_processing_address(0, $modargs);
6077 } else {
6078 $mail->Sender = $noreplyaddress;
6081 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6082 if (!empty($replyto) && !validate_email($replyto)) {
6083 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6084 $replyto = $noreplyaddress;
6087 if (is_string($from)) { // So we can pass whatever we want if there is need.
6088 $mail->From = $noreplyaddress;
6089 $mail->FromName = $from;
6090 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6091 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6092 // in a course with the sender.
6093 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6094 if (!validate_email($from->email)) {
6095 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
6096 // Better not to use $noreplyaddress in this case.
6097 return false;
6099 $mail->From = $from->email;
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_ALWAYS) {
6106 $fromstring = get_string('emailvia', 'core', $fromdetails);
6108 $mail->FromName = $fromstring;
6109 if (empty($replyto)) {
6110 $tempreplyto[] = array($from->email, fullname($from));
6112 } else {
6113 $mail->From = $noreplyaddress;
6114 $fromdetails = new stdClass();
6115 $fromdetails->name = fullname($from);
6116 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6117 $fromdetails->siteshortname = format_string($SITE->shortname);
6118 $fromstring = $fromdetails->name;
6119 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
6120 $fromstring = get_string('emailvia', 'core', $fromdetails);
6122 $mail->FromName = $fromstring;
6123 if (empty($replyto)) {
6124 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6128 if (!empty($replyto)) {
6129 $tempreplyto[] = array($replyto, $replytoname);
6132 $temprecipients[] = array($user->email, fullname($user));
6134 // Set word wrap.
6135 $mail->WordWrap = $wordwrapwidth;
6137 if (!empty($from->customheaders)) {
6138 // Add custom headers.
6139 if (is_array($from->customheaders)) {
6140 foreach ($from->customheaders as $customheader) {
6141 $mail->addCustomHeader($customheader);
6143 } else {
6144 $mail->addCustomHeader($from->customheaders);
6148 // If the X-PHP-Originating-Script email header is on then also add an additional
6149 // header with details of where exactly in moodle the email was triggered from,
6150 // either a call to message_send() or to email_to_user().
6151 if (ini_get('mail.add_x_header')) {
6153 $stack = debug_backtrace(false);
6154 $origin = $stack[0];
6156 foreach ($stack as $depth => $call) {
6157 if ($call['function'] == 'message_send') {
6158 $origin = $call;
6162 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6163 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6164 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6167 if (!empty($CFG->emailheaders)) {
6168 $headers = array_map('trim', explode("\n", $CFG->emailheaders));
6169 foreach ($headers as $header) {
6170 if (!empty($header)) {
6171 $mail->addCustomHeader($header);
6176 if (!empty($from->priority)) {
6177 $mail->Priority = $from->priority;
6180 $renderer = $PAGE->get_renderer('core');
6181 $context = array(
6182 'sitefullname' => $SITE->fullname,
6183 'siteshortname' => $SITE->shortname,
6184 'sitewwwroot' => $CFG->wwwroot,
6185 'subject' => $subject,
6186 'prefix' => $CFG->emailsubjectprefix,
6187 'to' => $user->email,
6188 'toname' => fullname($user),
6189 'from' => $mail->From,
6190 'fromname' => $mail->FromName,
6192 if (!empty($tempreplyto[0])) {
6193 $context['replyto'] = $tempreplyto[0][0];
6194 $context['replytoname'] = $tempreplyto[0][1];
6196 if ($user->id > 0) {
6197 $context['touserid'] = $user->id;
6198 $context['tousername'] = $user->username;
6201 if (!empty($user->mailformat) && $user->mailformat == 1) {
6202 // Only process html templates if the user preferences allow html email.
6204 if (!$messagehtml) {
6205 // If no html has been given, BUT there is an html wrapping template then
6206 // auto convert the text to html and then wrap it.
6207 $messagehtml = trim(text_to_html($messagetext));
6209 $context['body'] = $messagehtml;
6210 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6213 $context['body'] = html_to_text(nl2br($messagetext));
6214 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6215 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6216 $messagetext = $renderer->render_from_template('core/email_text', $context);
6218 // Autogenerate a MessageID if it's missing.
6219 if (empty($mail->MessageID)) {
6220 $mail->MessageID = generate_email_messageid();
6223 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6224 // Don't ever send HTML to users who don't want it.
6225 $mail->isHTML(true);
6226 $mail->Encoding = 'quoted-printable';
6227 $mail->Body = $messagehtml;
6228 $mail->AltBody = "\n$messagetext\n";
6229 } else {
6230 $mail->IsHTML(false);
6231 $mail->Body = "\n$messagetext\n";
6234 if ($attachment && $attachname) {
6235 if (preg_match( "~\\.\\.~" , $attachment )) {
6236 // Security check for ".." in dir path.
6237 $supportuser = core_user::get_support_user();
6238 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6239 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6240 } else {
6241 require_once($CFG->libdir.'/filelib.php');
6242 $mimetype = mimeinfo('type', $attachname);
6244 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6245 // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
6246 $attachpath = str_replace('\\', '/', realpath($attachment));
6248 // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
6249 $allowedpaths = array_map(function(string $path): string {
6250 return str_replace('\\', '/', realpath($path));
6251 }, [
6252 $CFG->cachedir,
6253 $CFG->dataroot,
6254 $CFG->dirroot,
6255 $CFG->localcachedir,
6256 $CFG->tempdir,
6257 $CFG->localrequestdir,
6260 // Set addpath to true.
6261 $addpath = true;
6263 // Check if attachment includes one of the allowed paths.
6264 foreach (array_filter($allowedpaths) as $allowedpath) {
6265 // Set addpath to false if the attachment includes one of the allowed paths.
6266 if (strpos($attachpath, $allowedpath) === 0) {
6267 $addpath = false;
6268 break;
6272 // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
6273 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6274 if ($addpath == true) {
6275 $attachment = $CFG->dataroot . '/' . $attachment;
6278 $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
6282 // Check if the email should be sent in an other charset then the default UTF-8.
6283 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6285 // Use the defined site mail charset or eventually the one preferred by the recipient.
6286 $charset = $CFG->sitemailcharset;
6287 if (!empty($CFG->allowusermailcharset)) {
6288 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6289 $charset = $useremailcharset;
6293 // Convert all the necessary strings if the charset is supported.
6294 $charsets = get_list_of_charsets();
6295 unset($charsets['UTF-8']);
6296 if (in_array($charset, $charsets)) {
6297 $mail->CharSet = $charset;
6298 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6299 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6300 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6301 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6303 foreach ($temprecipients as $key => $values) {
6304 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6306 foreach ($tempreplyto as $key => $values) {
6307 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6312 foreach ($temprecipients as $values) {
6313 $mail->addAddress($values[0], $values[1]);
6315 foreach ($tempreplyto as $values) {
6316 $mail->addReplyTo($values[0], $values[1]);
6319 if (!empty($CFG->emaildkimselector)) {
6320 $domain = substr(strrchr($mail->From, "@"), 1);
6321 $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
6322 if (file_exists($pempath)) {
6323 $mail->DKIM_domain = $domain;
6324 $mail->DKIM_private = $pempath;
6325 $mail->DKIM_selector = $CFG->emaildkimselector;
6326 $mail->DKIM_identity = $mail->From;
6327 } else {
6328 debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER);
6332 if ($mail->send()) {
6333 set_send_count($user);
6334 if (!empty($mail->SMTPDebug)) {
6335 echo '</pre>';
6337 return true;
6338 } else {
6339 // Trigger event for failing to send email.
6340 $event = \core\event\email_failed::create(array(
6341 'context' => context_system::instance(),
6342 'userid' => $from->id,
6343 'relateduserid' => $user->id,
6344 'other' => array(
6345 'subject' => $subject,
6346 'message' => $messagetext,
6347 'errorinfo' => $mail->ErrorInfo
6350 $event->trigger();
6351 if (CLI_SCRIPT) {
6352 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6354 if (!empty($mail->SMTPDebug)) {
6355 echo '</pre>';
6357 return false;
6362 * Check to see if a user's real email address should be used for the "From" field.
6364 * @param object $from The user object for the user we are sending the email from.
6365 * @param object $user The user object that we are sending the email to.
6366 * @param array $unused No longer used.
6367 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6369 function can_send_from_real_email_address($from, $user, $unused = null) {
6370 global $CFG;
6371 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6372 return false;
6374 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6375 // Email is in the list of allowed domains for sending email,
6376 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6377 // in a course with the sender.
6378 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6379 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6380 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6381 && enrol_get_shared_courses($user, $from, false, true)))) {
6382 return true;
6384 return false;
6388 * Generate a signoff for emails based on support settings
6390 * @return string
6392 function generate_email_signoff() {
6393 global $CFG;
6395 $signoff = "\n";
6396 if (!empty($CFG->supportname)) {
6397 $signoff .= $CFG->supportname."\n";
6399 if (!empty($CFG->supportemail)) {
6400 $signoff .= $CFG->supportemail."\n";
6402 if (!empty($CFG->supportpage)) {
6403 $signoff .= $CFG->supportpage."\n";
6405 return $signoff;
6409 * Sets specified user's password and send the new password to the user via email.
6411 * @param stdClass $user A {@link $USER} object
6412 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6413 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6415 function setnew_password_and_mail($user, $fasthash = false) {
6416 global $CFG, $DB;
6418 // We try to send the mail in language the user understands,
6419 // unfortunately the filter_string() does not support alternative langs yet
6420 // so multilang will not work properly for site->fullname.
6421 $lang = empty($user->lang) ? get_newuser_language() : $user->lang;
6423 $site = get_site();
6425 $supportuser = core_user::get_support_user();
6427 $newpassword = generate_password();
6429 update_internal_user_password($user, $newpassword, $fasthash);
6431 $a = new stdClass();
6432 $a->firstname = fullname($user, true);
6433 $a->sitename = format_string($site->fullname);
6434 $a->username = $user->username;
6435 $a->newpassword = $newpassword;
6436 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6437 $a->signoff = generate_email_signoff();
6439 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6441 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6443 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6444 return email_to_user($user, $supportuser, $subject, $message);
6449 * Resets specified user's password and send the new password to the user via email.
6451 * @param stdClass $user A {@link $USER} object
6452 * @return bool Returns true if mail was sent OK and false if there was an error.
6454 function reset_password_and_mail($user) {
6455 global $CFG;
6457 $site = get_site();
6458 $supportuser = core_user::get_support_user();
6460 $userauth = get_auth_plugin($user->auth);
6461 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6462 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6463 return false;
6466 $newpassword = generate_password();
6468 if (!$userauth->user_update_password($user, $newpassword)) {
6469 throw new \moodle_exception("cannotsetpassword");
6472 $a = new stdClass();
6473 $a->firstname = $user->firstname;
6474 $a->lastname = $user->lastname;
6475 $a->sitename = format_string($site->fullname);
6476 $a->username = $user->username;
6477 $a->newpassword = $newpassword;
6478 $a->link = $CFG->wwwroot .'/login/change_password.php';
6479 $a->signoff = generate_email_signoff();
6481 $message = get_string('newpasswordtext', '', $a);
6483 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6485 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6487 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6488 return email_to_user($user, $supportuser, $subject, $message);
6492 * Send email to specified user with confirmation text and activation link.
6494 * @param stdClass $user A {@link $USER} object
6495 * @param string $confirmationurl user confirmation URL
6496 * @return bool Returns true if mail was sent OK and false if there was an error.
6498 function send_confirmation_email($user, $confirmationurl = null) {
6499 global $CFG;
6501 $site = get_site();
6502 $supportuser = core_user::get_support_user();
6504 $data = new stdClass();
6505 $data->sitename = format_string($site->fullname);
6506 $data->admin = generate_email_signoff();
6508 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6510 if (empty($confirmationurl)) {
6511 $confirmationurl = '/login/confirm.php';
6514 $confirmationurl = new moodle_url($confirmationurl);
6515 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6516 $confirmationurl->remove_params('data');
6517 $confirmationpath = $confirmationurl->out(false);
6519 // We need to custom encode the username to include trailing dots in the link.
6520 // Because of this custom encoding we can't use moodle_url directly.
6521 // Determine if a query string is present in the confirmation url.
6522 $hasquerystring = strpos($confirmationpath, '?') !== false;
6523 // Perform normal url encoding of the username first.
6524 $username = urlencode($user->username);
6525 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6526 $username = str_replace('.', '%2E', $username);
6528 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6530 $message = get_string('emailconfirmation', '', $data);
6531 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6533 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6534 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6538 * Sends a password change confirmation email.
6540 * @param stdClass $user A {@link $USER} object
6541 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6542 * @return bool Returns true if mail was sent OK and false if there was an error.
6544 function send_password_change_confirmation_email($user, $resetrecord) {
6545 global $CFG;
6547 $site = get_site();
6548 $supportuser = core_user::get_support_user();
6549 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6551 $data = new stdClass();
6552 $data->firstname = $user->firstname;
6553 $data->lastname = $user->lastname;
6554 $data->username = $user->username;
6555 $data->sitename = format_string($site->fullname);
6556 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6557 $data->admin = generate_email_signoff();
6558 $data->resetminutes = $pwresetmins;
6560 $message = get_string('emailresetconfirmation', '', $data);
6561 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6563 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6564 return email_to_user($user, $supportuser, $subject, $message);
6569 * Sends an email containing information on how to change your password.
6571 * @param stdClass $user A {@link $USER} object
6572 * @return bool Returns true if mail was sent OK and false if there was an error.
6574 function send_password_change_info($user) {
6575 $site = get_site();
6576 $supportuser = core_user::get_support_user();
6578 $data = new stdClass();
6579 $data->firstname = $user->firstname;
6580 $data->lastname = $user->lastname;
6581 $data->username = $user->username;
6582 $data->sitename = format_string($site->fullname);
6583 $data->admin = generate_email_signoff();
6585 if (!is_enabled_auth($user->auth)) {
6586 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6587 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6588 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6589 return email_to_user($user, $supportuser, $subject, $message);
6592 $userauth = get_auth_plugin($user->auth);
6593 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6595 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6596 return email_to_user($user, $supportuser, $subject, $message);
6600 * Check that an email is allowed. It returns an error message if there was a problem.
6602 * @param string $email Content of email
6603 * @return string|false
6605 function email_is_not_allowed($email) {
6606 global $CFG;
6608 // Comparing lowercase domains.
6609 $email = strtolower($email);
6610 if (!empty($CFG->allowemailaddresses)) {
6611 $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6612 foreach ($allowed as $allowedpattern) {
6613 $allowedpattern = trim($allowedpattern);
6614 if (!$allowedpattern) {
6615 continue;
6617 if (strpos($allowedpattern, '.') === 0) {
6618 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6619 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6620 return false;
6623 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6624 return false;
6627 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6629 } else if (!empty($CFG->denyemailaddresses)) {
6630 $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6631 foreach ($denied as $deniedpattern) {
6632 $deniedpattern = trim($deniedpattern);
6633 if (!$deniedpattern) {
6634 continue;
6636 if (strpos($deniedpattern, '.') === 0) {
6637 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6638 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6639 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6642 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6643 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6648 return false;
6651 // FILE HANDLING.
6654 * Returns local file storage instance
6656 * @return file_storage
6658 function get_file_storage($reset = false) {
6659 global $CFG;
6661 static $fs = null;
6663 if ($reset) {
6664 $fs = null;
6665 return;
6668 if ($fs) {
6669 return $fs;
6672 require_once("$CFG->libdir/filelib.php");
6674 $fs = new file_storage();
6676 return $fs;
6680 * Returns local file storage instance
6682 * @return file_browser
6684 function get_file_browser() {
6685 global $CFG;
6687 static $fb = null;
6689 if ($fb) {
6690 return $fb;
6693 require_once("$CFG->libdir/filelib.php");
6695 $fb = new file_browser();
6697 return $fb;
6701 * Returns file packer
6703 * @param string $mimetype default application/zip
6704 * @return file_packer
6706 function get_file_packer($mimetype='application/zip') {
6707 global $CFG;
6709 static $fp = array();
6711 if (isset($fp[$mimetype])) {
6712 return $fp[$mimetype];
6715 switch ($mimetype) {
6716 case 'application/zip':
6717 case 'application/vnd.moodle.profiling':
6718 $classname = 'zip_packer';
6719 break;
6721 case 'application/x-gzip' :
6722 $classname = 'tgz_packer';
6723 break;
6725 case 'application/vnd.moodle.backup':
6726 $classname = 'mbz_packer';
6727 break;
6729 default:
6730 return false;
6733 require_once("$CFG->libdir/filestorage/$classname.php");
6734 $fp[$mimetype] = new $classname();
6736 return $fp[$mimetype];
6740 * Returns current name of file on disk if it exists.
6742 * @param string $newfile File to be verified
6743 * @return string Current name of file on disk if true
6745 function valid_uploaded_file($newfile) {
6746 if (empty($newfile)) {
6747 return '';
6749 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6750 return $newfile['tmp_name'];
6751 } else {
6752 return '';
6757 * Returns the maximum size for uploading files.
6759 * There are seven possible upload limits:
6760 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6761 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6762 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6763 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6764 * 5. by the Moodle admin in $CFG->maxbytes
6765 * 6. by the teacher in the current course $course->maxbytes
6766 * 7. by the teacher for the current module, eg $assignment->maxbytes
6768 * These last two are passed to this function as arguments (in bytes).
6769 * Anything defined as 0 is ignored.
6770 * The smallest of all the non-zero numbers is returned.
6772 * @todo Finish documenting this function
6774 * @param int $sitebytes Set maximum size
6775 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6776 * @param int $modulebytes Current module ->maxbytes (in bytes)
6777 * @param bool $unused This parameter has been deprecated and is not used any more.
6778 * @return int The maximum size for uploading files.
6780 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6782 if (! $filesize = ini_get('upload_max_filesize')) {
6783 $filesize = '5M';
6785 $minimumsize = get_real_size($filesize);
6787 if ($postsize = ini_get('post_max_size')) {
6788 $postsize = get_real_size($postsize);
6789 if ($postsize < $minimumsize) {
6790 $minimumsize = $postsize;
6794 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6795 $minimumsize = $sitebytes;
6798 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6799 $minimumsize = $coursebytes;
6802 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6803 $minimumsize = $modulebytes;
6806 return $minimumsize;
6810 * Returns the maximum size for uploading files for the current user
6812 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6814 * @param context $context The context in which to check user capabilities
6815 * @param int $sitebytes Set maximum size
6816 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6817 * @param int $modulebytes Current module ->maxbytes (in bytes)
6818 * @param stdClass $user The user
6819 * @param bool $unused This parameter has been deprecated and is not used any more.
6820 * @return int The maximum size for uploading files.
6822 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6823 $unused = false) {
6824 global $USER;
6826 if (empty($user)) {
6827 $user = $USER;
6830 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6831 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6834 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6838 * Returns an array of possible sizes in local language
6840 * Related to {@link get_max_upload_file_size()} - this function returns an
6841 * array of possible sizes in an array, translated to the
6842 * local language.
6844 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6846 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6847 * with the value set to 0. This option will be the first in the list.
6849 * @uses SORT_NUMERIC
6850 * @param int $sitebytes Set maximum size
6851 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6852 * @param int $modulebytes Current module ->maxbytes (in bytes)
6853 * @param int|array $custombytes custom upload size/s which will be added to list,
6854 * Only value/s smaller then maxsize will be added to list.
6855 * @return array
6857 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6858 global $CFG;
6860 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6861 return array();
6864 if ($sitebytes == 0) {
6865 // Will get the minimum of upload_max_filesize or post_max_size.
6866 $sitebytes = get_max_upload_file_size();
6869 $filesize = array();
6870 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6871 5242880, 10485760, 20971520, 52428800, 104857600,
6872 262144000, 524288000, 786432000, 1073741824,
6873 2147483648, 4294967296, 8589934592);
6875 // If custombytes is given and is valid then add it to the list.
6876 if (is_number($custombytes) and $custombytes > 0) {
6877 $custombytes = (int)$custombytes;
6878 if (!in_array($custombytes, $sizelist)) {
6879 $sizelist[] = $custombytes;
6881 } else if (is_array($custombytes)) {
6882 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6885 // Allow maxbytes to be selected if it falls outside the above boundaries.
6886 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6887 // Note: get_real_size() is used in order to prevent problems with invalid values.
6888 $sizelist[] = get_real_size($CFG->maxbytes);
6891 foreach ($sizelist as $sizebytes) {
6892 if ($sizebytes < $maxsize && $sizebytes > 0) {
6893 $filesize[(string)intval($sizebytes)] = display_size($sizebytes, 0);
6897 $limitlevel = '';
6898 $displaysize = '';
6899 if ($modulebytes &&
6900 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6901 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6902 $limitlevel = get_string('activity', 'core');
6903 $displaysize = display_size($modulebytes, 0);
6904 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6906 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6907 $limitlevel = get_string('course', 'core');
6908 $displaysize = display_size($coursebytes, 0);
6909 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6911 } else if ($sitebytes) {
6912 $limitlevel = get_string('site', 'core');
6913 $displaysize = display_size($sitebytes, 0);
6914 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6917 krsort($filesize, SORT_NUMERIC);
6918 if ($limitlevel) {
6919 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6920 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6923 return $filesize;
6927 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6929 * If excludefiles is defined, then that file/directory is ignored
6930 * If getdirs is true, then (sub)directories are included in the output
6931 * If getfiles is true, then files are included in the output
6932 * (at least one of these must be true!)
6934 * @todo Finish documenting this function. Add examples of $excludefile usage.
6936 * @param string $rootdir A given root directory to start from
6937 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6938 * @param bool $descend If true then subdirectories are recursed as well
6939 * @param bool $getdirs If true then (sub)directories are included in the output
6940 * @param bool $getfiles If true then files are included in the output
6941 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6943 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6945 $dirs = array();
6947 if (!$getdirs and !$getfiles) { // Nothing to show.
6948 return $dirs;
6951 if (!is_dir($rootdir)) { // Must be a directory.
6952 return $dirs;
6955 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6956 return $dirs;
6959 if (!is_array($excludefiles)) {
6960 $excludefiles = array($excludefiles);
6963 while (false !== ($file = readdir($dir))) {
6964 $firstchar = substr($file, 0, 1);
6965 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6966 continue;
6968 $fullfile = $rootdir .'/'. $file;
6969 if (filetype($fullfile) == 'dir') {
6970 if ($getdirs) {
6971 $dirs[] = $file;
6973 if ($descend) {
6974 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6975 foreach ($subdirs as $subdir) {
6976 $dirs[] = $file .'/'. $subdir;
6979 } else if ($getfiles) {
6980 $dirs[] = $file;
6983 closedir($dir);
6985 asort($dirs);
6987 return $dirs;
6992 * Adds up all the files in a directory and works out the size.
6994 * @param string $rootdir The directory to start from
6995 * @param string $excludefile A file to exclude when summing directory size
6996 * @return int The summed size of all files and subfiles within the root directory
6998 function get_directory_size($rootdir, $excludefile='') {
6999 global $CFG;
7001 // Do it this way if we can, it's much faster.
7002 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
7003 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
7004 $output = null;
7005 $return = null;
7006 exec($command, $output, $return);
7007 if (is_array($output)) {
7008 // We told it to return k.
7009 return get_real_size(intval($output[0]).'k');
7013 if (!is_dir($rootdir)) {
7014 // Must be a directory.
7015 return 0;
7018 if (!$dir = @opendir($rootdir)) {
7019 // Can't open it for some reason.
7020 return 0;
7023 $size = 0;
7025 while (false !== ($file = readdir($dir))) {
7026 $firstchar = substr($file, 0, 1);
7027 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
7028 continue;
7030 $fullfile = $rootdir .'/'. $file;
7031 if (filetype($fullfile) == 'dir') {
7032 $size += get_directory_size($fullfile, $excludefile);
7033 } else {
7034 $size += filesize($fullfile);
7037 closedir($dir);
7039 return $size;
7043 * Converts bytes into display form
7045 * @param int $size The size to convert to human readable form
7046 * @param int $decimalplaces If specified, uses fixed number of decimal places
7047 * @param string $fixedunits If specified, uses fixed units (e.g. 'KB')
7048 * @return string Display version of size
7050 function display_size($size, int $decimalplaces = 1, string $fixedunits = ''): string {
7052 static $units;
7054 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
7055 return get_string('unlimited');
7058 if (empty($units)) {
7059 $units[] = get_string('sizeb');
7060 $units[] = get_string('sizekb');
7061 $units[] = get_string('sizemb');
7062 $units[] = get_string('sizegb');
7063 $units[] = get_string('sizetb');
7064 $units[] = get_string('sizepb');
7067 switch ($fixedunits) {
7068 case 'PB' :
7069 $magnitude = 5;
7070 break;
7071 case 'TB' :
7072 $magnitude = 4;
7073 break;
7074 case 'GB' :
7075 $magnitude = 3;
7076 break;
7077 case 'MB' :
7078 $magnitude = 2;
7079 break;
7080 case 'KB' :
7081 $magnitude = 1;
7082 break;
7083 case 'B' :
7084 $magnitude = 0;
7085 break;
7086 case '':
7087 $magnitude = floor(log($size, 1024));
7088 $magnitude = max(0, min(5, $magnitude));
7089 break;
7090 default:
7091 throw new coding_exception('Unknown fixed units value: ' . $fixedunits);
7094 // Special case for magnitude 0 (bytes) - never use decimal places.
7095 $nbsp = "\xc2\xa0";
7096 if ($magnitude === 0) {
7097 return round($size) . $nbsp . $units[$magnitude];
7100 // Convert to specified units.
7101 $sizeinunit = $size / 1024 ** $magnitude;
7103 // Fixed decimal places.
7104 return sprintf('%.' . $decimalplaces . 'f', $sizeinunit) . $nbsp . $units[$magnitude];
7108 * Cleans a given filename by removing suspicious or troublesome characters
7110 * @see clean_param()
7111 * @param string $string file name
7112 * @return string cleaned file name
7114 function clean_filename($string) {
7115 return clean_param($string, PARAM_FILE);
7118 // STRING TRANSLATION.
7121 * Returns the code for the current language
7123 * @category string
7124 * @return string
7126 function current_language() {
7127 global $CFG, $PAGE, $SESSION, $USER;
7129 if (!empty($SESSION->forcelang)) {
7130 // Allows overriding course-forced language (useful for admins to check
7131 // issues in courses whose language they don't understand).
7132 // Also used by some code to temporarily get language-related information in a
7133 // specific language (see force_current_language()).
7134 $return = $SESSION->forcelang;
7136 } else if (!empty($PAGE->cm->lang)) {
7137 // Activity language, if set.
7138 $return = $PAGE->cm->lang;
7140 } else if (!empty($PAGE->course->id) && $PAGE->course->id != SITEID && !empty($PAGE->course->lang)) {
7141 // Course language can override all other settings for this page.
7142 $return = $PAGE->course->lang;
7144 } else if (!empty($SESSION->lang)) {
7145 // Session language can override other settings.
7146 $return = $SESSION->lang;
7148 } else if (!empty($USER->lang)) {
7149 $return = $USER->lang;
7151 } else if (isset($CFG->lang)) {
7152 $return = $CFG->lang;
7154 } else {
7155 $return = 'en';
7158 // Just in case this slipped in from somewhere by accident.
7159 $return = str_replace('_utf8', '', $return);
7161 return $return;
7165 * Fix the current language to the given language code.
7167 * @param string $lang The language code to use.
7168 * @return void
7170 function fix_current_language(string $lang): void {
7171 global $CFG, $COURSE, $SESSION, $USER;
7173 if (!get_string_manager()->translation_exists($lang)) {
7174 throw new coding_exception("The language pack for $lang is not available");
7177 $fixglobal = '';
7178 $fixlang = 'lang';
7179 if (!empty($SESSION->forcelang)) {
7180 $fixglobal = $SESSION;
7181 $fixlang = 'forcelang';
7182 } else if (!empty($COURSE->id) && $COURSE->id != SITEID && !empty($COURSE->lang)) {
7183 $fixglobal = $COURSE;
7184 } else if (!empty($SESSION->lang)) {
7185 $fixglobal = $SESSION;
7186 } else if (!empty($USER->lang)) {
7187 $fixglobal = $USER;
7188 } else if (isset($CFG->lang)) {
7189 set_config('lang', $lang);
7192 if ($fixglobal) {
7193 $fixglobal->$fixlang = $lang;
7198 * Returns parent language of current active language if defined
7200 * @category string
7201 * @param string $lang null means current language
7202 * @return string
7204 function get_parent_language($lang=null) {
7206 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7208 if ($parentlang === 'en') {
7209 $parentlang = '';
7212 return $parentlang;
7216 * Force the current language to get strings and dates localised in the given language.
7218 * After calling this function, all strings will be provided in the given language
7219 * until this function is called again, or equivalent code is run.
7221 * @param string $language
7222 * @return string previous $SESSION->forcelang value
7224 function force_current_language($language) {
7225 global $SESSION;
7226 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
7227 if ($language !== $sessionforcelang) {
7228 // Setting forcelang to null or an empty string disables its effect.
7229 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
7230 $SESSION->forcelang = $language;
7231 moodle_setlocale();
7234 return $sessionforcelang;
7238 * Returns current string_manager instance.
7240 * The param $forcereload is needed for CLI installer only where the string_manager instance
7241 * must be replaced during the install.php script life time.
7243 * @category string
7244 * @param bool $forcereload shall the singleton be released and new instance created instead?
7245 * @return core_string_manager
7247 function get_string_manager($forcereload=false) {
7248 global $CFG;
7250 static $singleton = null;
7252 if ($forcereload) {
7253 $singleton = null;
7255 if ($singleton === null) {
7256 if (empty($CFG->early_install_lang)) {
7258 $transaliases = array();
7259 if (empty($CFG->langlist)) {
7260 $translist = array();
7261 } else {
7262 $translist = explode(',', $CFG->langlist);
7263 $translist = array_map('trim', $translist);
7264 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7265 foreach ($translist as $i => $value) {
7266 $parts = preg_split('/\s*\|\s*/', $value, 2);
7267 if (count($parts) == 2) {
7268 $transaliases[$parts[0]] = $parts[1];
7269 $translist[$i] = $parts[0];
7274 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7275 $classname = $CFG->config_php_settings['customstringmanager'];
7277 if (class_exists($classname)) {
7278 $implements = class_implements($classname);
7280 if (isset($implements['core_string_manager'])) {
7281 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7282 return $singleton;
7284 } else {
7285 debugging('Unable to instantiate custom string manager: class '.$classname.
7286 ' does not implement the core_string_manager interface.');
7289 } else {
7290 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7294 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7296 } else {
7297 $singleton = new core_string_manager_install();
7301 return $singleton;
7305 * Returns a localized string.
7307 * Returns the translated string specified by $identifier as
7308 * for $module. Uses the same format files as STphp.
7309 * $a is an object, string or number that can be used
7310 * within translation strings
7312 * eg 'hello {$a->firstname} {$a->lastname}'
7313 * or 'hello {$a}'
7315 * If you would like to directly echo the localized string use
7316 * the function {@link print_string()}
7318 * Example usage of this function involves finding the string you would
7319 * like a local equivalent of and using its identifier and module information
7320 * to retrieve it.<br/>
7321 * If you open moodle/lang/en/moodle.php and look near line 278
7322 * you will find a string to prompt a user for their word for 'course'
7323 * <code>
7324 * $string['course'] = 'Course';
7325 * </code>
7326 * So if you want to display the string 'Course'
7327 * in any language that supports it on your site
7328 * you just need to use the identifier 'course'
7329 * <code>
7330 * $mystring = '<strong>'. get_string('course') .'</strong>';
7331 * or
7332 * </code>
7333 * If the string you want is in another file you'd take a slightly
7334 * different approach. Looking in moodle/lang/en/calendar.php you find
7335 * around line 75:
7336 * <code>
7337 * $string['typecourse'] = 'Course event';
7338 * </code>
7339 * If you want to display the string "Course event" in any language
7340 * supported you would use the identifier 'typecourse' and the module 'calendar'
7341 * (because it is in the file calendar.php):
7342 * <code>
7343 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7344 * </code>
7346 * As a last resort, should the identifier fail to map to a string
7347 * the returned string will be [[ $identifier ]]
7349 * In Moodle 2.3 there is a new argument to this function $lazyload.
7350 * Setting $lazyload to true causes get_string to return a lang_string object
7351 * rather than the string itself. The fetching of the string is then put off until
7352 * the string object is first used. The object can be used by calling it's out
7353 * method or by casting the object to a string, either directly e.g.
7354 * (string)$stringobject
7355 * or indirectly by using the string within another string or echoing it out e.g.
7356 * echo $stringobject
7357 * return "<p>{$stringobject}</p>";
7358 * It is worth noting that using $lazyload and attempting to use the string as an
7359 * array key will cause a fatal error as objects cannot be used as array keys.
7360 * But you should never do that anyway!
7361 * For more information {@link lang_string}
7363 * @category string
7364 * @param string $identifier The key identifier for the localized string
7365 * @param string $component The module where the key identifier is stored,
7366 * usually expressed as the filename in the language pack without the
7367 * .php on the end but can also be written as mod/forum or grade/export/xls.
7368 * If none is specified then moodle.php is used.
7369 * @param string|object|array $a An object, string or number that can be used
7370 * within translation strings
7371 * @param bool $lazyload If set to true a string object is returned instead of
7372 * the string itself. The string then isn't calculated until it is first used.
7373 * @return string The localized string.
7374 * @throws coding_exception
7376 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7377 global $CFG;
7379 // If the lazy load argument has been supplied return a lang_string object
7380 // instead.
7381 // We need to make sure it is true (and a bool) as you will see below there
7382 // used to be a forth argument at one point.
7383 if ($lazyload === true) {
7384 return new lang_string($identifier, $component, $a);
7387 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7388 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7391 // There is now a forth argument again, this time it is a boolean however so
7392 // we can still check for the old extralocations parameter.
7393 if (!is_bool($lazyload) && !empty($lazyload)) {
7394 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7397 if (strpos((string)$component, '/') !== false) {
7398 debugging('The module name you passed to get_string is the deprecated format ' .
7399 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7400 $componentpath = explode('/', $component);
7402 switch ($componentpath[0]) {
7403 case 'mod':
7404 $component = $componentpath[1];
7405 break;
7406 case 'blocks':
7407 case 'block':
7408 $component = 'block_'.$componentpath[1];
7409 break;
7410 case 'enrol':
7411 $component = 'enrol_'.$componentpath[1];
7412 break;
7413 case 'format':
7414 $component = 'format_'.$componentpath[1];
7415 break;
7416 case 'grade':
7417 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7418 break;
7422 $result = get_string_manager()->get_string($identifier, $component, $a);
7424 // Debugging feature lets you display string identifier and component.
7425 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7426 $result .= ' {' . $identifier . '/' . $component . '}';
7428 return $result;
7432 * Converts an array of strings to their localized value.
7434 * @param array $array An array of strings
7435 * @param string $component The language module that these strings can be found in.
7436 * @return stdClass translated strings.
7438 function get_strings($array, $component = '') {
7439 $string = new stdClass;
7440 foreach ($array as $item) {
7441 $string->$item = get_string($item, $component);
7443 return $string;
7447 * Prints out a translated string.
7449 * Prints out a translated string using the return value from the {@link get_string()} function.
7451 * Example usage of this function when the string is in the moodle.php file:<br/>
7452 * <code>
7453 * echo '<strong>';
7454 * print_string('course');
7455 * echo '</strong>';
7456 * </code>
7458 * Example usage of this function when the string is not in the moodle.php file:<br/>
7459 * <code>
7460 * echo '<h1>';
7461 * print_string('typecourse', 'calendar');
7462 * echo '</h1>';
7463 * </code>
7465 * @category string
7466 * @param string $identifier The key identifier for the localized string
7467 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7468 * @param string|object|array $a An object, string or number that can be used within translation strings
7470 function print_string($identifier, $component = '', $a = null) {
7471 echo get_string($identifier, $component, $a);
7475 * Returns a list of charset codes
7477 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7478 * (checking that such charset is supported by the texlib library!)
7480 * @return array And associative array with contents in the form of charset => charset
7482 function get_list_of_charsets() {
7484 $charsets = array(
7485 'EUC-JP' => 'EUC-JP',
7486 'ISO-2022-JP'=> 'ISO-2022-JP',
7487 'ISO-8859-1' => 'ISO-8859-1',
7488 'SHIFT-JIS' => 'SHIFT-JIS',
7489 'GB2312' => 'GB2312',
7490 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7491 'UTF-8' => 'UTF-8');
7493 asort($charsets);
7495 return $charsets;
7499 * Returns a list of valid and compatible themes
7501 * @return array
7503 function get_list_of_themes() {
7504 global $CFG;
7506 $themes = array();
7508 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7509 $themelist = explode(',', $CFG->themelist);
7510 } else {
7511 $themelist = array_keys(core_component::get_plugin_list("theme"));
7514 foreach ($themelist as $key => $themename) {
7515 $theme = theme_config::load($themename);
7516 $themes[$themename] = $theme;
7519 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7521 return $themes;
7525 * Factory function for emoticon_manager
7527 * @return emoticon_manager singleton
7529 function get_emoticon_manager() {
7530 static $singleton = null;
7532 if (is_null($singleton)) {
7533 $singleton = new emoticon_manager();
7536 return $singleton;
7540 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7542 * Whenever this manager mentiones 'emoticon object', the following data
7543 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7544 * altidentifier and altcomponent
7546 * @see admin_setting_emoticons
7548 * @copyright 2010 David Mudrak
7549 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7551 class emoticon_manager {
7554 * Returns the currently enabled emoticons
7556 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7557 * @return array of emoticon objects
7559 public function get_emoticons($selectable = false) {
7560 global $CFG;
7561 $notselectable = ['martin', 'egg'];
7563 if (empty($CFG->emoticons)) {
7564 return array();
7567 $emoticons = $this->decode_stored_config($CFG->emoticons);
7569 if (!is_array($emoticons)) {
7570 // Something is wrong with the format of stored setting.
7571 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7572 return array();
7574 if ($selectable) {
7575 foreach ($emoticons as $index => $emote) {
7576 if (in_array($emote->altidentifier, $notselectable)) {
7577 // Skip this one.
7578 unset($emoticons[$index]);
7583 return $emoticons;
7587 * Converts emoticon object into renderable pix_emoticon object
7589 * @param stdClass $emoticon emoticon object
7590 * @param array $attributes explicit HTML attributes to set
7591 * @return pix_emoticon
7593 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7594 $stringmanager = get_string_manager();
7595 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7596 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7597 } else {
7598 $alt = s($emoticon->text);
7600 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7604 * Encodes the array of emoticon objects into a string storable in config table
7606 * @see self::decode_stored_config()
7607 * @param array $emoticons array of emtocion objects
7608 * @return string
7610 public function encode_stored_config(array $emoticons) {
7611 return json_encode($emoticons);
7615 * Decodes the string into an array of emoticon objects
7617 * @see self::encode_stored_config()
7618 * @param string $encoded
7619 * @return string|null
7621 public function decode_stored_config($encoded) {
7622 $decoded = json_decode($encoded);
7623 if (!is_array($decoded)) {
7624 return null;
7626 return $decoded;
7630 * Returns default set of emoticons supported by Moodle
7632 * @return array of sdtClasses
7634 public function default_emoticons() {
7635 return array(
7636 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7637 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7638 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7639 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7640 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7641 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7642 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7643 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7644 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7645 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7646 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7647 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7648 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7649 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7650 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7651 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7652 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7653 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7654 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7655 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7656 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7657 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7658 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7659 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7660 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7661 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7662 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7663 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7664 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7665 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7670 * Helper method preparing the stdClass with the emoticon properties
7672 * @param string|array $text or array of strings
7673 * @param string $imagename to be used by {@link pix_emoticon}
7674 * @param string $altidentifier alternative string identifier, null for no alt
7675 * @param string $altcomponent where the alternative string is defined
7676 * @param string $imagecomponent to be used by {@link pix_emoticon}
7677 * @return stdClass
7679 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7680 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7681 return (object)array(
7682 'text' => $text,
7683 'imagename' => $imagename,
7684 'imagecomponent' => $imagecomponent,
7685 'altidentifier' => $altidentifier,
7686 'altcomponent' => $altcomponent,
7691 // ENCRYPTION.
7694 * rc4encrypt
7696 * @param string $data Data to encrypt.
7697 * @return string The now encrypted data.
7699 function rc4encrypt($data) {
7700 return endecrypt(get_site_identifier(), $data, '');
7704 * rc4decrypt
7706 * @param string $data Data to decrypt.
7707 * @return string The now decrypted data.
7709 function rc4decrypt($data) {
7710 return endecrypt(get_site_identifier(), $data, 'de');
7714 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7716 * @todo Finish documenting this function
7718 * @param string $pwd The password to use when encrypting or decrypting
7719 * @param string $data The data to be decrypted/encrypted
7720 * @param string $case Either 'de' for decrypt or '' for encrypt
7721 * @return string
7723 function endecrypt ($pwd, $data, $case) {
7725 if ($case == 'de') {
7726 $data = urldecode($data);
7729 $key[] = '';
7730 $box[] = '';
7731 $pwdlength = strlen($pwd);
7733 for ($i = 0; $i <= 255; $i++) {
7734 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7735 $box[$i] = $i;
7738 $x = 0;
7740 for ($i = 0; $i <= 255; $i++) {
7741 $x = ($x + $box[$i] + $key[$i]) % 256;
7742 $tempswap = $box[$i];
7743 $box[$i] = $box[$x];
7744 $box[$x] = $tempswap;
7747 $cipher = '';
7749 $a = 0;
7750 $j = 0;
7752 for ($i = 0; $i < strlen($data); $i++) {
7753 $a = ($a + 1) % 256;
7754 $j = ($j + $box[$a]) % 256;
7755 $temp = $box[$a];
7756 $box[$a] = $box[$j];
7757 $box[$j] = $temp;
7758 $k = $box[(($box[$a] + $box[$j]) % 256)];
7759 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7760 $cipher .= chr($cipherby);
7763 if ($case == 'de') {
7764 $cipher = urldecode(urlencode($cipher));
7765 } else {
7766 $cipher = urlencode($cipher);
7769 return $cipher;
7772 // ENVIRONMENT CHECKING.
7775 * This method validates a plug name. It is much faster than calling clean_param.
7777 * @param string $name a string that might be a plugin name.
7778 * @return bool if this string is a valid plugin name.
7780 function is_valid_plugin_name($name) {
7781 // This does not work for 'mod', bad luck, use any other type.
7782 return core_component::is_valid_plugin_name('tool', $name);
7786 * Get a list of all the plugins of a given type that define a certain API function
7787 * in a certain file. The plugin component names and function names are returned.
7789 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7790 * @param string $function the part of the name of the function after the
7791 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7792 * names like report_courselist_hook.
7793 * @param string $file the name of file within the plugin that defines the
7794 * function. Defaults to lib.php.
7795 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7796 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7798 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7799 global $CFG;
7801 // We don't include here as all plugin types files would be included.
7802 $plugins = get_plugins_with_function($function, $file, false);
7804 if (empty($plugins[$plugintype])) {
7805 return array();
7808 $allplugins = core_component::get_plugin_list($plugintype);
7810 // Reformat the array and include the files.
7811 $pluginfunctions = array();
7812 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7814 // Check that it has not been removed and the file is still available.
7815 if (!empty($allplugins[$pluginname])) {
7817 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7818 if (file_exists($filepath)) {
7819 include_once($filepath);
7821 // Now that the file is loaded, we must verify the function still exists.
7822 if (function_exists($functionname)) {
7823 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7824 } else {
7825 // Invalidate the cache for next run.
7826 \cache_helper::invalidate_by_definition('core', 'plugin_functions');
7832 return $pluginfunctions;
7836 * Get a list of all the plugins that define a certain API function in a certain file.
7838 * @param string $function the part of the name of the function after the
7839 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7840 * names like report_courselist_hook.
7841 * @param string $file the name of file within the plugin that defines the
7842 * function. Defaults to lib.php.
7843 * @param bool $include Whether to include the files that contain the functions or not.
7844 * @return array with [plugintype][plugin] = functionname
7846 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7847 global $CFG;
7849 if (during_initial_install() || isset($CFG->upgraderunning)) {
7850 // API functions _must not_ be called during an installation or upgrade.
7851 return [];
7854 $cache = \cache::make('core', 'plugin_functions');
7856 // Including both although I doubt that we will find two functions definitions with the same name.
7857 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7858 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7859 $pluginfunctions = $cache->get($key);
7860 $dirty = false;
7862 // Use the plugin manager to check that plugins are currently installed.
7863 $pluginmanager = \core_plugin_manager::instance();
7865 if ($pluginfunctions !== false) {
7867 // Checking that the files are still available.
7868 foreach ($pluginfunctions as $plugintype => $plugins) {
7870 $allplugins = \core_component::get_plugin_list($plugintype);
7871 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7872 foreach ($plugins as $plugin => $function) {
7873 if (!isset($installedplugins[$plugin])) {
7874 // Plugin code is still present on disk but it is not installed.
7875 $dirty = true;
7876 break 2;
7879 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7880 if (empty($allplugins[$plugin])) {
7881 $dirty = true;
7882 break 2;
7885 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7886 if ($include && $fileexists) {
7887 // Include the files if it was requested.
7888 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7889 } else if (!$fileexists) {
7890 // If the file is not available any more it should not be returned.
7891 $dirty = true;
7892 break 2;
7895 // Check if the function still exists in the file.
7896 if ($include && !function_exists($function)) {
7897 $dirty = true;
7898 break 2;
7903 // If the cache is dirty, we should fall through and let it rebuild.
7904 if (!$dirty) {
7905 return $pluginfunctions;
7909 $pluginfunctions = array();
7911 // To fill the cached. Also, everything should continue working with cache disabled.
7912 $plugintypes = \core_component::get_plugin_types();
7913 foreach ($plugintypes as $plugintype => $unused) {
7915 // We need to include files here.
7916 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7917 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7918 foreach ($pluginswithfile as $plugin => $notused) {
7920 if (!isset($installedplugins[$plugin])) {
7921 continue;
7924 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7926 $pluginfunction = false;
7927 if (function_exists($fullfunction)) {
7928 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7929 $pluginfunction = $fullfunction;
7931 } else if ($plugintype === 'mod') {
7932 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7933 $shortfunction = $plugin . '_' . $function;
7934 if (function_exists($shortfunction)) {
7935 $pluginfunction = $shortfunction;
7939 if ($pluginfunction) {
7940 if (empty($pluginfunctions[$plugintype])) {
7941 $pluginfunctions[$plugintype] = array();
7943 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7948 $cache->set($key, $pluginfunctions);
7950 return $pluginfunctions;
7955 * Lists plugin-like directories within specified directory
7957 * This function was originally used for standard Moodle plugins, please use
7958 * new core_component::get_plugin_list() now.
7960 * This function is used for general directory listing and backwards compatility.
7962 * @param string $directory relative directory from root
7963 * @param string $exclude dir name to exclude from the list (defaults to none)
7964 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7965 * @return array Sorted array of directory names found under the requested parameters
7967 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7968 global $CFG;
7970 $plugins = array();
7972 if (empty($basedir)) {
7973 $basedir = $CFG->dirroot .'/'. $directory;
7975 } else {
7976 $basedir = $basedir .'/'. $directory;
7979 if ($CFG->debugdeveloper and empty($exclude)) {
7980 // Make sure devs do not use this to list normal plugins,
7981 // this is intended for general directories that are not plugins!
7983 $subtypes = core_component::get_plugin_types();
7984 if (in_array($basedir, $subtypes)) {
7985 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7987 unset($subtypes);
7990 $ignorelist = array_flip(array_filter([
7991 'CVS',
7992 '_vti_cnf',
7993 'amd',
7994 'classes',
7995 'simpletest',
7996 'tests',
7997 'templates',
7998 'yui',
7999 $exclude,
8000 ]));
8002 if (file_exists($basedir) && filetype($basedir) == 'dir') {
8003 if (!$dirhandle = opendir($basedir)) {
8004 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
8005 return array();
8007 while (false !== ($dir = readdir($dirhandle))) {
8008 if (strpos($dir, '.') === 0) {
8009 // Ignore directories starting with .
8010 // These are treated as hidden directories.
8011 continue;
8013 if (array_key_exists($dir, $ignorelist)) {
8014 // This directory features on the ignore list.
8015 continue;
8017 if (filetype($basedir .'/'. $dir) != 'dir') {
8018 continue;
8020 $plugins[] = $dir;
8022 closedir($dirhandle);
8024 if ($plugins) {
8025 asort($plugins);
8027 return $plugins;
8031 * Invoke plugin's callback functions
8033 * @param string $type plugin type e.g. 'mod'
8034 * @param string $name plugin name
8035 * @param string $feature feature name
8036 * @param string $action feature's action
8037 * @param array $params parameters of callback function, should be an array
8038 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
8039 * @return mixed
8041 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
8043 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
8044 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
8048 * Invoke component's callback functions
8050 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8051 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8052 * @param array $params parameters of callback function
8053 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
8054 * @return mixed
8056 function component_callback($component, $function, array $params = array(), $default = null) {
8058 $functionname = component_callback_exists($component, $function);
8060 if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
8061 // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
8062 // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
8063 // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
8064 // This check can be removed when minimum PHP version for Moodle is raised to 8.
8065 debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
8066 DEBUG_DEVELOPER);
8067 $params = array_values($params);
8070 if ($functionname) {
8071 // Function exists, so just return function result.
8072 $ret = call_user_func_array($functionname, $params);
8073 if (is_null($ret)) {
8074 return $default;
8075 } else {
8076 return $ret;
8079 return $default;
8083 * Determine if a component callback exists and return the function name to call. Note that this
8084 * function will include the required library files so that the functioname returned can be
8085 * called directly.
8087 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8088 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8089 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
8090 * @throws coding_exception if invalid component specfied
8092 function component_callback_exists($component, $function) {
8093 global $CFG; // This is needed for the inclusions.
8095 $cleancomponent = clean_param($component, PARAM_COMPONENT);
8096 if (empty($cleancomponent)) {
8097 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8099 $component = $cleancomponent;
8101 list($type, $name) = core_component::normalize_component($component);
8102 $component = $type . '_' . $name;
8104 $oldfunction = $name.'_'.$function;
8105 $function = $component.'_'.$function;
8107 $dir = core_component::get_component_directory($component);
8108 if (empty($dir)) {
8109 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8112 // Load library and look for function.
8113 if (file_exists($dir.'/lib.php')) {
8114 require_once($dir.'/lib.php');
8117 if (!function_exists($function) and function_exists($oldfunction)) {
8118 if ($type !== 'mod' and $type !== 'core') {
8119 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
8121 $function = $oldfunction;
8124 if (function_exists($function)) {
8125 return $function;
8127 return false;
8131 * Call the specified callback method on the provided class.
8133 * If the callback returns null, then the default value is returned instead.
8134 * If the class does not exist, then the default value is returned.
8136 * @param string $classname The name of the class to call upon.
8137 * @param string $methodname The name of the staticically defined method on the class.
8138 * @param array $params The arguments to pass into the method.
8139 * @param mixed $default The default value.
8140 * @return mixed The return value.
8142 function component_class_callback($classname, $methodname, array $params, $default = null) {
8143 if (!class_exists($classname)) {
8144 return $default;
8147 if (!method_exists($classname, $methodname)) {
8148 return $default;
8151 $fullfunction = $classname . '::' . $methodname;
8152 $result = call_user_func_array($fullfunction, $params);
8154 if (null === $result) {
8155 return $default;
8156 } else {
8157 return $result;
8162 * Checks whether a plugin supports a specified feature.
8164 * @param string $type Plugin type e.g. 'mod'
8165 * @param string $name Plugin name e.g. 'forum'
8166 * @param string $feature Feature code (FEATURE_xx constant)
8167 * @param mixed $default default value if feature support unknown
8168 * @return mixed Feature result (false if not supported, null if feature is unknown,
8169 * otherwise usually true but may have other feature-specific value such as array)
8170 * @throws coding_exception
8172 function plugin_supports($type, $name, $feature, $default = null) {
8173 global $CFG;
8175 if ($type === 'mod' and $name === 'NEWMODULE') {
8176 // Somebody forgot to rename the module template.
8177 return false;
8180 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8181 if (empty($component)) {
8182 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8185 $function = null;
8187 if ($type === 'mod') {
8188 // We need this special case because we support subplugins in modules,
8189 // otherwise it would end up in infinite loop.
8190 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8191 include_once("$CFG->dirroot/mod/$name/lib.php");
8192 $function = $component.'_supports';
8193 if (!function_exists($function)) {
8194 // Legacy non-frankenstyle function name.
8195 $function = $name.'_supports';
8199 } else {
8200 if (!$path = core_component::get_plugin_directory($type, $name)) {
8201 // Non existent plugin type.
8202 return false;
8204 if (file_exists("$path/lib.php")) {
8205 include_once("$path/lib.php");
8206 $function = $component.'_supports';
8210 if ($function and function_exists($function)) {
8211 $supports = $function($feature);
8212 if (is_null($supports)) {
8213 // Plugin does not know - use default.
8214 return $default;
8215 } else {
8216 return $supports;
8220 // Plugin does not care, so use default.
8221 return $default;
8225 * Returns true if the current version of PHP is greater that the specified one.
8227 * @todo Check PHP version being required here is it too low?
8229 * @param string $version The version of php being tested.
8230 * @return bool
8232 function check_php_version($version='5.2.4') {
8233 return (version_compare(phpversion(), $version) >= 0);
8237 * Determine if moodle installation requires update.
8239 * Checks version numbers of main code and all plugins to see
8240 * if there are any mismatches.
8242 * @return bool
8244 function moodle_needs_upgrading() {
8245 global $CFG;
8247 if (empty($CFG->version)) {
8248 return true;
8251 // There is no need to purge plugininfo caches here because
8252 // these caches are not used during upgrade and they are purged after
8253 // every upgrade.
8255 if (empty($CFG->allversionshash)) {
8256 return true;
8259 $hash = core_component::get_all_versions_hash();
8261 return ($hash !== $CFG->allversionshash);
8265 * Returns the major version of this site
8267 * Moodle version numbers consist of three numbers separated by a dot, for
8268 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8269 * called major version. This function extracts the major version from either
8270 * $CFG->release (default) or eventually from the $release variable defined in
8271 * the main version.php.
8273 * @param bool $fromdisk should the version if source code files be used
8274 * @return string|false the major version like '2.3', false if could not be determined
8276 function moodle_major_version($fromdisk = false) {
8277 global $CFG;
8279 if ($fromdisk) {
8280 $release = null;
8281 require($CFG->dirroot.'/version.php');
8282 if (empty($release)) {
8283 return false;
8286 } else {
8287 if (empty($CFG->release)) {
8288 return false;
8290 $release = $CFG->release;
8293 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8294 return $matches[0];
8295 } else {
8296 return false;
8300 // MISCELLANEOUS.
8303 * Gets the system locale
8305 * @return string Retuns the current locale.
8307 function moodle_getlocale() {
8308 global $CFG;
8310 // Fetch the correct locale based on ostype.
8311 if ($CFG->ostype == 'WINDOWS') {
8312 $stringtofetch = 'localewin';
8313 } else {
8314 $stringtofetch = 'locale';
8317 if (!empty($CFG->locale)) { // Override locale for all language packs.
8318 return $CFG->locale;
8321 return get_string($stringtofetch, 'langconfig');
8325 * Sets the system locale
8327 * @category string
8328 * @param string $locale Can be used to force a locale
8330 function moodle_setlocale($locale='') {
8331 global $CFG;
8333 static $currentlocale = ''; // Last locale caching.
8335 $oldlocale = $currentlocale;
8337 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8338 if (!empty($locale)) {
8339 $currentlocale = $locale;
8340 } else {
8341 $currentlocale = moodle_getlocale();
8344 // Do nothing if locale already set up.
8345 if ($oldlocale == $currentlocale) {
8346 return;
8349 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8350 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8351 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8353 // Get current values.
8354 $monetary= setlocale (LC_MONETARY, 0);
8355 $numeric = setlocale (LC_NUMERIC, 0);
8356 $ctype = setlocale (LC_CTYPE, 0);
8357 if ($CFG->ostype != 'WINDOWS') {
8358 $messages= setlocale (LC_MESSAGES, 0);
8360 // Set locale to all.
8361 $result = setlocale (LC_ALL, $currentlocale);
8362 // If setting of locale fails try the other utf8 or utf-8 variant,
8363 // some operating systems support both (Debian), others just one (OSX).
8364 if ($result === false) {
8365 if (stripos($currentlocale, '.UTF-8') !== false) {
8366 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8367 setlocale (LC_ALL, $newlocale);
8368 } else if (stripos($currentlocale, '.UTF8') !== false) {
8369 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8370 setlocale (LC_ALL, $newlocale);
8373 // Set old values.
8374 setlocale (LC_MONETARY, $monetary);
8375 setlocale (LC_NUMERIC, $numeric);
8376 if ($CFG->ostype != 'WINDOWS') {
8377 setlocale (LC_MESSAGES, $messages);
8379 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8380 // To workaround a well-known PHP problem with Turkish letter Ii.
8381 setlocale (LC_CTYPE, $ctype);
8386 * Count words in a string.
8388 * Words are defined as things between whitespace.
8390 * @category string
8391 * @param string $string The text to be searched for words. May be HTML.
8392 * @return int The count of words in the specified string
8394 function count_words($string) {
8395 // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8396 // Also, br is a special case because it definitely delimits a word, but has no close tag.
8397 $string = preg_replace('~
8398 ( # Capture the tag we match.
8399 </ # Start of close tag.
8400 (?! # Do not match any of these specific close tag names.
8401 a> | b> | del> | em> | i> |
8402 ins> | s> | small> |
8403 strong> | sub> | sup> | u>
8405 \w+ # But, apart from those execptions, match any tag name.
8406 > # End of close tag.
8408 <br> | <br\s*/> # Special cases that are not close tags.
8410 ~x', '$1 ', $string); // Add a space after the close tag.
8411 // Now remove HTML tags.
8412 $string = strip_tags($string);
8413 // Decode HTML entities.
8414 $string = html_entity_decode($string);
8416 // Now, the word count is the number of blocks of characters separated
8417 // by any sort of space. That seems to be the definition used by all other systems.
8418 // To be precise about what is considered to separate words:
8419 // * Anything that Unicode considers a 'Separator'
8420 // * Anything that Unicode considers a 'Control character'
8421 // * An em- or en- dash.
8422 return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY));
8426 * Count letters in a string.
8428 * Letters are defined as chars not in tags and different from whitespace.
8430 * @category string
8431 * @param string $string The text to be searched for letters. May be HTML.
8432 * @return int The count of letters in the specified text.
8434 function count_letters($string) {
8435 $string = strip_tags($string); // Tags are out now.
8436 $string = html_entity_decode($string);
8437 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8439 return core_text::strlen($string);
8443 * Generate and return a random string of the specified length.
8445 * @param int $length The length of the string to be created.
8446 * @return string
8448 function random_string($length=15) {
8449 $randombytes = random_bytes_emulate($length);
8450 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8451 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8452 $pool .= '0123456789';
8453 $poollen = strlen($pool);
8454 $string = '';
8455 for ($i = 0; $i < $length; $i++) {
8456 $rand = ord($randombytes[$i]);
8457 $string .= substr($pool, ($rand%($poollen)), 1);
8459 return $string;
8463 * Generate a complex random string (useful for md5 salts)
8465 * This function is based on the above {@link random_string()} however it uses a
8466 * larger pool of characters and generates a string between 24 and 32 characters
8468 * @param int $length Optional if set generates a string to exactly this length
8469 * @return string
8471 function complex_random_string($length=null) {
8472 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8473 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8474 $poollen = strlen($pool);
8475 if ($length===null) {
8476 $length = floor(rand(24, 32));
8478 $randombytes = random_bytes_emulate($length);
8479 $string = '';
8480 for ($i = 0; $i < $length; $i++) {
8481 $rand = ord($randombytes[$i]);
8482 $string .= $pool[($rand%$poollen)];
8484 return $string;
8488 * Try to generates cryptographically secure pseudo-random bytes.
8490 * Note this is achieved by fallbacking between:
8491 * - PHP 7 random_bytes().
8492 * - OpenSSL openssl_random_pseudo_bytes().
8493 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8495 * @param int $length requested length in bytes
8496 * @return string binary data
8498 function random_bytes_emulate($length) {
8499 global $CFG;
8500 if ($length <= 0) {
8501 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8502 return '';
8504 if (function_exists('random_bytes')) {
8505 // Use PHP 7 goodness.
8506 $hash = @random_bytes($length);
8507 if ($hash !== false) {
8508 return $hash;
8511 if (function_exists('openssl_random_pseudo_bytes')) {
8512 // If you have the openssl extension enabled.
8513 $hash = openssl_random_pseudo_bytes($length);
8514 if ($hash !== false) {
8515 return $hash;
8519 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8520 $staticdata = serialize($CFG) . serialize($_SERVER);
8521 $hash = '';
8522 do {
8523 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8524 } while (strlen($hash) < $length);
8526 return substr($hash, 0, $length);
8530 * Given some text (which may contain HTML) and an ideal length,
8531 * this function truncates the text neatly on a word boundary if possible
8533 * @category string
8534 * @param string $text text to be shortened
8535 * @param int $ideal ideal string length
8536 * @param boolean $exact if false, $text will not be cut mid-word
8537 * @param string $ending The string to append if the passed string is truncated
8538 * @return string $truncate shortened string
8540 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8541 // If the plain text is shorter than the maximum length, return the whole text.
8542 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8543 return $text;
8546 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8547 // and only tag in its 'line'.
8548 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8550 $totallength = core_text::strlen($ending);
8551 $truncate = '';
8553 // This array stores information about open and close tags and their position
8554 // in the truncated string. Each item in the array is an object with fields
8555 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8556 // (byte position in truncated text).
8557 $tagdetails = array();
8559 foreach ($lines as $linematchings) {
8560 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8561 if (!empty($linematchings[1])) {
8562 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8563 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8564 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8565 // Record closing tag.
8566 $tagdetails[] = (object) array(
8567 'open' => false,
8568 'tag' => core_text::strtolower($tagmatchings[1]),
8569 'pos' => core_text::strlen($truncate),
8572 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8573 // Record opening tag.
8574 $tagdetails[] = (object) array(
8575 'open' => true,
8576 'tag' => core_text::strtolower($tagmatchings[1]),
8577 'pos' => core_text::strlen($truncate),
8579 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8580 $tagdetails[] = (object) array(
8581 'open' => true,
8582 'tag' => core_text::strtolower('if'),
8583 'pos' => core_text::strlen($truncate),
8585 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8586 $tagdetails[] = (object) array(
8587 'open' => false,
8588 'tag' => core_text::strtolower('if'),
8589 'pos' => core_text::strlen($truncate),
8593 // Add html-tag to $truncate'd text.
8594 $truncate .= $linematchings[1];
8597 // Calculate the length of the plain text part of the line; handle entities as one character.
8598 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8599 if ($totallength + $contentlength > $ideal) {
8600 // The number of characters which are left.
8601 $left = $ideal - $totallength;
8602 $entitieslength = 0;
8603 // Search for html entities.
8604 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)) {
8605 // Calculate the real length of all entities in the legal range.
8606 foreach ($entities[0] as $entity) {
8607 if ($entity[1]+1-$entitieslength <= $left) {
8608 $left--;
8609 $entitieslength += core_text::strlen($entity[0]);
8610 } else {
8611 // No more characters left.
8612 break;
8616 $breakpos = $left + $entitieslength;
8618 // If the words shouldn't be cut in the middle...
8619 if (!$exact) {
8620 // Search the last occurence of a space.
8621 for (; $breakpos > 0; $breakpos--) {
8622 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8623 if ($char === '.' or $char === ' ') {
8624 $breakpos += 1;
8625 break;
8626 } else if (strlen($char) > 2) {
8627 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8628 $breakpos += 1;
8629 break;
8634 if ($breakpos == 0) {
8635 // This deals with the test_shorten_text_no_spaces case.
8636 $breakpos = $left + $entitieslength;
8637 } else if ($breakpos > $left + $entitieslength) {
8638 // This deals with the previous for loop breaking on the first char.
8639 $breakpos = $left + $entitieslength;
8642 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8643 // Maximum length is reached, so get off the loop.
8644 break;
8645 } else {
8646 $truncate .= $linematchings[2];
8647 $totallength += $contentlength;
8650 // If the maximum length is reached, get off the loop.
8651 if ($totallength >= $ideal) {
8652 break;
8656 // Add the defined ending to the text.
8657 $truncate .= $ending;
8659 // Now calculate the list of open html tags based on the truncate position.
8660 $opentags = array();
8661 foreach ($tagdetails as $taginfo) {
8662 if ($taginfo->open) {
8663 // Add tag to the beginning of $opentags list.
8664 array_unshift($opentags, $taginfo->tag);
8665 } else {
8666 // Can have multiple exact same open tags, close the last one.
8667 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8668 if ($pos !== false) {
8669 unset($opentags[$pos]);
8674 // Close all unclosed html-tags.
8675 foreach ($opentags as $tag) {
8676 if ($tag === 'if') {
8677 $truncate .= '<!--<![endif]-->';
8678 } else {
8679 $truncate .= '</' . $tag . '>';
8683 return $truncate;
8687 * Shortens a given filename by removing characters positioned after the ideal string length.
8688 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8689 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8691 * @param string $filename file name
8692 * @param int $length ideal string length
8693 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8694 * @return string $shortened shortened file name
8696 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8697 $shortened = $filename;
8698 // Extract a part of the filename if it's char size exceeds the ideal string length.
8699 if (core_text::strlen($filename) > $length) {
8700 // Exclude extension if present in filename.
8701 $mimetypes = get_mimetypes_array();
8702 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8703 if ($extension && !empty($mimetypes[$extension])) {
8704 $basename = pathinfo($filename, PATHINFO_FILENAME);
8705 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8706 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8707 $shortened .= '.' . $extension;
8708 } else {
8709 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8710 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8713 return $shortened;
8717 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8719 * @param array $path The paths to reduce the length.
8720 * @param int $length Ideal string length
8721 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8722 * @return array $result Shortened paths in array.
8724 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8725 $result = null;
8727 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8728 $carry[] = shorten_filename($singlepath, $length, $includehash);
8729 return $carry;
8730 }, []);
8732 return $result;
8736 * Given dates in seconds, how many weeks is the date from startdate
8737 * The first week is 1, the second 2 etc ...
8739 * @param int $startdate Timestamp for the start date
8740 * @param int $thedate Timestamp for the end date
8741 * @return string
8743 function getweek ($startdate, $thedate) {
8744 if ($thedate < $startdate) {
8745 return 0;
8748 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8752 * Returns a randomly generated password of length $maxlen. inspired by
8754 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8755 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8757 * @param int $maxlen The maximum size of the password being generated.
8758 * @return string
8760 function generate_password($maxlen=10) {
8761 global $CFG;
8763 if (empty($CFG->passwordpolicy)) {
8764 $fillers = PASSWORD_DIGITS;
8765 $wordlist = file($CFG->wordlist);
8766 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8767 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8768 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8769 $password = $word1 . $filler1 . $word2;
8770 } else {
8771 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8772 $digits = $CFG->minpassworddigits;
8773 $lower = $CFG->minpasswordlower;
8774 $upper = $CFG->minpasswordupper;
8775 $nonalphanum = $CFG->minpasswordnonalphanum;
8776 $total = $lower + $upper + $digits + $nonalphanum;
8777 // Var minlength should be the greater one of the two ( $minlen and $total ).
8778 $minlen = $minlen < $total ? $total : $minlen;
8779 // Var maxlen can never be smaller than minlen.
8780 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8781 $additional = $maxlen - $total;
8783 // Make sure we have enough characters to fulfill
8784 // complexity requirements.
8785 $passworddigits = PASSWORD_DIGITS;
8786 while ($digits > strlen($passworddigits)) {
8787 $passworddigits .= PASSWORD_DIGITS;
8789 $passwordlower = PASSWORD_LOWER;
8790 while ($lower > strlen($passwordlower)) {
8791 $passwordlower .= PASSWORD_LOWER;
8793 $passwordupper = PASSWORD_UPPER;
8794 while ($upper > strlen($passwordupper)) {
8795 $passwordupper .= PASSWORD_UPPER;
8797 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8798 while ($nonalphanum > strlen($passwordnonalphanum)) {
8799 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8802 // Now mix and shuffle it all.
8803 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8804 substr(str_shuffle ($passwordupper), 0, $upper) .
8805 substr(str_shuffle ($passworddigits), 0, $digits) .
8806 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8807 substr(str_shuffle ($passwordlower .
8808 $passwordupper .
8809 $passworddigits .
8810 $passwordnonalphanum), 0 , $additional));
8813 return substr ($password, 0, $maxlen);
8817 * Given a float, prints it nicely.
8818 * Localized floats must not be used in calculations!
8820 * The stripzeros feature is intended for making numbers look nicer in small
8821 * areas where it is not necessary to indicate the degree of accuracy by showing
8822 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8823 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8825 * @param float $float The float to print
8826 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8827 * @param bool $localized use localized decimal separator
8828 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8829 * the decimal point are always striped if $decimalpoints is -1.
8830 * @return string locale float
8832 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8833 if (is_null($float)) {
8834 return '';
8836 if ($localized) {
8837 $separator = get_string('decsep', 'langconfig');
8838 } else {
8839 $separator = '.';
8841 if ($decimalpoints == -1) {
8842 // The following counts the number of decimals.
8843 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8844 $floatval = floatval($float);
8845 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
8848 $result = number_format($float, $decimalpoints, $separator, '');
8849 if ($stripzeros && $decimalpoints > 0) {
8850 // Remove zeros and final dot if not needed.
8851 // However, only do this if there is a decimal point!
8852 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8854 return $result;
8858 * Converts locale specific floating point/comma number back to standard PHP float value
8859 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8861 * @param string $localefloat locale aware float representation
8862 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8863 * @return mixed float|bool - false or the parsed float.
8865 function unformat_float($localefloat, $strict = false) {
8866 $localefloat = trim((string)$localefloat);
8868 if ($localefloat == '') {
8869 return null;
8872 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8873 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8875 if ($strict && !is_numeric($localefloat)) {
8876 return false;
8879 return (float)$localefloat;
8883 * Given a simple array, this shuffles it up just like shuffle()
8884 * Unlike PHP's shuffle() this function works on any machine.
8886 * @param array $array The array to be rearranged
8887 * @return array
8889 function swapshuffle($array) {
8891 $last = count($array) - 1;
8892 for ($i = 0; $i <= $last; $i++) {
8893 $from = rand(0, $last);
8894 $curr = $array[$i];
8895 $array[$i] = $array[$from];
8896 $array[$from] = $curr;
8898 return $array;
8902 * Like {@link swapshuffle()}, but works on associative arrays
8904 * @param array $array The associative array to be rearranged
8905 * @return array
8907 function swapshuffle_assoc($array) {
8909 $newarray = array();
8910 $newkeys = swapshuffle(array_keys($array));
8912 foreach ($newkeys as $newkey) {
8913 $newarray[$newkey] = $array[$newkey];
8915 return $newarray;
8919 * Given an arbitrary array, and a number of draws,
8920 * this function returns an array with that amount
8921 * of items. The indexes are retained.
8923 * @todo Finish documenting this function
8925 * @param array $array
8926 * @param int $draws
8927 * @return array
8929 function draw_rand_array($array, $draws) {
8931 $return = array();
8933 $last = count($array);
8935 if ($draws > $last) {
8936 $draws = $last;
8939 while ($draws > 0) {
8940 $last--;
8942 $keys = array_keys($array);
8943 $rand = rand(0, $last);
8945 $return[$keys[$rand]] = $array[$keys[$rand]];
8946 unset($array[$keys[$rand]]);
8948 $draws--;
8951 return $return;
8955 * Calculate the difference between two microtimes
8957 * @param string $a The first Microtime
8958 * @param string $b The second Microtime
8959 * @return string
8961 function microtime_diff($a, $b) {
8962 list($adec, $asec) = explode(' ', $a);
8963 list($bdec, $bsec) = explode(' ', $b);
8964 return $bsec - $asec + $bdec - $adec;
8968 * Given a list (eg a,b,c,d,e) this function returns
8969 * an array of 1->a, 2->b, 3->c etc
8971 * @param string $list The string to explode into array bits
8972 * @param string $separator The separator used within the list string
8973 * @return array The now assembled array
8975 function make_menu_from_list($list, $separator=',') {
8977 $array = array_reverse(explode($separator, $list), true);
8978 foreach ($array as $key => $item) {
8979 $outarray[$key+1] = trim($item);
8981 return $outarray;
8985 * Creates an array that represents all the current grades that
8986 * can be chosen using the given grading type.
8988 * Negative numbers
8989 * are scales, zero is no grade, and positive numbers are maximum
8990 * grades.
8992 * @todo Finish documenting this function or better deprecated this completely!
8994 * @param int $gradingtype
8995 * @return array
8997 function make_grades_menu($gradingtype) {
8998 global $DB;
9000 $grades = array();
9001 if ($gradingtype < 0) {
9002 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
9003 return make_menu_from_list($scale->scale);
9005 } else if ($gradingtype > 0) {
9006 for ($i=$gradingtype; $i>=0; $i--) {
9007 $grades[$i] = $i .' / '. $gradingtype;
9009 return $grades;
9011 return $grades;
9015 * make_unique_id_code
9017 * @todo Finish documenting this function
9019 * @uses $_SERVER
9020 * @param string $extra Extra string to append to the end of the code
9021 * @return string
9023 function make_unique_id_code($extra = '') {
9025 $hostname = 'unknownhost';
9026 if (!empty($_SERVER['HTTP_HOST'])) {
9027 $hostname = $_SERVER['HTTP_HOST'];
9028 } else if (!empty($_ENV['HTTP_HOST'])) {
9029 $hostname = $_ENV['HTTP_HOST'];
9030 } else if (!empty($_SERVER['SERVER_NAME'])) {
9031 $hostname = $_SERVER['SERVER_NAME'];
9032 } else if (!empty($_ENV['SERVER_NAME'])) {
9033 $hostname = $_ENV['SERVER_NAME'];
9036 $date = gmdate("ymdHis");
9038 $random = random_string(6);
9040 if ($extra) {
9041 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
9042 } else {
9043 return $hostname .'+'. $date .'+'. $random;
9049 * Function to check the passed address is within the passed subnet
9051 * The parameter is a comma separated string of subnet definitions.
9052 * Subnet strings can be in one of three formats:
9053 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
9054 * 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)
9055 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
9056 * Code for type 1 modified from user posted comments by mediator at
9057 * {@link http://au.php.net/manual/en/function.ip2long.php}
9059 * @param string $addr The address you are checking
9060 * @param string $subnetstr The string of subnet addresses
9061 * @return bool
9063 function address_in_subnet($addr, $subnetstr) {
9065 if ($addr == '0.0.0.0') {
9066 return false;
9068 $subnets = explode(',', $subnetstr);
9069 $found = false;
9070 $addr = trim($addr);
9071 $addr = cleanremoteaddr($addr, false); // Normalise.
9072 if ($addr === null) {
9073 return false;
9075 $addrparts = explode(':', $addr);
9077 $ipv6 = strpos($addr, ':');
9079 foreach ($subnets as $subnet) {
9080 $subnet = trim($subnet);
9081 if ($subnet === '') {
9082 continue;
9085 if (strpos($subnet, '/') !== false) {
9086 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
9087 list($ip, $mask) = explode('/', $subnet);
9088 $mask = trim($mask);
9089 if (!is_number($mask)) {
9090 continue; // Incorect mask number, eh?
9092 $ip = cleanremoteaddr($ip, false); // Normalise.
9093 if ($ip === null) {
9094 continue;
9096 if (strpos($ip, ':') !== false) {
9097 // IPv6.
9098 if (!$ipv6) {
9099 continue;
9101 if ($mask > 128 or $mask < 0) {
9102 continue; // Nonsense.
9104 if ($mask == 0) {
9105 return true; // Any address.
9107 if ($mask == 128) {
9108 if ($ip === $addr) {
9109 return true;
9111 continue;
9113 $ipparts = explode(':', $ip);
9114 $modulo = $mask % 16;
9115 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9116 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9117 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9118 if ($modulo == 0) {
9119 return true;
9121 $pos = ($mask-$modulo)/16;
9122 $ipnet = hexdec($ipparts[$pos]);
9123 $addrnet = hexdec($addrparts[$pos]);
9124 $mask = 0xffff << (16 - $modulo);
9125 if (($addrnet & $mask) == ($ipnet & $mask)) {
9126 return true;
9130 } else {
9131 // IPv4.
9132 if ($ipv6) {
9133 continue;
9135 if ($mask > 32 or $mask < 0) {
9136 continue; // Nonsense.
9138 if ($mask == 0) {
9139 return true;
9141 if ($mask == 32) {
9142 if ($ip === $addr) {
9143 return true;
9145 continue;
9147 $mask = 0xffffffff << (32 - $mask);
9148 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9149 return true;
9153 } else if (strpos($subnet, '-') !== false) {
9154 // 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.
9155 $parts = explode('-', $subnet);
9156 if (count($parts) != 2) {
9157 continue;
9160 if (strpos($subnet, ':') !== false) {
9161 // IPv6.
9162 if (!$ipv6) {
9163 continue;
9165 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9166 if ($ipstart === null) {
9167 continue;
9169 $ipparts = explode(':', $ipstart);
9170 $start = hexdec(array_pop($ipparts));
9171 $ipparts[] = trim($parts[1]);
9172 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9173 if ($ipend === null) {
9174 continue;
9176 $ipparts[7] = '';
9177 $ipnet = implode(':', $ipparts);
9178 if (strpos($addr, $ipnet) !== 0) {
9179 continue;
9181 $ipparts = explode(':', $ipend);
9182 $end = hexdec($ipparts[7]);
9184 $addrend = hexdec($addrparts[7]);
9186 if (($addrend >= $start) and ($addrend <= $end)) {
9187 return true;
9190 } else {
9191 // IPv4.
9192 if ($ipv6) {
9193 continue;
9195 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9196 if ($ipstart === null) {
9197 continue;
9199 $ipparts = explode('.', $ipstart);
9200 $ipparts[3] = trim($parts[1]);
9201 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9202 if ($ipend === null) {
9203 continue;
9206 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9207 return true;
9211 } else {
9212 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9213 if (strpos($subnet, ':') !== false) {
9214 // IPv6.
9215 if (!$ipv6) {
9216 continue;
9218 $parts = explode(':', $subnet);
9219 $count = count($parts);
9220 if ($parts[$count-1] === '') {
9221 unset($parts[$count-1]); // Trim trailing :'s.
9222 $count--;
9223 $subnet = implode('.', $parts);
9225 $isip = cleanremoteaddr($subnet, false); // Normalise.
9226 if ($isip !== null) {
9227 if ($isip === $addr) {
9228 return true;
9230 continue;
9231 } else if ($count > 8) {
9232 continue;
9234 $zeros = array_fill(0, 8-$count, '0');
9235 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9236 if (address_in_subnet($addr, $subnet)) {
9237 return true;
9240 } else {
9241 // IPv4.
9242 if ($ipv6) {
9243 continue;
9245 $parts = explode('.', $subnet);
9246 $count = count($parts);
9247 if ($parts[$count-1] === '') {
9248 unset($parts[$count-1]); // Trim trailing .
9249 $count--;
9250 $subnet = implode('.', $parts);
9252 if ($count == 4) {
9253 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9254 if ($subnet === $addr) {
9255 return true;
9257 continue;
9258 } else if ($count > 4) {
9259 continue;
9261 $zeros = array_fill(0, 4-$count, '0');
9262 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9263 if (address_in_subnet($addr, $subnet)) {
9264 return true;
9270 return false;
9274 * For outputting debugging info
9276 * @param string $string The string to write
9277 * @param string $eol The end of line char(s) to use
9278 * @param string $sleep Period to make the application sleep
9279 * This ensures any messages have time to display before redirect
9281 function mtrace($string, $eol="\n", $sleep=0) {
9282 global $CFG;
9284 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
9285 $fn = $CFG->mtrace_wrapper;
9286 $fn($string, $eol);
9287 return;
9288 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
9289 // We must explicitly call the add_line function here.
9290 // Uses of fwrite to STDOUT are not picked up by ob_start.
9291 if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
9292 fwrite(STDOUT, $output);
9294 } else {
9295 echo $string . $eol;
9298 // Flush again.
9299 flush();
9301 // Delay to keep message on user's screen in case of subsequent redirect.
9302 if ($sleep) {
9303 sleep($sleep);
9308 * Replace 1 or more slashes or backslashes to 1 slash
9310 * @param string $path The path to strip
9311 * @return string the path with double slashes removed
9313 function cleardoubleslashes ($path) {
9314 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9318 * Is the current ip in a given list?
9320 * @param string $list
9321 * @return bool
9323 function remoteip_in_list($list) {
9324 $clientip = getremoteaddr(null);
9326 if (!$clientip) {
9327 // Ensure access on cli.
9328 return true;
9330 return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
9334 * Returns most reliable client address
9336 * @param string $default If an address can't be determined, then return this
9337 * @return string The remote IP address
9339 function getremoteaddr($default='0.0.0.0') {
9340 global $CFG;
9342 if (!isset($CFG->getremoteaddrconf)) {
9343 // This will happen, for example, before just after the upgrade, as the
9344 // user is redirected to the admin screen.
9345 $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT;
9346 } else {
9347 $variablestoskip = $CFG->getremoteaddrconf;
9349 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9350 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9351 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9352 return $address ? $address : $default;
9355 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9356 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9357 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9359 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9360 global $CFG;
9361 return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
9364 // Multiple proxies can append values to this header including an
9365 // untrusted original request header so we must only trust the last ip.
9366 $address = end($forwardedaddresses);
9368 if (substr_count($address, ":") > 1) {
9369 // Remove port and brackets from IPv6.
9370 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9371 $address = $matches[1];
9373 } else {
9374 // Remove port from IPv4.
9375 if (substr_count($address, ":") == 1) {
9376 $parts = explode(":", $address);
9377 $address = $parts[0];
9381 $address = cleanremoteaddr($address);
9382 return $address ? $address : $default;
9385 if (!empty($_SERVER['REMOTE_ADDR'])) {
9386 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9387 return $address ? $address : $default;
9388 } else {
9389 return $default;
9394 * Cleans an ip address. Internal addresses are now allowed.
9395 * (Originally local addresses were not allowed.)
9397 * @param string $addr IPv4 or IPv6 address
9398 * @param bool $compress use IPv6 address compression
9399 * @return string normalised ip address string, null if error
9401 function cleanremoteaddr($addr, $compress=false) {
9402 $addr = trim($addr);
9404 if (strpos($addr, ':') !== false) {
9405 // Can be only IPv6.
9406 $parts = explode(':', $addr);
9407 $count = count($parts);
9409 if (strpos($parts[$count-1], '.') !== false) {
9410 // Legacy ipv4 notation.
9411 $last = array_pop($parts);
9412 $ipv4 = cleanremoteaddr($last, true);
9413 if ($ipv4 === null) {
9414 return null;
9416 $bits = explode('.', $ipv4);
9417 $parts[] = dechex($bits[0]).dechex($bits[1]);
9418 $parts[] = dechex($bits[2]).dechex($bits[3]);
9419 $count = count($parts);
9420 $addr = implode(':', $parts);
9423 if ($count < 3 or $count > 8) {
9424 return null; // Severly malformed.
9427 if ($count != 8) {
9428 if (strpos($addr, '::') === false) {
9429 return null; // Malformed.
9431 // Uncompress.
9432 $insertat = array_search('', $parts, true);
9433 $missing = array_fill(0, 1 + 8 - $count, '0');
9434 array_splice($parts, $insertat, 1, $missing);
9435 foreach ($parts as $key => $part) {
9436 if ($part === '') {
9437 $parts[$key] = '0';
9442 $adr = implode(':', $parts);
9443 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9444 return null; // Incorrect format - sorry.
9447 // Normalise 0s and case.
9448 $parts = array_map('hexdec', $parts);
9449 $parts = array_map('dechex', $parts);
9451 $result = implode(':', $parts);
9453 if (!$compress) {
9454 return $result;
9457 if ($result === '0:0:0:0:0:0:0:0') {
9458 return '::'; // All addresses.
9461 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9462 if ($compressed !== $result) {
9463 return $compressed;
9466 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9467 if ($compressed !== $result) {
9468 return $compressed;
9471 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9472 if ($compressed !== $result) {
9473 return $compressed;
9476 return $result;
9479 // First get all things that look like IPv4 addresses.
9480 $parts = array();
9481 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9482 return null;
9484 unset($parts[0]);
9486 foreach ($parts as $key => $match) {
9487 if ($match > 255) {
9488 return null;
9490 $parts[$key] = (int)$match; // Normalise 0s.
9493 return implode('.', $parts);
9498 * Is IP address a public address?
9500 * @param string $ip The ip to check
9501 * @return bool true if the ip is public
9503 function ip_is_public($ip) {
9504 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9508 * This function will make a complete copy of anything it's given,
9509 * regardless of whether it's an object or not.
9511 * @param mixed $thing Something you want cloned
9512 * @return mixed What ever it is you passed it
9514 function fullclone($thing) {
9515 return unserialize(serialize($thing));
9519 * Used to make sure that $min <= $value <= $max
9521 * Make sure that value is between min, and max
9523 * @param int $min The minimum value
9524 * @param int $value The value to check
9525 * @param int $max The maximum value
9526 * @return int
9528 function bounded_number($min, $value, $max) {
9529 if ($value < $min) {
9530 return $min;
9532 if ($value > $max) {
9533 return $max;
9535 return $value;
9539 * Check if there is a nested array within the passed array
9541 * @param array $array
9542 * @return bool true if there is a nested array false otherwise
9544 function array_is_nested($array) {
9545 foreach ($array as $value) {
9546 if (is_array($value)) {
9547 return true;
9550 return false;
9554 * get_performance_info() pairs up with init_performance_info()
9555 * loaded in setup.php. Returns an array with 'html' and 'txt'
9556 * values ready for use, and each of the individual stats provided
9557 * separately as well.
9559 * @return array
9561 function get_performance_info() {
9562 global $CFG, $PERF, $DB, $PAGE;
9564 $info = array();
9565 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9567 $info['html'] = '';
9568 if (!empty($CFG->themedesignermode)) {
9569 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9570 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9572 $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
9574 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9576 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9577 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9579 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9580 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9582 if (function_exists('memory_get_usage')) {
9583 $info['memory_total'] = memory_get_usage();
9584 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9585 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9586 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9587 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9590 if (function_exists('memory_get_peak_usage')) {
9591 $info['memory_peak'] = memory_get_peak_usage();
9592 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9593 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9596 $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9597 $inc = get_included_files();
9598 $info['includecount'] = count($inc);
9599 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9600 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9602 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9603 // We can not track more performance before installation or before PAGE init, sorry.
9604 return $info;
9607 $filtermanager = filter_manager::instance();
9608 if (method_exists($filtermanager, 'get_performance_summary')) {
9609 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9610 $info = array_merge($filterinfo, $info);
9611 foreach ($filterinfo as $key => $value) {
9612 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9613 $info['txt'] .= "$key: $value ";
9617 $stringmanager = get_string_manager();
9618 if (method_exists($stringmanager, 'get_performance_summary')) {
9619 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9620 $info = array_merge($filterinfo, $info);
9621 foreach ($filterinfo as $key => $value) {
9622 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9623 $info['txt'] .= "$key: $value ";
9627 if (!empty($PERF->logwrites)) {
9628 $info['logwrites'] = $PERF->logwrites;
9629 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9630 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9633 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9634 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9635 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9637 if ($DB->want_read_slave()) {
9638 $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9639 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9640 $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9643 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9644 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9645 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9647 if (function_exists('posix_times')) {
9648 $ptimes = posix_times();
9649 if (is_array($ptimes)) {
9650 foreach ($ptimes as $key => $val) {
9651 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9653 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9654 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9655 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9659 // Grab the load average for the last minute.
9660 // /proc will only work under some linux configurations
9661 // while uptime is there under MacOSX/Darwin and other unices.
9662 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9663 list($serverload) = explode(' ', $loadavg[0]);
9664 unset($loadavg);
9665 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9666 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9667 $serverload = $matches[1];
9668 } else {
9669 trigger_error('Could not parse uptime output!');
9672 if (!empty($serverload)) {
9673 $info['serverload'] = $serverload;
9674 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9675 $info['txt'] .= "serverload: {$info['serverload']} ";
9678 // Display size of session if session started.
9679 if ($si = \core\session\manager::get_performance_info()) {
9680 $info['sessionsize'] = $si['size'];
9681 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9682 $info['txt'] .= $si['txt'];
9685 // Display time waiting for session if applicable.
9686 if (!empty($PERF->sessionlock['wait'])) {
9687 $sessionwait = number_format($PERF->sessionlock['wait'], 3) . ' secs';
9688 $info['html'] .= html_writer::tag('li', 'Session wait: ' . $sessionwait, [
9689 'class' => 'sessionwait col-sm-4'
9691 $info['txt'] .= 'sessionwait: ' . $sessionwait . ' ';
9694 $info['html'] .= '</ul>';
9695 $html = '';
9696 if ($stats = cache_helper::get_stats()) {
9698 $table = new html_table();
9699 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9700 $table->head = ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S', 'I/O'];
9701 $table->data = [];
9702 $table->align = ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right', 'right'];
9704 $text = 'Caches used (hits/misses/sets): ';
9705 $hits = 0;
9706 $misses = 0;
9707 $sets = 0;
9708 $maxstores = 0;
9710 // We want to align static caches into their own column.
9711 $hasstatic = false;
9712 foreach ($stats as $definition => $details) {
9713 $numstores = count($details['stores']);
9714 $first = key($details['stores']);
9715 if ($first !== cache_store::STATIC_ACCEL) {
9716 $numstores++; // Add a blank space for the missing static store.
9718 $maxstores = max($maxstores, $numstores);
9721 $storec = 0;
9723 while ($storec++ < ($maxstores - 2)) {
9724 if ($storec == ($maxstores - 2)) {
9725 $table->head[] = get_string('mappingfinal', 'cache');
9726 } else {
9727 $table->head[] = "Store $storec";
9729 $table->align[] = 'left';
9730 $table->align[] = 'right';
9731 $table->align[] = 'right';
9732 $table->align[] = 'right';
9733 $table->align[] = 'right';
9734 $table->head[] = 'H';
9735 $table->head[] = 'M';
9736 $table->head[] = 'S';
9737 $table->head[] = 'I/O';
9740 ksort($stats);
9742 foreach ($stats as $definition => $details) {
9743 switch ($details['mode']) {
9744 case cache_store::MODE_APPLICATION:
9745 $modeclass = 'application';
9746 $mode = ' <span title="application cache">App</span>';
9747 break;
9748 case cache_store::MODE_SESSION:
9749 $modeclass = 'session';
9750 $mode = ' <span title="session cache">Ses</span>';
9751 break;
9752 case cache_store::MODE_REQUEST:
9753 $modeclass = 'request';
9754 $mode = ' <span title="request cache">Req</span>';
9755 break;
9757 $row = [$mode, $definition];
9759 $text .= "$definition {";
9761 $storec = 0;
9762 foreach ($details['stores'] as $store => $data) {
9764 if ($storec == 0 && $store !== cache_store::STATIC_ACCEL) {
9765 $row[] = '';
9766 $row[] = '';
9767 $row[] = '';
9768 $storec++;
9771 $hits += $data['hits'];
9772 $misses += $data['misses'];
9773 $sets += $data['sets'];
9774 if ($data['hits'] == 0 and $data['misses'] > 0) {
9775 $cachestoreclass = 'nohits bg-danger';
9776 } else if ($data['hits'] < $data['misses']) {
9777 $cachestoreclass = 'lowhits bg-warning text-dark';
9778 } else {
9779 $cachestoreclass = 'hihits';
9781 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9782 $cell = new html_table_cell($store);
9783 $cell->attributes = ['class' => $cachestoreclass];
9784 $row[] = $cell;
9785 $cell = new html_table_cell($data['hits']);
9786 $cell->attributes = ['class' => $cachestoreclass];
9787 $row[] = $cell;
9788 $cell = new html_table_cell($data['misses']);
9789 $cell->attributes = ['class' => $cachestoreclass];
9790 $row[] = $cell;
9792 if ($store !== cache_store::STATIC_ACCEL) {
9793 // The static cache is never set.
9794 $cell = new html_table_cell($data['sets']);
9795 $cell->attributes = ['class' => $cachestoreclass];
9796 $row[] = $cell;
9798 if ($data['hits'] || $data['sets']) {
9799 if ($data['iobytes'] === cache_store::IO_BYTES_NOT_SUPPORTED) {
9800 $size = '-';
9801 } else {
9802 $size = display_size($data['iobytes'], 1, 'KB');
9803 if ($data['iobytes'] >= 10 * 1024) {
9804 $cachestoreclass = ' bg-warning text-dark';
9807 } else {
9808 $size = '';
9810 $cell = new html_table_cell($size);
9811 $cell->attributes = ['class' => $cachestoreclass];
9812 $row[] = $cell;
9814 $storec++;
9816 while ($storec++ < $maxstores) {
9817 $row[] = '';
9818 $row[] = '';
9819 $row[] = '';
9820 $row[] = '';
9821 $row[] = '';
9823 $text .= '} ';
9825 $table->data[] = $row;
9828 $html .= html_writer::table($table);
9830 // Now lets also show sub totals for each cache store.
9831 $storetotals = [];
9832 $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9833 foreach ($stats as $definition => $details) {
9834 foreach ($details['stores'] as $store => $data) {
9835 if (!array_key_exists($store, $storetotals)) {
9836 $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9838 $storetotals[$store]['class'] = $data['class'];
9839 $storetotals[$store]['hits'] += $data['hits'];
9840 $storetotals[$store]['misses'] += $data['misses'];
9841 $storetotals[$store]['sets'] += $data['sets'];
9842 $storetotal['hits'] += $data['hits'];
9843 $storetotal['misses'] += $data['misses'];
9844 $storetotal['sets'] += $data['sets'];
9845 if ($data['iobytes'] !== cache_store::IO_BYTES_NOT_SUPPORTED) {
9846 $storetotals[$store]['iobytes'] += $data['iobytes'];
9847 $storetotal['iobytes'] += $data['iobytes'];
9852 $table = new html_table();
9853 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9854 $table->head = [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S', 'I/O'];
9855 $table->data = [];
9856 $table->align = ['left', 'left', 'right', 'right', 'right', 'right'];
9858 ksort($storetotals);
9860 foreach ($storetotals as $store => $data) {
9861 $row = [];
9862 if ($data['hits'] == 0 and $data['misses'] > 0) {
9863 $cachestoreclass = 'nohits bg-danger';
9864 } else if ($data['hits'] < $data['misses']) {
9865 $cachestoreclass = 'lowhits bg-warning text-dark';
9866 } else {
9867 $cachestoreclass = 'hihits';
9869 $cell = new html_table_cell($store);
9870 $cell->attributes = ['class' => $cachestoreclass];
9871 $row[] = $cell;
9872 $cell = new html_table_cell($data['class']);
9873 $cell->attributes = ['class' => $cachestoreclass];
9874 $row[] = $cell;
9875 $cell = new html_table_cell($data['hits']);
9876 $cell->attributes = ['class' => $cachestoreclass];
9877 $row[] = $cell;
9878 $cell = new html_table_cell($data['misses']);
9879 $cell->attributes = ['class' => $cachestoreclass];
9880 $row[] = $cell;
9881 $cell = new html_table_cell($data['sets']);
9882 $cell->attributes = ['class' => $cachestoreclass];
9883 $row[] = $cell;
9884 if ($data['hits'] || $data['sets']) {
9885 if ($data['iobytes']) {
9886 $size = display_size($data['iobytes'], 1, 'KB');
9887 } else {
9888 $size = '-';
9890 } else {
9891 $size = '';
9893 $cell = new html_table_cell($size);
9894 $cell->attributes = ['class' => $cachestoreclass];
9895 $row[] = $cell;
9896 $table->data[] = $row;
9898 if (!empty($storetotal['iobytes'])) {
9899 $size = display_size($storetotal['iobytes'], 1, 'KB');
9900 } else if (!empty($storetotal['hits']) || !empty($storetotal['sets'])) {
9901 $size = '-';
9902 } else {
9903 $size = '';
9905 $row = [
9906 get_string('total'),
9908 $storetotal['hits'],
9909 $storetotal['misses'],
9910 $storetotal['sets'],
9911 $size,
9913 $table->data[] = $row;
9915 $html .= html_writer::table($table);
9917 $info['cachesused'] = "$hits / $misses / $sets";
9918 $info['html'] .= $html;
9919 $info['txt'] .= $text.'. ';
9920 } else {
9921 $info['cachesused'] = '0 / 0 / 0';
9922 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9923 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9926 // Display lock information if any.
9927 if (!empty($PERF->locks)) {
9928 $table = new html_table();
9929 $table->attributes['class'] = 'locktimings table table-dark table-sm w-auto table-bordered';
9930 $table->head = ['Lock', 'Waited (s)', 'Obtained', 'Held for (s)'];
9931 $table->align = ['left', 'right', 'center', 'right'];
9932 $table->data = [];
9933 $text = 'Locks (waited/obtained/held):';
9934 foreach ($PERF->locks as $locktiming) {
9935 $row = [];
9936 $row[] = s($locktiming->type . '/' . $locktiming->resource);
9937 $text .= ' ' . $locktiming->type . '/' . $locktiming->resource . ' (';
9939 // The time we had to wait to get the lock.
9940 $roundedtime = number_format($locktiming->wait, 1);
9941 $cell = new html_table_cell($roundedtime);
9942 if ($locktiming->wait > 0.5) {
9943 $cell->attributes = ['class' => 'bg-warning text-dark'];
9945 $row[] = $cell;
9946 $text .= $roundedtime . '/';
9948 // Show a tick or cross for success.
9949 $row[] = $locktiming->success ? '&#x2713;' : '&#x274c;';
9950 $text .= ($locktiming->success ? 'y' : 'n') . '/';
9952 // If applicable, show how long we held the lock before releasing it.
9953 if (property_exists($locktiming, 'held')) {
9954 $roundedtime = number_format($locktiming->held, 1);
9955 $cell = new html_table_cell($roundedtime);
9956 if ($locktiming->held > 0.5) {
9957 $cell->attributes = ['class' => 'bg-warning text-dark'];
9959 $row[] = $cell;
9960 $text .= $roundedtime;
9961 } else {
9962 $row[] = '-';
9963 $text .= '-';
9965 $text .= ')';
9967 $table->data[] = $row;
9969 $info['html'] .= html_writer::table($table);
9970 $info['txt'] .= $text . '. ';
9973 $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto pt-3">'.$info['html'].'</div>';
9974 return $info;
9978 * Renames a file or directory to a unique name within the same directory.
9980 * This function is designed to avoid any potential race conditions, and select an unused name.
9982 * @param string $filepath Original filepath
9983 * @param string $prefix Prefix to use for the temporary name
9984 * @return string|bool New file path or false if failed
9985 * @since Moodle 3.10
9987 function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
9988 $dir = dirname($filepath);
9989 $basename = $dir . '/' . $prefix;
9990 $limit = 0;
9991 while ($limit < 100) {
9992 // Select a new name based on a random number.
9993 $newfilepath = $basename . md5(mt_rand());
9995 // Attempt a rename to that new name.
9996 if (@rename($filepath, $newfilepath)) {
9997 return $newfilepath;
10000 // The first time, do some sanity checks, maybe it is failing for a good reason and there
10001 // is no point trying 100 times if so.
10002 if ($limit === 0 && (!file_exists($filepath) || !is_writable($dir))) {
10003 return false;
10005 $limit++;
10007 return false;
10011 * Delete directory or only its content
10013 * @param string $dir directory path
10014 * @param bool $contentonly
10015 * @return bool success, true also if dir does not exist
10017 function remove_dir($dir, $contentonly=false) {
10018 if (!is_dir($dir)) {
10019 // Nothing to do.
10020 return true;
10023 if (!$contentonly) {
10024 // Start by renaming the directory; this will guarantee that other processes don't write to it
10025 // while it is in the process of being deleted.
10026 $tempdir = rename_to_unused_name($dir);
10027 if ($tempdir) {
10028 // If the rename was successful then delete the $tempdir instead.
10029 $dir = $tempdir;
10031 // If the rename fails, we will continue through and attempt to delete the directory
10032 // without renaming it since that is likely to at least delete most of the files.
10035 if (!$handle = opendir($dir)) {
10036 return false;
10038 $result = true;
10039 while (false!==($item = readdir($handle))) {
10040 if ($item != '.' && $item != '..') {
10041 if (is_dir($dir.'/'.$item)) {
10042 $result = remove_dir($dir.'/'.$item) && $result;
10043 } else {
10044 $result = unlink($dir.'/'.$item) && $result;
10048 closedir($handle);
10049 if ($contentonly) {
10050 clearstatcache(); // Make sure file stat cache is properly invalidated.
10051 return $result;
10053 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
10054 clearstatcache(); // Make sure file stat cache is properly invalidated.
10055 return $result;
10059 * Detect if an object or a class contains a given property
10060 * will take an actual object or the name of a class
10062 * @param mix $obj Name of class or real object to test
10063 * @param string $property name of property to find
10064 * @return bool true if property exists
10066 function object_property_exists( $obj, $property ) {
10067 if (is_string( $obj )) {
10068 $properties = get_class_vars( $obj );
10069 } else {
10070 $properties = get_object_vars( $obj );
10072 return array_key_exists( $property, $properties );
10076 * Converts an object into an associative array
10078 * This function converts an object into an associative array by iterating
10079 * over its public properties. Because this function uses the foreach
10080 * construct, Iterators are respected. It works recursively on arrays of objects.
10081 * Arrays and simple values are returned as is.
10083 * If class has magic properties, it can implement IteratorAggregate
10084 * and return all available properties in getIterator()
10086 * @param mixed $var
10087 * @return array
10089 function convert_to_array($var) {
10090 $result = array();
10092 // Loop over elements/properties.
10093 foreach ($var as $key => $value) {
10094 // Recursively convert objects.
10095 if (is_object($value) || is_array($value)) {
10096 $result[$key] = convert_to_array($value);
10097 } else {
10098 // Simple values are untouched.
10099 $result[$key] = $value;
10102 return $result;
10106 * Detect a custom script replacement in the data directory that will
10107 * replace an existing moodle script
10109 * @return string|bool full path name if a custom script exists, false if no custom script exists
10111 function custom_script_path() {
10112 global $CFG, $SCRIPT;
10114 if ($SCRIPT === null) {
10115 // Probably some weird external script.
10116 return false;
10119 $scriptpath = $CFG->customscripts . $SCRIPT;
10121 // Check the custom script exists.
10122 if (file_exists($scriptpath) and is_file($scriptpath)) {
10123 return $scriptpath;
10124 } else {
10125 return false;
10130 * Returns whether or not the user object is a remote MNET user. This function
10131 * is in moodlelib because it does not rely on loading any of the MNET code.
10133 * @param object $user A valid user object
10134 * @return bool True if the user is from a remote Moodle.
10136 function is_mnet_remote_user($user) {
10137 global $CFG;
10139 if (!isset($CFG->mnet_localhost_id)) {
10140 include_once($CFG->dirroot . '/mnet/lib.php');
10141 $env = new mnet_environment();
10142 $env->init();
10143 unset($env);
10146 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
10150 * This function will search for browser prefereed languages, setting Moodle
10151 * to use the best one available if $SESSION->lang is undefined
10153 function setup_lang_from_browser() {
10154 global $CFG, $SESSION, $USER;
10156 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
10157 // Lang is defined in session or user profile, nothing to do.
10158 return;
10161 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
10162 return;
10165 // Extract and clean langs from headers.
10166 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
10167 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
10168 $rawlangs = explode(',', $rawlangs); // Convert to array.
10169 $langs = array();
10171 $order = 1.0;
10172 foreach ($rawlangs as $lang) {
10173 if (strpos($lang, ';') === false) {
10174 $langs[(string)$order] = $lang;
10175 $order = $order-0.01;
10176 } else {
10177 $parts = explode(';', $lang);
10178 $pos = strpos($parts[1], '=');
10179 $langs[substr($parts[1], $pos+1)] = $parts[0];
10182 krsort($langs, SORT_NUMERIC);
10184 // Look for such langs under standard locations.
10185 foreach ($langs as $lang) {
10186 // Clean it properly for include.
10187 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
10188 if (get_string_manager()->translation_exists($lang, false)) {
10189 // Lang exists, set it in session.
10190 $SESSION->lang = $lang;
10191 // We have finished. Go out.
10192 break;
10195 return;
10199 * Check if $url matches anything in proxybypass list
10201 * Any errors just result in the proxy being used (least bad)
10203 * @param string $url url to check
10204 * @return boolean true if we should bypass the proxy
10206 function is_proxybypass( $url ) {
10207 global $CFG;
10209 // Sanity check.
10210 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
10211 return false;
10214 // Get the host part out of the url.
10215 if (!$host = parse_url( $url, PHP_URL_HOST )) {
10216 return false;
10219 // Get the possible bypass hosts into an array.
10220 $matches = explode( ',', $CFG->proxybypass );
10222 // Check for a match.
10223 // (IPs need to match the left hand side and hosts the right of the url,
10224 // but we can recklessly check both as there can't be a false +ve).
10225 foreach ($matches as $match) {
10226 $match = trim($match);
10228 // Try for IP match (Left side).
10229 $lhs = substr($host, 0, strlen($match));
10230 if (strcasecmp($match, $lhs)==0) {
10231 return true;
10234 // Try for host match (Right side).
10235 $rhs = substr($host, -strlen($match));
10236 if (strcasecmp($match, $rhs)==0) {
10237 return true;
10241 // Nothing matched.
10242 return false;
10246 * Check if the passed navigation is of the new style
10248 * @param mixed $navigation
10249 * @return bool true for yes false for no
10251 function is_newnav($navigation) {
10252 if (is_array($navigation) && !empty($navigation['newnav'])) {
10253 return true;
10254 } else {
10255 return false;
10260 * Checks whether the given variable name is defined as a variable within the given object.
10262 * This will NOT work with stdClass objects, which have no class variables.
10264 * @param string $var The variable name
10265 * @param object $object The object to check
10266 * @return boolean
10268 function in_object_vars($var, $object) {
10269 $classvars = get_class_vars(get_class($object));
10270 $classvars = array_keys($classvars);
10271 return in_array($var, $classvars);
10275 * Returns an array without repeated objects.
10276 * This function is similar to array_unique, but for arrays that have objects as values
10278 * @param array $array
10279 * @param bool $keepkeyassoc
10280 * @return array
10282 function object_array_unique($array, $keepkeyassoc = true) {
10283 $duplicatekeys = array();
10284 $tmp = array();
10286 foreach ($array as $key => $val) {
10287 // Convert objects to arrays, in_array() does not support objects.
10288 if (is_object($val)) {
10289 $val = (array)$val;
10292 if (!in_array($val, $tmp)) {
10293 $tmp[] = $val;
10294 } else {
10295 $duplicatekeys[] = $key;
10299 foreach ($duplicatekeys as $key) {
10300 unset($array[$key]);
10303 return $keepkeyassoc ? $array : array_values($array);
10307 * Is a userid the primary administrator?
10309 * @param int $userid int id of user to check
10310 * @return boolean
10312 function is_primary_admin($userid) {
10313 $primaryadmin = get_admin();
10315 if ($userid == $primaryadmin->id) {
10316 return true;
10317 } else {
10318 return false;
10323 * Returns the site identifier
10325 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10327 function get_site_identifier() {
10328 global $CFG;
10329 // Check to see if it is missing. If so, initialise it.
10330 if (empty($CFG->siteidentifier)) {
10331 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10333 // Return it.
10334 return $CFG->siteidentifier;
10338 * Check whether the given password has no more than the specified
10339 * number of consecutive identical characters.
10341 * @param string $password password to be checked against the password policy
10342 * @param integer $maxchars maximum number of consecutive identical characters
10343 * @return bool
10345 function check_consecutive_identical_characters($password, $maxchars) {
10347 if ($maxchars < 1) {
10348 return true; // Zero 0 is to disable this check.
10350 if (strlen($password) <= $maxchars) {
10351 return true; // Too short to fail this test.
10354 $previouschar = '';
10355 $consecutivecount = 1;
10356 foreach (str_split($password) as $char) {
10357 if ($char != $previouschar) {
10358 $consecutivecount = 1;
10359 } else {
10360 $consecutivecount++;
10361 if ($consecutivecount > $maxchars) {
10362 return false; // Check failed already.
10366 $previouschar = $char;
10369 return true;
10373 * Helper function to do partial function binding.
10374 * so we can use it for preg_replace_callback, for example
10375 * this works with php functions, user functions, static methods and class methods
10376 * it returns you a callback that you can pass on like so:
10378 * $callback = partial('somefunction', $arg1, $arg2);
10379 * or
10380 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10381 * or even
10382 * $obj = new someclass();
10383 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10385 * and then the arguments that are passed through at calltime are appended to the argument list.
10387 * @param mixed $function a php callback
10388 * @param mixed $arg1,... $argv arguments to partially bind with
10389 * @return array Array callback
10391 function partial() {
10392 if (!class_exists('partial')) {
10394 * Used to manage function binding.
10395 * @copyright 2009 Penny Leach
10396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10398 class partial{
10399 /** @var array */
10400 public $values = array();
10401 /** @var string The function to call as a callback. */
10402 public $func;
10404 * Constructor
10405 * @param string $func
10406 * @param array $args
10408 public function __construct($func, $args) {
10409 $this->values = $args;
10410 $this->func = $func;
10413 * Calls the callback function.
10414 * @return mixed
10416 public function method() {
10417 $args = func_get_args();
10418 return call_user_func_array($this->func, array_merge($this->values, $args));
10422 $args = func_get_args();
10423 $func = array_shift($args);
10424 $p = new partial($func, $args);
10425 return array($p, 'method');
10429 * helper function to load up and initialise the mnet environment
10430 * this must be called before you use mnet functions.
10432 * @return mnet_environment the equivalent of old $MNET global
10434 function get_mnet_environment() {
10435 global $CFG;
10436 require_once($CFG->dirroot . '/mnet/lib.php');
10437 static $instance = null;
10438 if (empty($instance)) {
10439 $instance = new mnet_environment();
10440 $instance->init();
10442 return $instance;
10446 * during xmlrpc server code execution, any code wishing to access
10447 * information about the remote peer must use this to get it.
10449 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10451 function get_mnet_remote_client() {
10452 if (!defined('MNET_SERVER')) {
10453 debugging(get_string('notinxmlrpcserver', 'mnet'));
10454 return false;
10456 global $MNET_REMOTE_CLIENT;
10457 if (isset($MNET_REMOTE_CLIENT)) {
10458 return $MNET_REMOTE_CLIENT;
10460 return false;
10464 * during the xmlrpc server code execution, this will be called
10465 * to setup the object returned by {@link get_mnet_remote_client}
10467 * @param mnet_remote_client $client the client to set up
10468 * @throws moodle_exception
10470 function set_mnet_remote_client($client) {
10471 if (!defined('MNET_SERVER')) {
10472 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10474 global $MNET_REMOTE_CLIENT;
10475 $MNET_REMOTE_CLIENT = $client;
10479 * return the jump url for a given remote user
10480 * this is used for rewriting forum post links in emails, etc
10482 * @param stdclass $user the user to get the idp url for
10484 function mnet_get_idp_jump_url($user) {
10485 global $CFG;
10487 static $mnetjumps = array();
10488 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10489 $idp = mnet_get_peer_host($user->mnethostid);
10490 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10491 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10493 return $mnetjumps[$user->mnethostid];
10497 * Gets the homepage to use for the current user
10499 * @return int One of HOMEPAGE_*
10501 function get_home_page() {
10502 global $CFG;
10504 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10505 // If dashboard is disabled, home will be set to default page.
10506 $defaultpage = get_default_home_page();
10507 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10508 if (!empty($CFG->enabledashboard)) {
10509 return HOMEPAGE_MY;
10510 } else {
10511 return $defaultpage;
10513 } else if ($CFG->defaulthomepage == HOMEPAGE_MYCOURSES) {
10514 return HOMEPAGE_MYCOURSES;
10515 } else {
10516 $userhomepage = (int) get_user_preferences('user_home_page_preference', $defaultpage);
10517 if (empty($CFG->enabledashboard) && $userhomepage == HOMEPAGE_MY) {
10518 // If the user was using the dashboard but it's disabled, return the default home page.
10519 $userhomepage = $defaultpage;
10521 return $userhomepage;
10524 return HOMEPAGE_SITE;
10528 * Returns the default home page to display if current one is not defined or can't be applied.
10529 * The default behaviour is to return Dashboard if it's enabled or My courses page if it isn't.
10531 * @return int The default home page.
10533 function get_default_home_page(): int {
10534 global $CFG;
10536 return !empty($CFG->enabledashboard) ? HOMEPAGE_MY : HOMEPAGE_MYCOURSES;
10540 * Gets the name of a course to be displayed when showing a list of courses.
10541 * By default this is just $course->fullname but user can configure it. The
10542 * result of this function should be passed through print_string.
10543 * @param stdClass|core_course_list_element $course Moodle course object
10544 * @return string Display name of course (either fullname or short + fullname)
10546 function get_course_display_name_for_list($course) {
10547 global $CFG;
10548 if (!empty($CFG->courselistshortnames)) {
10549 if (!($course instanceof stdClass)) {
10550 $course = (object)convert_to_array($course);
10552 return get_string('courseextendednamedisplay', '', $course);
10553 } else {
10554 return $course->fullname;
10559 * Safe analogue of unserialize() that can only parse arrays
10561 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10562 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10563 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10565 * @param string $expression
10566 * @return array|bool either parsed array or false if parsing was impossible.
10568 function unserialize_array($expression) {
10569 $subs = [];
10570 // Find nested arrays, parse them and store in $subs , substitute with special string.
10571 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10572 $key = '--SUB' . count($subs) . '--';
10573 $subs[$key] = unserialize_array($matches[2]);
10574 if ($subs[$key] === false) {
10575 return false;
10577 $expression = str_replace($matches[2], $key . ';', $expression);
10580 // Check the expression is an array.
10581 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10582 return false;
10584 // Get the size and elements of an array (key;value;key;value;....).
10585 $parts = explode(';', $matches1[2]);
10586 $size = intval($matches1[1]);
10587 if (count($parts) < $size * 2 + 1) {
10588 return false;
10590 // Analyze each part and make sure it is an integer or string or a substitute.
10591 $value = [];
10592 for ($i = 0; $i < $size * 2; $i++) {
10593 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10594 $parts[$i] = (int)$matches2[1];
10595 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10596 $parts[$i] = $matches3[2];
10597 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10598 $parts[$i] = $subs[$parts[$i]];
10599 } else {
10600 return false;
10603 // Combine keys and values.
10604 for ($i = 0; $i < $size * 2; $i += 2) {
10605 $value[$parts[$i]] = $parts[$i+1];
10607 return $value;
10611 * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10613 * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10614 * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10615 * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10617 * @param string $input
10618 * @return stdClass
10620 function unserialize_object(string $input): stdClass {
10621 $instance = (array) unserialize($input, ['allowed_classes' => [stdClass::class]]);
10622 return (object) $instance;
10626 * The lang_string class
10628 * This special class is used to create an object representation of a string request.
10629 * It is special because processing doesn't occur until the object is first used.
10630 * The class was created especially to aid performance in areas where strings were
10631 * required to be generated but were not necessarily used.
10632 * As an example the admin tree when generated uses over 1500 strings, of which
10633 * normally only 1/3 are ever actually printed at any time.
10634 * The performance advantage is achieved by not actually processing strings that
10635 * arn't being used, as such reducing the processing required for the page.
10637 * How to use the lang_string class?
10638 * There are two methods of using the lang_string class, first through the
10639 * forth argument of the get_string function, and secondly directly.
10640 * The following are examples of both.
10641 * 1. Through get_string calls e.g.
10642 * $string = get_string($identifier, $component, $a, true);
10643 * $string = get_string('yes', 'moodle', null, true);
10644 * 2. Direct instantiation
10645 * $string = new lang_string($identifier, $component, $a, $lang);
10646 * $string = new lang_string('yes');
10648 * How do I use a lang_string object?
10649 * The lang_string object makes use of a magic __toString method so that you
10650 * are able to use the object exactly as you would use a string in most cases.
10651 * This means you are able to collect it into a variable and then directly
10652 * echo it, or concatenate it into another string, or similar.
10653 * The other thing you can do is manually get the string by calling the
10654 * lang_strings out method e.g.
10655 * $string = new lang_string('yes');
10656 * $string->out();
10657 * Also worth noting is that the out method can take one argument, $lang which
10658 * allows the developer to change the language on the fly.
10660 * When should I use a lang_string object?
10661 * The lang_string object is designed to be used in any situation where a
10662 * string may not be needed, but needs to be generated.
10663 * The admin tree is a good example of where lang_string objects should be
10664 * used.
10665 * A more practical example would be any class that requries strings that may
10666 * not be printed (after all classes get renderer by renderers and who knows
10667 * what they will do ;))
10669 * When should I not use a lang_string object?
10670 * Don't use lang_strings when you are going to use a string immediately.
10671 * There is no need as it will be processed immediately and there will be no
10672 * advantage, and in fact perhaps a negative hit as a class has to be
10673 * instantiated for a lang_string object, however get_string won't require
10674 * that.
10676 * Limitations:
10677 * 1. You cannot use a lang_string object as an array offset. Doing so will
10678 * result in PHP throwing an error. (You can use it as an object property!)
10680 * @package core
10681 * @category string
10682 * @copyright 2011 Sam Hemelryk
10683 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10685 class lang_string {
10687 /** @var string The strings identifier */
10688 protected $identifier;
10689 /** @var string The strings component. Default '' */
10690 protected $component = '';
10691 /** @var array|stdClass Any arguments required for the string. Default null */
10692 protected $a = null;
10693 /** @var string The language to use when processing the string. Default null */
10694 protected $lang = null;
10696 /** @var string The processed string (once processed) */
10697 protected $string = null;
10700 * A special boolean. If set to true then the object has been woken up and
10701 * cannot be regenerated. If this is set then $this->string MUST be used.
10702 * @var bool
10704 protected $forcedstring = false;
10707 * Constructs a lang_string object
10709 * This function should do as little processing as possible to ensure the best
10710 * performance for strings that won't be used.
10712 * @param string $identifier The strings identifier
10713 * @param string $component The strings component
10714 * @param stdClass|array $a Any arguments the string requires
10715 * @param string $lang The language to use when processing the string.
10716 * @throws coding_exception
10718 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10719 if (empty($component)) {
10720 $component = 'moodle';
10723 $this->identifier = $identifier;
10724 $this->component = $component;
10725 $this->lang = $lang;
10727 // We MUST duplicate $a to ensure that it if it changes by reference those
10728 // changes are not carried across.
10729 // To do this we always ensure $a or its properties/values are strings
10730 // and that any properties/values that arn't convertable are forgotten.
10731 if ($a !== null) {
10732 if (is_scalar($a)) {
10733 $this->a = $a;
10734 } else if ($a instanceof lang_string) {
10735 $this->a = $a->out();
10736 } else if (is_object($a) or is_array($a)) {
10737 $a = (array)$a;
10738 $this->a = array();
10739 foreach ($a as $key => $value) {
10740 // Make sure conversion errors don't get displayed (results in '').
10741 if (is_array($value)) {
10742 $this->a[$key] = '';
10743 } else if (is_object($value)) {
10744 if (method_exists($value, '__toString')) {
10745 $this->a[$key] = $value->__toString();
10746 } else {
10747 $this->a[$key] = '';
10749 } else {
10750 $this->a[$key] = (string)$value;
10756 if (debugging(false, DEBUG_DEVELOPER)) {
10757 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10758 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10760 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10761 throw new coding_exception('Invalid string compontent. Please check your string definition');
10763 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10764 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10770 * Processes the string.
10772 * This function actually processes the string, stores it in the string property
10773 * and then returns it.
10774 * You will notice that this function is VERY similar to the get_string method.
10775 * That is because it is pretty much doing the same thing.
10776 * However as this function is an upgrade it isn't as tolerant to backwards
10777 * compatibility.
10779 * @return string
10780 * @throws coding_exception
10782 protected function get_string() {
10783 global $CFG;
10785 // Check if we need to process the string.
10786 if ($this->string === null) {
10787 // Check the quality of the identifier.
10788 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10789 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);
10792 // Process the string.
10793 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10794 // Debugging feature lets you display string identifier and component.
10795 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10796 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10799 // Return the string.
10800 return $this->string;
10804 * Returns the string
10806 * @param string $lang The langauge to use when processing the string
10807 * @return string
10809 public function out($lang = null) {
10810 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10811 if ($this->forcedstring) {
10812 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10813 return $this->get_string();
10815 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10816 return $translatedstring->out();
10818 return $this->get_string();
10822 * Magic __toString method for printing a string
10824 * @return string
10826 public function __toString() {
10827 return $this->get_string();
10831 * Magic __set_state method used for var_export
10833 * @param array $array
10834 * @return self
10836 public static function __set_state(array $array): self {
10837 $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10838 $tmp->string = $array['string'];
10839 $tmp->forcedstring = $array['forcedstring'];
10840 return $tmp;
10844 * Prepares the lang_string for sleep and stores only the forcedstring and
10845 * string properties... the string cannot be regenerated so we need to ensure
10846 * it is generated for this.
10848 * @return string
10850 public function __sleep() {
10851 $this->get_string();
10852 $this->forcedstring = true;
10853 return array('forcedstring', 'string', 'lang');
10857 * Returns the identifier.
10859 * @return string
10861 public function get_identifier() {
10862 return $this->identifier;
10866 * Returns the component.
10868 * @return string
10870 public function get_component() {
10871 return $this->component;
10876 * Get human readable name describing the given callable.
10878 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10879 * It does not check if the callable actually exists.
10881 * @param callable|string|array $callable
10882 * @return string|bool Human readable name of callable, or false if not a valid callable.
10884 function get_callable_name($callable) {
10886 if (!is_callable($callable, true, $name)) {
10887 return false;
10889 } else {
10890 return $name;
10895 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10896 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10897 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10898 * such as site registration when $CFG->wwwroot is not publicly accessible.
10899 * Good thing is there is no false negative.
10900 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10902 * @return bool
10904 function site_is_public() {
10905 global $CFG;
10907 // Return early if site admin has forced this setting.
10908 if (isset($CFG->site_is_public)) {
10909 return (bool)$CFG->site_is_public;
10912 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10914 if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10915 $ispublic = false;
10916 } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10917 $ispublic = false;
10918 } else if (($address = \core\ip_utils::get_ip_address($host)) && !ip_is_public($address)) {
10919 $ispublic = false;
10920 } else {
10921 $ispublic = true;
10924 return $ispublic;